Implementing a derivative in C/C++ with finite differences
Codemia Knowledge Hub ·
In C or C++ you normally compute a derivative numerically with finite differences: evaluate the function at points near x and estimate the slope from those values. Symbolic math or an automatic differentiation library is only needed for special cases. Central difference is usually the best default because it is more accurate than forward or backward difference for the same step size.
Forward, backward and central difference
The three classic approximations, computed side by side:
For f(x) = x * x at x = 3, the true derivative is 6, which makes this an easy correctness check.
Choosing the step size h
h is a real numerical decision. Too large and the approximation is crude. Too small and floating-point cancellation sets in, because you subtract nearly equal numbers and lose precision.
In practice:
- Start with
1e-5or1e-6fordouble. - Test against functions with known derivatives.
- Tune for the scale of your input values.
sin(x) is a useful test function:
Comparing the result to cos(x) shows how your chosen h behaves.
Plain C with function pointers
A function pointer is all a C implementation needs:
This style suits embedded or low-dependency code where you want a small, explicit interface.
Designing the helper's interface
Derivative helpers tend to end up inside optimization, root finding or simulation code, so decide on:
- Function pointer or callable input.
- An explicit step size parameter.
- Control over the numeric type, such as
floatordouble.
In modern C++, templates avoid the overhead of wrapping callables in std::function, but the simpler interface is fine for many applications unless profiling says otherwise.
Second derivative
Once the first derivative works, the second derivative follows the same pattern:
This is useful for curvature analysis and for optimization routines that need local shape information.
Testing against known derivatives
Check any numerical derivative against analytic results. Good test functions:
x^2, derivative2xsin(x), derivativecos(x)exp(x), derivativeexp(x)
These tests verify both the formula and the step size before the code goes into a larger numeric system.
Mistakes to avoid
- Picking a step size without testing it.
- Using forward difference when central difference would be more accurate.
- Expecting exact results despite floating-point limits.
- Using numerical differentiation where symbolic or automatic differentiation is actually required.
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 courseNo course covers this one yet
Basis Lab writes one for you from a sentence about what you want to be able to do, then teaches it and checks you understood. Your first course is free.
Build my courseData Structures & Algorithms practice on Codemia
Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.