import numpy as np
from scipy.optimize import curve_fit, leastsq, least_squares
import matplotlib.pyplot as plt
def g(x, a, b):
return 10 * a / (10 * b) + (a - 10 * b) * np.exp(-a * np.sin(x))
x = np.arange(1, 21)
a = 1.1
b = 0.01
y = g(x, a, b)
def g_fit(x, a, b):
return 10 * a / (10 * b) + (a - 10 * b) * np.exp(-a * np.sin(x))
popt, _ = curve_fit(g_fit, x, y)
print("curve_fit 拟合结果:", popt)
def residuals(params, x, y):
a, b = params
return y - g(x, a, b)
initial_guess = [1, 1]
result = leastsq(residuals, initial_guess, args=(x, y))
print("leastsq 拟合结果:", result[0])
def fun(params, x, y):
a, b = params
return g(x, a, b) - y
initial_guess = np.array([1, 1])
result = least_squares(fun, initial_guess, args=(x, y))
print("least_squares 拟合结果:", result.x)
x_fit = np.linspace(1, 20, 100)
y_fit_curve_fit = g_fit(x_fit, *popt)
y_fit_leastsq = g(x_fit, *result[0])
y_fit_least_squares = g(x_fit, *result.x)
plt.plot(x, y, 'o', label='原始数据')
plt.plot(x_fit, y_fit_curve_fit, label='curve_fit 拟合曲线')
plt.plot(x_fit, y_fit_leastsq, label='leastsq 拟合曲线')
plt.plot(x_fit, y_fit_least_squares, label='least_squares 拟合曲线')
plt.xlabel('x')
plt.ylabel('y')
plt.title('函数拟合结果')
plt.legend()
plt.show()