import numpy as np
import matplotlib.pylab as plt
def numerical_diff(f, x):
h = 1e-04
return (f(x + h) - f(x - h)) / (2 * h)
def function_1(x):
return 0.01 * x ** 2 + 0.1 * x
def tangent_line(f, x):
d = numerical_diff(f, x)
print(d)
b = f(x) - d * x
return lambda t: d*t + b
"""注意:tangent_line函数在画图时,调用numerical_diff函数是为了求得导数,故不能将数组x带入function_1中"""
x = np.arange(0, 20, 0.1)
y = function_1(x)
plt.plot(x, y)
plt.xlabel('x', fontsize=14)
plt.ylabel('f(x)', fontsize=14)
plt.title('y=0.01x^2+0.1x')
tf = tangent_line(function_1, 5)
y2 = tf(x)
plt.plot(x, y2)
tf2 = tangent_line(function_1, 10)
y3 = tf2(x)
plt.plot(x, y3)
plt.show()
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/a058283e7a9ebdecf34c932cfc1ce1b8.png)
tf = tangent_line(function_1, 5)
y2 = tf(x)
- 这段代码很重要,不能采用function_1(x),因为x为数组,而这里得函数要在特定点求导数
- tf获得函数形式
- y2 = tf(x): 还需要给函数的参量t赋值形成图形