在 Python 中获取 Legendre 级数与数据的最小二乘拟合
要获取 Legendre 级数与数据的最小二乘拟合,请使用 Python numpy 中的 legendre.legfit() 方法。该方法返回从低到高排序的 Legendre 系数。如果 y 是二维的,则 y 的第 k 列中数据的系数位于第 k 列。
参数 x 是 M 个样本(数据)点 (x[i], y[i]) 的 x 坐标。参数 y 是样本点的 y 坐标。通过为 y 传递一个每列包含一个数据集的二维数组,只需调用一次 polyfit 即可(独立地)拟合共享相同 x 坐标的几组样本点。
参数 deg 是拟合多项式的度数。如果 deg 是单个整数,则拟合中包括 deg 项之前的所有项。参数 rcond 是拟合的相对条件数。相对于最大奇异值,小于 rcond 的奇异值将被忽略。默认值为 len(x)*eps,其中 eps 是平台浮点类型的相对精度,在大多数情况下约为 2e-16。参数 full 是确定返回值性质的开关。当为 False(默认值)时,仅返回系数;当为 True 时,还会返回奇异值分解的诊断信息。
参数 w 是权重。如果不是 None,则权重 w[i] 适用于 x[i] 处的未平方残差 y[i] - y_hat[i]。理想情况下,权重的选择应使乘积 w[i]*y[i] 的误差都具有相同的方差。使用逆方差加权时,使用 w[i] = 1/sigma(y[i])。默认值为None。
步骤
首先,导入所需的库 −
import numpy as np from numpy.polynomial import legendre as L
x坐标 −
x = np.linspace(-1,1,51)
显示x坐标 −
print("X坐标...\n",x)
y坐标 −
y = x**3 - x + np.random.randn(len(x))
print("\nY坐标...\n",y)
要获取 Legendre 级数与数据的最小二乘拟合,请使用 Python numpy 中的 legendre.legfit() 方法。该方法返回从低到高排序的 Legendre 系数。如果 y 是二维的,则 y 的第 k 列数据的系数位于第 k 列 −
c, stats = L.legfit(x,y,3,full=True)
print("\n结果...\n",c)
print("\n结果...\n",stats)
示例
import numpy as np
from numpy.polynomial import legendre as L
# x 坐标
x = np.linspace(-1,1,51)
# 显示 x 坐标
print("X 坐标...\n",x)
# y 坐标
y = x**3 - x + np.random.randn(len(x))
print("\nY 坐标...\n",y)
# 要获取 Legendre 级数与数据的最小二乘拟合,请使用 Python numpy 中的 legendre.legfit() 方法
c, stats = L.legfit(x,y,3,full=True)
print("\n结果...\n",c)
print("\n结果...\n",stats)
输出
X Co-ordinate...
[-1. -0.96 -0.92 -0.88 -0.84 -0.8 -0.76 -0.72 -0.68 -0.64 -0.6 -0.56
-0.52 -0.48 -0.44 -0.4 -0.36 -0.32 -0.28 -0.24 -0.2 -0.16 -0.12 -0.08
-0.04 0. 0.04 0.08 0.12 0.16 0.2 0.24 0.28 0.32 0.36 0.4
0.44 0.48 0.52 0.56 0.6 0.64 0.68 0.72 0.76 0.8 0.84 0.88
0.92 0.96 1. ]
Y Co-ordinate...
[-5.28795520e-02 -7.61252904e-03 7.35194215e-02 -1.33072588e-01
-1.21785636e+00 7.75679385e-02 6.55168668e-01 1.42872448e+00
8.42326214e-01 2.49667989e+00 9.58942508e-01 -2.67332869e-01
-7.85575928e-01 1.93333045e+00 7.32492468e-01 5.23576961e-01
-1.91529521e+00 -1.41434385e+00 4.44787373e-01 3.81831261e-01
3.74128321e-01 1.20562789e+00 1.44870029e+00 1.01091575e-03
8.94334713e-01 1.22342199e+00 9.52055370e-01 -7.29520012e-01
-2.42648820e-01 -9.78434555e-02 1.27468237e-01 9.39489448e-01
1.08795136e+00 2.31230197e+00 1.93107556e-02 -6.13335407e-01
1.93170835e-01 -8.77958854e-01 -3.59868085e-01 4.31331759e-01
7.24929856e-01 -2.22736540e-01 -1.29623093e+00 4.13226024e-01
7.82155644e-01 -1.56618537e-01 1.25043737e+00 6.32386988e-01
-2.75716271e-01 8.80669895e-02 -3.20225560e-01]
结果...
[ 0.29249467 -0.10521942 -0.24847572 0.2010877 ]
结果...
[array([39.35467561]), 4, array([1.0425003 , 1.02126704, 0.97827074, 0.95561139]), 1.1324274851176597e-14]
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

