先定义牛顿插值函数,输入插值点和我拟合的点,毕竟是拟合光滑曲线,而画图都是点点相连,所以拟合点越多,曲线越光滑。
import matplotlib.pyplot as plt
import numpy as np
def newton_interpolation(X,Y,x):
"""
计算x点的插值
"""
sum=Y[0]
temp=np.zeros((len(X),len(X)))
for i in range(0,len(X)):
temp[i,0]=Y[i]
temp_sum=1.0
for i in range(1,len(X)):
temp_sum=temp_sum*(x-X[i-1])
for j in range(i,len(X)):
temp[j,i]=(temp[j,i-1]-temp[j-1,i-1])/(X[j]-X[j-i])
sum+=temp_sum*temp[i,i]
return sum
然后画图拟合:
plt.figure(figsize=(16,9))
plt.title("newton_interpolation")
color = ['green','red','purple']
for j,i in enumerate([5,9,11]):
X = np.linspace(-5, 5, num= i)
Y= np.array(1 / (1 + X * X))
xs=np.linspace(np.min(X),np.max(X),1000,endpoint=True)
ys=[]
for x in xs:
ys.append(newton_interpolation(X,Y,x))
plt.plot(X,Y,'s',label=f"n={i-1}", color=color[j])
plt.plot(xs,ys,label='', color=color[j])
xs=np.linspace(-5,5,100,endpoint=True)
plt.plot(xs,np.array(1 / (1 + xs * xs)),'b',label='y=1 / (1 + x^2)')
plt.xlabel('x')
plt.ylabel('y')
plt.legend(loc=4)
漂亮的龙格现象就体现出来了~ 需要不同的阶次,只需要修改enumerate([5,9,11])里的数值就可以了!
|