Exercise for the course Python for MATLAB users, by Olivier Verdier

In [1]:
%pylab
%matplotlib inline
Using matplotlib backend: MacOSX
Populating the interactive namespace from numpy and matplotlib

A numerical derivative of a function $f$ is a formula of the type $$ f'(x_0) \simeq \frac{f(x_0+h/2) - f(x_0-h/2)}{h} $$

Implement a function derivator which returns the derivative function.

In [2]:
def derivator(f, h):
    def df(x):
        return (f(x+h/2) - f(x - h/2))/h
    return df
In [3]:
msin_ = derivator(cos, 1e-10)
In [4]:
assert(allclose(msin_(0), 0))
assert(allclose(msin_(pi), 0))
assert(allclose(msin_(pi/2), -1.))