# Calculus with python: Derivatives

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:

$\displaystyle lim_{h \to 0} \dfrac{f(x+h) - f(x)}{h}$

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

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:

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:

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

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:

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.

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?

See you later