Lesson 2 of 18

The Derivative

The Derivative

The derivative of ff at xx is the instantaneous rate of change — the slope of the tangent line at that point:

f(x)=limh0f(x+h)f(x)hf'(x) = \lim_{h \to 0} \frac{f(x+h) - f(x)}{h}

Central Difference Formula

The forward difference f(x+h)f(x)h\frac{f(x+h) - f(x)}{h} has error O(h)O(h). The central difference is more accurate — error O(h2)O(h^2):

f(x)f(x+h)f(xh)2hf'(x) \approx \frac{f(x+h) - f(x-h)}{2h}

This is what you should implement. With h = 1e-6, results match analytic derivatives to 9+ significant figures.

Analytic Derivatives

For reference, the exact rules you can verify numerically:

FunctionDerivative
xnx^nnxn1n \cdot x^{n-1} (power rule)
sin(x)\sin(x)cos(x)\cos(x)
exe^xexe^x
ln(x)\ln(x)1x\frac{1}{x}
f(g(x))f(g(x))f(g(x))g(x)f'(g(x)) \cdot g'(x) (chain rule)

Verification

For f(x)=x2f(x) = x^2:

  • Analytic: f(2)=22=4f'(2) = 2 \cdot 2 = 4
  • Central difference: (2+h)2(2h)22h=8h2h=4\frac{(2+h)^2 - (2-h)^2}{2h} = \frac{8h}{2h} = 4 ✓ (exact, regardless of hh)

Your Task

Implement double derivative(double (*f)(double), double x, double h) using the central difference formula.

TCC compiler loading...
Loading...
Click "Run" to execute your code.