import math
import numpy as np
import matplotlib.pyplot as plt
What are derivatives?
Let’s create a random function
def f(x):
return 3 * x**2 - 4 * x + 5
= np.arange(-5, 5, 0.25)
xs = f(xs)
ys plt.plot(xs, ys)
The formula for derivative is….
\[\frac{df(x)}{dx} = \lim_{h \to 0} \frac{f(x+h) - f(x)}{h}\]
Nudging the function slightly and checking what it’s effect would be on the function
= 0.0001 # beware! don't make it too small! (why?)
h = 3.0
x + h) f(x), f(x
(20.0, 20.001400030000006)
We can quantify this nudge by taking their difference and dividing it by the nudge step (or “normalising” it by the step size 😉)
= (f(x + h) - f(x)) / h
dfdx dfdx
14.000300000063248
For a multi-variate funtion, we can nudge it with respect to any 1 variable
This wil help us look at the behaviour of the function when we change the value of any 1 variable slightly
Say \[f(x, y, z) = x^2 + y^2 + z^3\]
This can be differentiated wrt x, y or z
So we can look at \[\frac{df(x, y, z)}{dx} \ or\ \frac{df(x, y, z)}{dy} \ or\ \frac{df(x, y, z)}{dz}\]
Let’s say
= 0.0001
h
# inputs
= 2.0
a = -3.0
b = 10
c = a * b + c
d print(d)
4.0
We want to inspect what will happen to d
if we change a
slightly
= a * b + c
d1 += h
a = a * b + c
d2 print("d1:", d1)
print("d2:", d2)
print("slope:", (d2 - d1) / h)
d1: 4.0
d2: 3.999699999999999
slope: -3.000000000010772
Lets try with b
now
= a * b + c
d1 += h
b = a * b + c
d2 print("d1:", d1)
print("d2:", d2)
print("slope:", (d2 - d1) / h)
d1: 3.999699999999999
d2: 3.99990001
slope: 2.0001000000124947
Note: Slightly increasing a
decreases the value of d
but slightly increasing b
actually increases the value of d
. Here the “slope” or “gradient” or “derivative” tells us what is the magnitude of the change