import numpy as np from scipy.optimize import leastsq import matplotlib.pyplot as plt # 定义待拟合的函数形式 def func(x, coeffs): return coeffs[0] * np.sin(coeffs[1] * x) + coeffs[2] # 定义目标函数,即待拟合数据 def target_func(x): return 2.5 * np.sin(0.7 * x) + 1.2 # 生成带噪声的待拟合数据 np.random.seed(0) x_data = np.linspace(-10, 10, 100) y_data = target_func(x_data) + np.random.normal(0, 0.5, 100) # 定义误差函数,即最小二乘法的目标函数 def residuals(coeffs, y, x): return y - func(x, coeffs) # 初始参数的估计值 initial_coeffs = [1, 1, 1] # 使用最小二乘法拟合函数 result = leastsq(residuals, initial_coeffs, args=(y_data, x_data)) best_coeffs = result[0] # 打印拟合得到的系数 print("拟合得到的系数:", best_coeffs) # 绘制拟合结果 x_fit = np.linspace(-10, 10, 100) y_fit = func(x_fit, best_coeffs) plt.plot(x_data, y_data, 'bo', label='原始数据') plt.plot(x_fit, y_fit, 'r-', label='拟合曲线') plt.legend() plt.xlabel('x') plt.ylabel('y') plt.show()