1.代码实现
点击查看代码
import numpy as np
from scipy.optimize import curve_fit, least_squares
from scipy.linalg import lstsq
import matplotlib.pyplot as plt
def g(x, a, b):
return (10 * a) / (10 * b + (a - 10 * b) * np.exp(-a * np.sin(x)))
# 给定参数
a = 1.1
b = 0.01
x = np.arange(1, 21)
y = g(x, a, b)
# (1) 使用curve_fit拟合函数
def func(x, a, b):
return (10 * a) / (10 * b + (a - 10 * b) * np.exp(-a * np.sin(x)))
popt_curve_fit, pcov_curve_fit = curve_fit(func, x, y)
y_curve_fit = func(x, *popt_curve_fit)
# (2) 使用lstsq拟合函数
A = np.vstack([np.ones_like(x), np.sin(x)]).T
y_lstsq = lstsq(A, y)[0]
y_lstsq_fit = (10 * y_lstsq[0]) / (10 * y_lstsq[1] + (y_lstsq[0] - 10 * y_lstsq[1]) * np.exp(-y_lstsq[0] * np.sin(x)))
# (3) 使用least_squares拟合函数
def residuals(p, x, y):
a, b = p
return g(x, a, b) - y
p0 = [1, 1]
result = least_squares(residuals, p0, args=(x, y))
y_least_squares = g(x, result.x[0], result.x[1])
# 绘图
plt.scatter(x, y, label='Original Data')
plt.plot(x, y_curve_fit, label='curve_fit')
plt.plot(x, y_lstsq_fit, label='lstsq')
plt.plot(x, y_least_squares, label='least_squares')
plt.xlabel('x')
plt.ylabel('y')
plt.title('Fitting Results')
plt.legend()
plt.show()
2.运行结果