7.7 g(x)=(10a)/(10b+(a-10b)e^(asinx)),取a=1.1,b=0.01,计算x=1,2,...,20时,g(x)对应的函数值,把这样得到的数据作为模拟观测值,记作(xi,yi)(其中i为x,y的下标),i=1,2,...,20。用curve_fit拟合函数g(x)。用leastsq拟合函数g(x)。用least_squares拟合函数g(x)
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit, leastsq, least_squares
from scipy.constants import e
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})")
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)
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)
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("\ncurve_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("学号后四位:3004")