Today we’ll write a program in python to calculate the derivative of a function.

The definition of the derivative of a function f is:

We’ll deal with the limit later. For now, let’s just code in the formula:

1 2 |
def derivative(func, x, h): return (func(x+h) - func(x))/h |

This function takes in a function
f, the point at which the derivative should be calculated
x, and a parameter
h. We make *
h tend to *
<em>0</em> by giving it a very small value.

Let’s test this function:

1 2 3 4 5 6 7 8 |
In [15]: derivative(sin, 0, 0.000001) Out[15]: 0.9999999999998334 In [16]: derivative(sin, pi/2, 0.000001) Out[16]: -0.0001041732256013006 In [17]: derivative(sin, pi, 0.000001) Out[17]: -0.9999999785396789 |

It works. Derivative of sin is almost 1 at 0 , almost 0 at π/2 and almost -1 at π.

We can safely hardcode the value of h. The optimal value of h doesn’t really depend on anything other than the floating point precision on the platform we’re working on (python runtime in the current case).

Doing that would change the derivative implementation to:

1 2 3 |
def derivative(func, x): h = 0.00001 return (func(x+h) - func(x))/h |

Now it’s a bit easier to use our function:

1 2 3 4 5 6 7 8 |
In [15]: derivative(sin, 0) Out[15]: 0.9999999999998334 In [16]: derivative(sin, pi/2) Out[16]: -0.0001041732256013006 In [17]: derivative(sin, pi) Out[17]: -0.9999999785396789 |

But it still looks a weird. The derivative operation takes a function as input and returns another function as output, which is the derivative of input function. Instead, our implementation takes a function and a value, and evaluates and returns the derivative at that value immediately. There’s a way to fix that as well:

1 2 3 4 5 |
def derivative(func): h = 0.00001 def result(x): return (func(x+h) - func(x))/h return result |

That’s much better. Now whenever we call this function, it defines a function ( result) at runtime, which when called with an argument x, evaluates to the derivative of func at x.

#### How do we use this function?

Similar to the derivative operation of mathematica.

1 2 3 4 5 6 7 8 9 10 |
In [43]: derivativeOfSin = derivative(sin) In [44]: derivativeOfSin(0) Out[44]: 0.9999999999833332 In [45]: derivativeOfSin(pi/2) Out[45]: -0.00010867320376917176 In [46]: derivativeOfSin(pi) Out[46]: -0.9999999774568861 |

derivative takes a function func as input, and returns another function which when called, evaluates and returns the rate of change of func. Can you guess how do we calculate the double derivative of a function?

1 |
derivative(derivative(func)) |

See you later