Implementing the derivative in C/C
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
Introduction
In C or C++, derivatives are usually implemented numerically unless you are building symbolic math software or using an automatic differentiation library. The standard approach is finite differences, where you sample a function near a point and estimate the slope from those nearby values.
Start with Finite Difference Methods
The three classic approximations are:
- Forward difference.
- Backward difference.
- Central difference.
Central difference is often the best default because it is usually more accurate than forward or backward difference for the same step size.
Here is a simple C++ example that computes all three:
For f(x) = x * x at x = 3, the true derivative is 6, so this is an easy correctness check.
Why Step Size Matters
Choosing h is a real numerical decision. If h is too large, the approximation is crude. If h is too small, floating-point cancellation becomes a problem because you subtract nearly equal numbers and lose precision.
Practical rule:
- Start with something like
1e-5or1e-6fordouble. - Test against functions with known derivatives.
- Tune based on the scale of your input values.
For example, sin(x) is a useful test function:
Comparing the approximation to cos(x) gives you a practical sense of how the chosen h behaves.
A C-Style Version with Function Pointers
If you need a plain C implementation, function pointers are enough.
This style is useful in embedded or low-dependency code where you want a small, explicit interface.
Higher-Level Design Choices
Derivative helpers often end up inside optimization, root finding, or simulation code, so the interface matters:
- Function pointer or callable input.
- Explicit step size parameter.
- Numeric type control such as
floatordouble.
In modern C++, templates can reduce overhead by avoiding std::function wrapping, but for many applications the simpler interface is acceptable unless profiling proves otherwise.
Second Derivative and Extensions
Once the first derivative helper is correct, extending it to a second derivative is straightforward.
This kind of helper is useful in curvature analysis and in optimization routines that need local shape information.
Validate Against Known Functions
Any numerical derivative implementation should be checked against analytic results when possible. Good test functions include:
- '
x^2, derivative2x' - '
sin(x), derivativecos(x)' - '
exp(x), derivativeexp(x)'
Those tests help you verify both the formula and the chosen step size before the code is used in a larger numeric system.
Common Pitfalls
- Using a step size that is too large or too small without testing.
- Assuming forward difference is accurate enough when central difference would be better.
- Forgetting floating-point limits and expecting exact results.
- Using numerical differentiation where symbolic or automatic differentiation is actually required.
- Skipping validation against functions with known derivatives.
Summary
- Numerical derivatives in C or C++ are usually implemented with finite differences.
- Central difference is often the best default for first derivatives.
- Step size
hstrongly affects accuracy and stability. - Both C-style function pointers and C++ callables work well for derivative helpers.
- Always validate the implementation against known analytic derivatives before trusting production results.
Related reading
- Implicit instantiation of undefined template ''stdbasic_stringchar, stdchar_traitschar, stdallocatorchar ''
- Import OpenCV Mat into C Tensorflow without copying
- Internal Implementation of STLMAP in C
- Is armadillo solve thread safe?
- Is it legal to initialize a thread_local variable in the destructor of a global variable?
- Is it legal to pass stdshared_future as a reference to functions?
- Is it more efficient to copy a vector by reserving and copying, or by creating and swapping?
- Is it OK to call stdasync at high frequency?
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.