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)):
#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
计算n等于4、8、12时y=cos(x)的插值图像:
plt.figure(figsize=(16,9))
plt.title("newton_interpolation")
color = ['green','red','purple']
for j,i in enumerate([5,9,13]):
X = np.linspace(-4.5, 4.5, num= i)
Y= np.cos(X)
xs=np.linspace(np.min(X),np.max(X),100,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(-4,4,100,endpoint=True)
plt.plot(xs,np.cos(xs),'b',label='y=cos(x)')#原曲线
plt.xlabel('x')
plt.ylabel('y')
plt.legend(loc=1)#指定legend的位置右下角
计算n等于4、8、12时y=1 / (1 + e^(-x))的插值图像:
e = 2.718281828
plt.figure(figsize=(16,9))
plt.title("newton_interpolation")
color = ['green','red','purple']
for j,i in enumerate([5,9,13]):
X = np.linspace(-10.1, 10.1, num= i)
Y= np.array(1 / (1 + np.exp(-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(-10,10,100,endpoint=True)
plt.plot(xs,np.array(1 / (1 + np.exp(-xs))),'b',label='y=1 / (1 + e^(-x))')#原曲线
plt.xlabel('x')
plt.ylabel('y')
plt.legend(loc=2)#指定legend的位置右下角
标签:plt,temp,插值法,sum,牛顿,Python,np,xs,color
From: https://www.cnblogs.com/kemuling/p/17712484.html