C/C++ programming
derivative implementation
numerical methods
calculus in programming
coding tutorials

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:

cpp
1#include <cmath>
2#include <functional>
3#include <iostream>
4
5double forward_diff(const std::function<double(double)>& f, double x, double h) {
6    return (f(x + h) - f(x)) / h;
7}
8
9double backward_diff(const std::function<double(double)>& f, double x, double h) {
10    return (f(x) - f(x - h)) / h;
11}
12
13double central_diff(const std::function<double(double)>& f, double x, double h) {
14    return (f(x + h) - f(x - h)) / (2.0 * h);
15}
16
17int main() {
18    auto f = [](double x) { return x * x; };
19    double x = 3.0;
20    double h = 1e-5;
21
22    std::cout << "forward:  " << forward_diff(f, x, h) << '\n';
23    std::cout << "backward: " << backward_diff(f, x, h) << '\n';
24    std::cout << "central:  " << central_diff(f, x, h) << '\n';
25}

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-5 or 1e-6 for double.
  • Test against functions with known derivatives.
  • Tune for the scale of your input values.

sin(x) is a useful test function:

cpp
1#include <cmath>
2#include <functional>
3#include <iostream>
4
5double derivative(const std::function<double(double)>& f, double x, double h) {
6    return (f(x + h) - f(x - h)) / (2.0 * h);
7}
8
9int main() {
10    auto f = [](double x) { return std::sin(x); };
11    double x = 1.0;
12    double h = 1e-5;
13
14    std::cout << "approx: " << derivative(f, x, h) << '\n';
15    std::cout << "exact:  " << std::cos(x) << '\n';
16}

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:

c
1#include <math.h>
2#include <stdio.h>
3
4double central_diff(double (*f)(double), double x, double h) {
5    return (f(x + h) - f(x - h)) / (2.0 * h);
6}
7
8double cubic(double x) {
9    return x * x * x;
10}
11
12int main(void) {
13    double x = 2.0;
14    double h = 1e-5;
15    printf("approx derivative: %.10f\n", central_diff(cubic, x, h));
16    return 0;
17}

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 float or double.

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:

cpp
1#include <cmath>
2#include <functional>
3#include <iostream>
4
5double second_derivative(const std::function<double(double)>& f, double x, double h) {
6    return (f(x + h) - 2.0 * f(x) + f(x - h)) / (h * h);
7}
8
9int main() {
10    auto f = [](double x) { return x * x; };
11    std::cout << second_derivative(f, 3.0, 1e-5) << '\n';
12}

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, derivative 2x
  • sin(x), derivative cos(x)
  • exp(x), derivative exp(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.

Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Basis Lab
No 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 course
Data 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.

Practice algorithms