Numerical differentiation

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

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

Write a function numdiff(f, x, h) that uses the equation above to return the approximation of the derivative of a mathematical function represented by a function f(x).

Your function numdiff(f, x, h) should accept three arguments as inputs:

  • f: the name of the function to be differentiated
  • x: the value at which to differentiate f
  • h: the value of h to be used in the approximation equation above

Once written, you could use your function in the following way to approximate the derivative of x^{2} at x=3.0 using h=0.01 (this example is shown using Python):

numdiff(myfun, 3.0, 0.01)

where you have defined myfun as:

def myfun(x):
    return x*x

In this case numdiff(myfun, 3.0, 0.01) should return:

In [1]: numdiff(myfun, 3.0, 0.01)
Out[1]: 5.999999999999872

Use your function numdiff 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 true value, the value given by your function numdiff, and the error, i.e., the difference between the true value and your approximation. Use 10 decimal places of precision.

If you need help finding out what the true 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).

Hints

  • 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() in programming languages.
  • In Python logarithm base e is math.log() and logarithm base 10 is math.log10. You will need to import math to use them. The exponential function e^{x} in Python is math.exp(). The cosine function \cos in Python is math.cos(). Finally \pi in Python is math.pi.