Create A Derivative Calculator in Python

I first learned of derivatives in my sophomore year of high school. They astounded me. Its amazing that we can use infinity and limits to find certain slopes and rates of change. Of course I had to apply it to my computer science knowledge.

James Taylor

--

One of the formal definitions of derivatives is

Where f(x) is the function, a is the point to find the slope, f’(a) is slope at point. Essentially, this limit finds the rate of change between two points as those points become increasingly close to each other and converge to a point with no distance between each other (h=0)

I was inspired to create a derivative on my computer. A normal derivative like this would require algebra and I didn’t want to teach it algebra. Neither did my computer understand dividing by zero. That made things tricky.

I figured out that if we make h really small (h=0.00000000001) we could mimic the behaviors of plugging in zero without having to plug zero into the denominator and cause a lot of hullabaloo.

My modified equation looked like this.

This made it relatively simple. I just needed to have the function and I could perform the derivative. Granted it isn’t 100% accurate, but it is pretty close.

So then I started to implement my program. I needed some basic libraries such as math, so I could have our trignometric, exponential, and other advanced functions.

from math import *

I then proceded to create an equation that the computer could derive. It would take a value and then return the output of the function.

def f(x):
return x ** 2
#For instance f(2) = 4

Simple enough. Now we have to derive it. I created a new python function that would take two paraments. The first parameter was a function — like f — and the value at which to derive and find the slope. It was written like this.

def derive(function, value):
h = 0.00000000001
top = function(value + h) - function(value)
bottom = h
slope = top / bottom
# Returns the slope to the third decimal
return float("%.3f" % slope)

As you can see this works pretty well.

>>> derive(f, 2)
4.0

This is good because even though it is an approximation, it still calculates the correct slope at x = 2 for f(x) = x² by rounding to the nearest third decimal place

You can try this with other functions you want to define as well. For instance,

def g(x):
return sin(x) * cos(x) + exp(2*x) + 2*x**4 - 10

is the python version

When you run it in the python derive function at a value of x = -1, you get this.

>>> g(-1)
-8.319313430176228
>>> derive(g, -1)
-8.145

If you used a calculator, WolframAlpha, or your calculus skills, you would find that the slope of the function at x = -1 is actually -8.145

So now you know how to implement derivatives from calculus in a python program. See if you can compute the area under the curve from a to b (an integral) using similar logic!

--

--