By: Tao Steven Zheng
Import these libraries
import matplotlib.pyplot as plt
import numpy as np
Part 1: Calculating Derivatives on Python
def deriv(f,x):
h = 0.000000001 #step-size
return (f(x+h) - f(x))/h #definition of derivative
Part 2: Plot function with tangent
def tangent_line(f,x_0,a,b):
x = np.linspace(a,b,200)
y = f(x)
y_0 = f(x_0)
y_tan = deriv(f,x_0) * (x - x_0) + y_0
#plotting
plt.plot(x,y,'r-')
plt.plot(x,y_tan,'b-')
plt.axis([a,b,a,b])
plt.xlabel('x')
plt.ylabel('y')
plt.title('Plot of a function with tangent line')
plt.show()
Part 3: Tests and results
#Test number 1
def f1(x):
return x**2
tangent_line(f1,1,-2,2)
#Test number 2
def f2(x):
return np.exp(-x**2)
tangent_line(f2,1,-2,2)
Community content is available under CC-BY-SA unless otherwise noted.