數學建模習題7.7

VVV1發表於2024-11-17

`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")`

相關文章