数学建模__最小二乘法拟合参数Python实现

'''
拟合 y = p1 * x^2 + p2 * x + p3
'''

import numpy as np
from scipy.optimize import leastsq

def err(p, x, y):
    return (p[0]*x*x + p[1]*x + p[2] - y) * (p[0]*x*x + p[1]*x + p[2] - y)


#当数据中有明显偏差的值考虑去掉

p = [1,2,3]
Xi = np.array([2,-1, 0, 1, -2,3, -3,4,-4])
Yi = np.array([5.6,2.2, 1.1, 1.8, 4.8,9.5, 10.5,15.5,19.5])

print(len(Xi), len(Yi))

ret = leastsq(err, p, args = (Xi, Yi))

print(ret)


import matplotlib.pyplot as plt
a,b,c = ret[0]

#定义画布大小
plt.figure(figsize=(8,6))

#画出散点图
plt.scatter(Xi,Yi,color="red",label="Sample Point",linewidth=3)


#给定一个连续的x区间
x = np.linspace(-10,10,1000)
y = a*x*x + b*x + c

#画出拟合后的曲线
plt.plot(x,y,color="orange",label="Fitting Line",linewidth=2)
plt.legend()
plt.show()  

猜你喜欢

转载自blog.csdn.net/xdg15294969271/article/details/132898373
今日推荐