习题7.10(2)

1.代码实现

点击查看代码
import numpy as np
import pylab as plt

# 原始数据点
x0 = np.array([-2, -1.7, -1.4, -1.1, -0.8, -0.5, -0.2, 0.1, 0.4, 0.7, 1, 1.3, 1.6, 1.9, 2.2, 2.5, 2.8, 3.1, 3.4, 3.7, 4, 4.3, 4.6, 4.9])
y0 = np.array([0.1029, 0.1174, 0.1316, 0.1448, 0.1566, 0.1662, 0.1733, 0.1775, 0.1785, 0.1764, 0.1711, 0.1630, 0.1526, 0.1402,
               0.1266, 0.1122, 0.0977, 0.0835, 0.0702, 0.0588, 0.0479, 0.0373, 0.0291, 0.0224])
# 尝试不同的多项式阶次,这里从1到10阶
degrees = range(1, 11)
best_degree = None
best_coeffs = None
best_rmsd = np.inf
for degree in degrees:
    A = np.vander(x0, degree + 1)
    p = np.linalg.lstsq(A, y0, rcond=None)[0]
    # 计算拟合值
    y_pred = np.polyval(p, x0)
    # 计算剩余标准差(Root Mean Squared Deviation)
    residuals = y0 - y_pred
    rmsd = np.sqrt(np.mean(residuals ** 2))
    if rmsd < best_rmsd:
        best_degree = degree
        best_coeffs = p
        best_rmsd = rmsd
print(f"最佳多项式阶次为: {best_degree}")
print("相应多项式从高次到低次幂的系数为:", np.round(best_coeffs, 4))
print("剩余标准差为:", best_rmsd)
print("3014")
plt.plot(x0, y0, 'o')
xt = np.linspace(min(x0), max(x0), 100)
plt.plot(xt, np.polyval(best_coeffs, xt))
plt.show()

2.运行结果

posted on 2024-11-17 15:04  克卜勒星球  阅读(1)  评论(0编辑  收藏  举报

导航