import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit

# 自定义函数 e指数形式
# def func(x, a, b,c):
#     return a*np.sqrt(x)*(b*np.square(x)+c)

# 三次曲线方程
def f_3(x, A, B, C, D):
    return A * x * x * x + B * x * x + C * x + D

# 定义x、y散点坐标
x = [i+1 for i in range(10)]
x = np.array(x)
num = [0.5, 9.36, 52, 191, 350, 571, 912, 1207, 1682.69, 2135.00]
y = np.array(num)

# 非线性最小二乘法拟合
popt, pcov = curve_fit(f_3, x, y)
print('拟合误差为:{}'.format(pcov))
#获取popt里面是拟合系数
a = popt[0]
b = popt[1]
c = popt[2]
d = popt[3]
yvals = f_3(x,a,b,c, d) # 拟合y值
print('popt:', popt)
print('系数a:', a)
print('系数b:', b)
print('系数c:', c)
print('系数pcov:', pcov)
print('系数yvals:', yvals)

#绘图
plot1 = plt.plot(x, y, 's',label='original values')
plot2 = plt.plot(x, yvals, 'r',label='polyfit values')
plt.xlabel('x')
plt.ylabel('y')
plt.legend(loc=4) #指定legend的位置右下角
plt.title('curve_fit')
plt.show()

  

01-06 17:49