`import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit, leastsq, least_squares
定义函数 g(x, a, b)
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_values = np.arange(1, 21)
y_values = g(x_values, a, b)
打印生成的数据点
for i, (xi, yi) in enumerate(zip(x_values, y_values), start=1):
print(f"({xi}, {yi:.6f})")
使用 curve_fit 进行拟合
popt_curve_fit, pcov_curve_fit = curve_fit(g, x_values, y_values, p0=[a, b])
y_fit_curve_fit = g(x_values, *popt_curve_fit)
使用 leastsq 进行拟合
def func_leastsq(params, x, y):
return y - g(x, *params)
popt_leastsq = leastsq(func_leastsq, [a, b], args=(x_values, y_values))[0]
y_fit_leastsq = g(x_values, *popt_leastsq)
使用 least_squares 进行拟合
popt_least_squares = least_squares(func_leastsq, [a, b], args=(x_values, y_values)).x
y_fit_least_squares = g(x_values, *popt_least_squares)
打印拟合参数
print("curve_fit parameters:", popt_curve_fit)
print("leastsq parameters:", popt_leastsq)
print("least squares parameters:", popt_least_squares)
绘制结果
plt.figure(figsize=(10, 6))
plt.scatter(x_values, y_values, label='Simulated data', color='red')
plt.plot(x_values, y_fit_curve_fit, label='curve_fit', linestyle='-')
plt.plot(x_values, y_fit_leastsq, label='leastsq', linestyle='--')
plt.plot(x_values, y_fit_least_squares, label='least squares', linestyle='-.')
plt.xlabel('x')
plt.ylabel('g(x)')
plt.legend()
plt.title('Fitting of g(x) using curve_fit, leastsq, and least squares')
plt.grid(True)
plt.show()
print("学号后四位:3005")`