# -*- coding: utf-8 -*-
"""
Created on Sun Feb 16 10:19:23 2020
project name:
@author: 帅帅de三叔
"""
import math
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
#初始化画布
fig = plt.figure()
plt.grid(True)
#绘制一条正弦函数曲线
x = np.linspace(0, 7,100)
y = np.exp(x)
curve_ani, = plt.plot(x, y, color = 'red', alpha=0.8, label = '$y=e^x$') #指数函数曲线
point_ani, = plt.plot(0,0, color = 'red',alpha=0.5, marker='o') #切点
xtext_ani = plt.text(5.5,50,'',fontsize=12)#自变量
ytext_ani = plt.text(5.5,130,'',fontsize=12)#因变量
ktext_ani = plt.text(5.5,200,'',fontsize=12)#斜率
delta = 0.05 #用来控制精度
def gradient(x0): #x0处的切线斜率
num_min = np.exp(x0 - delta)
num_max = np.exp(x0 + delta)
k = (num_max - num_min) / (2*delta)
return k
def tangent_line(x0,y0,k): #过x0,y0的切线段
xs = np.linspace(x0 - 0.5,x0 + 0.5,100)
ys = y0 + k * (xs - x0) #切线方程
return xs,ys
k = gradient(x[0])
xs,ys = tangent_line(x[0],y[0],k)
tangent_ani, = plt.plot(xs,ys,c='blue',alpha=0.8)
def update(num):
k=gradient(x[num])
xs,ys = tangent_line(x[num],y[num],k)
tangent_ani.set_data(xs,ys)
point_ani.set_data(x[num],y[num])
xtext_ani.set_text('x=%.3f'%x[num])
ytext_ani.set_text('y =%.3f'%y[num])
ktext_ani.set_text('y\'=%.3f'%k)
return [point_ani,xtext_ani,ytext_ani,tangent_ani,k]
ani = animation.FuncAnimation(fig=fig,func=update,frames=np.arange(0,100),interval=200)
ani.save('D:\exponential.gif')
plt.legend()
plt.show()