多项式最小二乘法曲线拟合Python程序

多项式最小二乘法曲线拟合Python程序_第1张图片
多项式最小二乘法曲线拟合Python程序_第2张图片
在这里插入图片描述

#多项式最小二乘法曲线拟合
from numpy import *
from numpy.linalg import *
X = [1, 3, 4, 5, 6, 7, 8, 9, 10]
Y = [2, 7, 8, 10, 11, 11, 10, 9, 8]
n = len(X)
m = 2 #求m次方多项式, m<=n
A = zeros((m+1,m+1)) #创建零数组
B = zeros((m+1,1))

for i in range(m+1):
    y = 0
    for j in range(m+1):
        if i==0 and j== 0:
            A[0][0] = n
        else:
            x = 0
            for s in range(n):
                x += X[s]**(i+j)
            A[i][j] = x
    for s in range(n):
        y += X[s]**(i) * Y[s]
    B[i][0] = y
result = solve(A,B)
for i in range(m+1):
    a = result[i][0]
    print(f'a{i} = {a}')

结果:

a0 = -1.4596638655462273
a1 = 3.6053093964858673
a2 = -0.2675706646294881

你可能感兴趣的:(算法,python)