UP | HOME

Exercise 10

Numerical Differentiation

The following equation can be used to find an approximate derivative of a mathematical function \(f(x)\) if \(h\) is sufficiently small:

\begin{equation} f'(x) \approx \frac{f(x+h)-f(x-h)}{2h} \end{equation}

Write a function numdiff(f, x, h) that returns the approximation of the derivative of a mathematical function represented by a function f(x).

Apply this to differentiate:

  • \(f(x) = \left( e^{x} \right)\) at \(x=0\)
  • \(f(x) = \left( e^{-2x^{2}} \right)\) at \(x=1\)
  • \(f(x) = \left( \cos x \right)\) at \(x = \pi/2\)
  • \(f(x) = \left( \ln x \right)\) at \(x=1\)

Use \(h = 0.01\)

In each case write out the error, i.e., the difference between the exact derivative and the result of the approximation. Use 10 decimal places of precision.

If you need help finding out what the exact solutions to these derivatives are, (1) try to remember your calculus!, (2) ask a classmate, (3) google it, or (4) ask me (at which point I will direct you to WolframAlpha).

hint: the \(\ln()\) function (logarithm, base \(e\)) is typically called log() in programming languages like Python, MATLAB / Octave, R and C, whereas the logarithm, base 10 (typically referred to in math class as \(\mathrm{log}()\), is typically called log10().

solutions


Paul Gribble | fall 2014
This work is licensed under a Creative Commons Attribution 4.0 International License
Creative Commons License