import numpy as np
import matplotlib.pyplot as plt
# 牛顿插值函数
def newton_interpolation(x, y):
"""
param x: data points x
param y: data points y
return : the newton polynomial
"""
n = len(x)
# 生成一个 n * n 的零矩阵
coef_matrix = np.zeros((n, n))
coef_matrix[:, 0] = y
for i in range(1, n):
for j in range(n - i):
coef_matrix[j][i] = (coef_matrix[j + 1][i - 1] - coef_matrix[j][i - 1]) / (x[j + i] - x[j])
coefs = coef_matrix[0]
return np.polynomial.polynomial.Polynomial(np.polyfit(x, y, len(x) - 1))
# 绘制插值函数和数据点
def plot_func_and_points(filename, newton_poly, x, y, t, sigma):
"""
param filename: save the file
param newton_poly: the newton polynomial
param x: data points x
param y: data points y
param t: t range
param sigma: sigma range
"""
plt.plot(t, sigma, label='Interpolation Polynomial')
plt.scatter(x, y, color='red', label='Data Points')
plt.xlabel('T (℃)')
plt.ylabel('σ×10³(N/m)')
plt.title('Newton Interpolation')
plt.legend()
plt.grid()
plt.xlim(0, 100)
plt.ylim(0, 100)
plt.savefig(filename, dpi=300)
plt.show()
# 主函数
def main():
# 数据点
x = np.array([0, 20, 40, 60, 80])
y = np.array([78.2, 73.4, 70.2, 66.7, 63.2])
# 生成牛顿插值多项式
newton_poly = newton_interpolation(x, y)
print("插值多项式:")
print(newton_poly)
# 绘制图象
t = np.arange(0, 101, 1)
sigma = newton_poly(t)
plot_func_and_points("D:/网页下载/interpolation-result.png", newton_poly, x, y, t, sigma)
if __name__ == "__main__":
main()