11-20:课程小结--多项式拟合

import numpy as np
import matplotlib.pyplot as plt


x = np.arange(10)*0.1
fx = np.array([0.97,0.83,0.65,0.54,0.46,0.36,0.29,0.25,0.21,0.17])

p = 1
N = 6  # 阶数

def Neiji(p,a,b):
    '''
    加权内积,p为加权值
    '''
    return p*np.dot(a,b)

def Nihe(x,fx,p,N):
    '''
    多项式拟合函数
    (x,fx):给定的需要拟合的点
    p:加权内积的权重值
    N:多项式阶数
    '''
    A = np.zeros((N,N))
    b = np.zeros((N,1))
    for i in range(N):
        for j in range(N):
            A[i,j] = Neiji(p,x**i,x**j)
        b[i,0] = Neiji(p,fx,x**i)
    an = np.linalg.solve(A,b)             # 多项式拟合模型系数
    return an
    
an = Nihe(x,fx,p,N) 
xx = np.arange(min(x),max(x),0.01)       # 做图横坐标
result = np.sum([an[i]*(xx**i) for i in range(N)],axis=0)  # 拟合结果曲线
 
plt.scatter(x,fx,c='r')
plt.plot(xx,result)
plt.show()
6阶多项式拟合.png

推荐阅读更多精彩内容