Math & Physics Problems Wikia
Advertisement

By: Tao Steven Zheng (郑涛)

 1 import matplotlib.pyplot as plt
 2 import numpy as np
 3 
 4 '''Part 1: Calculating Derivatives on Python'''
 5 
 6      h = 0.000000001                 #step-size 
 7      return (f(x+h) - f(x))/h        #definition of derivative
 8 
 9 '''Part 2: Plot function with tangent'''
10  
11 def tangent_line(f,x_0,a,b):
12      x = np.linspace(a,b,200)
13      y = f(x) 
14      y_0 = f(x_0)
15      y_tan = deriv(f,x_0) * (x - x_0) + y_0 
16     
17    #plotting
18      plt.plot(x,y,'r-')
19      plt.plot(x,y_tan,'b-')
20      plt.axis([a,b,a,b])
21      plt.xlabel('x')     
22      plt.ylabel('y')    
23      plt.title('Plot of a function with tangent line') 
24      plt.show()    
25      
26 '''Part 3: Tests and results'''
27 #Test number 1
28 
29 def f1(x):
30      return x**2
31  
32  tangent_line(f1,1,-2,2)
33 
34 #Test number 2
35 
36  def f2(x):
37      return np.exp(-x**2)
38  
39  tangent_line(f2,1,-2,2)


Test 1

Tangent Plot Test1.png

Test 2

Tangent Graph Test2.png

Advertisement