import matplotlib.pyplot as plt
from pylab import mpl
import math
"""
牛顿插值法
插值的函数表为
xi -28.9, -12.2, 4.4, 21.1, 37.8
f(xi) 2.2, 3.9, 6.6, 10.3, 15.4
"""
x=[-28.9,-12.2,4.4,21.1,37.8]
y=[2.2,3.9,6.6,10.3,15.4]
"""计算4次差商的值"""
def Four_time_difference_quotient(x, y):
i = 0 # i记录计算差商的次数
quotient = [0, 0, 0, 0, 0,]
while i < 4:
j = 4
while j > i:
if i == 0:
quotient[j]=((y[j]-y[j-1])/(x[j]-x[j-1]))
else:
quotient[j] = (quotient[j]-quotient[j-1])/(x[j]-x[j-1-i])
j -= 1
i += 1
return quotient;
def function(data):
return x[0]+parameters[1]*(data-0.4)+parameters[2]*(data-0.4)*(data-0.55)+\
parameters[3]*(data-0.4)*(data-0.55)*(data-0.65)\
+parameters[4]*(data-0.4)*(data-0.55)*(data-0.80)
"""计算插值多项式的值和相应的误差"""
def calculate_data(x,parameters):
returnData=[];
for data in x:
returnData.append(function(data))
return returnData
"""画函数的图像
newData为曲线拟合后的曲线
"""
def draw(newData):
plt.scatter(x,y,label="离散数据",color="red")
plt.plot(x,newData,label="牛顿插值拟合曲线",color="black")
plt.scatter(0.596,function(0.596),label="预测函数点",color="blue")
plt.title("牛顿插值法")
mpl.rcParams['font.sans-serif'] = ['SimHei']
mpl.rcParams['axes.unicode_minus'] = False
plt.legend(loc="upper left")
plt.show()
parameters=Four_time_difference_quotient(x, y)
yuanzu=calculate_data(x,parameters)
draw(yuanzu)
![](https://video.ask-data.xyz/img.php?b=https://iknow-pic.cdn.bcebos.com/37d12f2eb9389b50fb1f16e28835e5dde6116e9a?x-bce-process=image%2Fresize%2Cm_lfit%2Cw_600%2Ch_800%2Climit_1%2Fquality%2Cq_85%2Fformat%2Cf_auto)