Lesson 16 of 18

Chain Rule

The Chain Rule

The chain rule handles derivatives of composed functions f(g(x))f(g(x)):

ddx[f(g(x))]=f(g(x))g(x)\frac{d}{dx}\bigl[f(g(x))\bigr] = f'(g(x)) \cdot g'(x)

Examples

h(x)h(x)ff, ggh(x)h'(x)
sin(x2)\sin(x^2)f=sinf=\sin, g=x2g=x^2cos(x2)2x\cos(x^2) \cdot 2x
e3xe^{3x}f=euf=e^u, g=3xg=3x3e3x3e^{3x}
x2+1\sqrt{x^2+1}f=uf=\sqrt{u}, g=x2+1g=x^2+1x/x2+1x/\sqrt{x^2+1}

Numerical Chain Derivative

We can approximate the chain derivative numerically using the central difference formula applied to the composition:

ddx[f(g(x))]f(g(x+h))f(g(xh))2h\frac{d}{dx}\bigl[f(g(x))\bigr] \approx \frac{f(g(x+h)) - f(g(x-h))}{2h}

This is just the standard central difference, but applied to the composed function fgf \circ g:

double chain_deriv(double (*f)(double), double (*g)(double),
                   double x, double h) {
    return (f(g(x + h)) - f(g(x - h))) / (2.0 * h);
}

Verification

For h(x)=sin(x2)h(x) = \sin(x^2) at x=1x = 1:

  • Analytic: h(1)=cos(12)21=2cos(1)1.0806h'(1) = \cos(1^2) \cdot 2 \cdot 1 = 2\cos(1) \approx 1.0806
  • Numerical with h=106h = 10^{-6}: should match to 4+ decimal places

Your Task

Implement double chain_deriv(f, g, x, h) using the central difference on the composition f(g(x))f(g(x)).

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