You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python拟合函数f(θ)=a+b·cos(θ-c)并求解最优系数

Hey there! Fitting a cosine function like f(θ) = a + b·cos(θ - c) to your data to minimize mean squared error is totally doable with Python's scipy.optimize.curve_fit—it's one of the most straightforward and efficient ways to handle this kind of nonlinear curve fitting. Let me walk you through a complete, working example.

Fitting f(θ) = a + b·cos(θ - c) for Minimum MSE

Step 1: Import the necessary libraries

We'll use numpy for array operations and data handling, scipy.optimize.curve_fit for the fitting logic, and matplotlib (optional) to visualize how well the fit matches your data.

import numpy as np
from scipy.optimize import curve_fit
import matplotlib.pyplot as plt

Step 2: Define your cosine model function

curve_fit expects the model function to take the independent variable first, followed by the parameters we want to optimize. Here's the exact function definition you'll need:

def cosine_model(theta, a, b, c):
    """Cosine model: f(θ) = a + b·cos(θ - c)"""
    return a + b * np.cos(theta - c)

Step 3: Prepare your data (or plug in your own)

Let's generate sample data with noise to simulate real-world measurements. Replace this section with your actual θ values and corresponding f(θ) data!

# True underlying parameters (we'll try to recover these)
a_true = 2.0
b_true = 3.0
c_true = np.pi / 4  # 45 degrees in radians

# Generate independent variable θ over 0 to 2π
theta = np.linspace(0, 2 * np.pi, 100)

# Generate noisy f(θ) data (add Gaussian noise to the true model)
f_theta_true = cosine_model(theta, a_true, b_true, c_true)
f_theta_noisy = f_theta_true + np.random.normal(0, 0.3, size=theta.shape)

Step 4: Run the curve fit

Nonlinear fitting can be sensitive to initial guesses, so we'll provide a reasonable starting point for a, b, and c based on the data. This helps the algorithm converge quickly to the optimal solution.

# Initial guess for [a, b, c]
# a: approximate mean of your data; b: approximate amplitude (max - min)/2; c: start with 0
initial_guess = [np.mean(f_theta_noisy), (np.max(f_theta_noisy) - np.min(f_theta_noisy))/2, 0.0]

# Perform the fit
popt, pcov = curve_fit(cosine_model, theta, f_theta_noisy, p0=initial_guess)

# Extract the optimized parameters
a_fit, b_fit, c_fit = popt
print("Fitted Parameters:")
print(f"a = {a_fit:.4f} (true value: {a_true})")
print(f"b = {b_fit:.4f} (true value: {b_true})")
print(f"c = {c_fit:.4f} (true value: {c_true:.4f})")

Step 5: Visualize the results

To verify how well the fit matches your data, plot the noisy measurements, true model, and fitted curve side by side:

# Generate the fitted curve using the optimized parameters
f_theta_fit = cosine_model(theta, a_fit, b_fit, c_fit)

# Create the plot
plt.figure(figsize=(8, 5))
plt.scatter(theta, f_theta_noisy, label='Noisy Data', alpha=0.6)
plt.plot(theta, f_theta_true, label='True Model', color='green', linestyle='--')
plt.plot(theta, f_theta_fit, label='Fitted Model', color='red')
plt.xlabel('θ (radians)')
plt.ylabel('f(θ)')
plt.legend()
plt.grid(True)
plt.show()

Quick Tips for Better Fits

  • Tweak Initial Guesses: If the fit doesn't converge or gives odd results, adjust p0. For a, use the mean of your data; for b, use half the range of your data; for c, try 0 or π/2 if you have no prior knowledge.
  • Error Estimation: The pcov matrix gives covariance of the fitted parameters. Calculate standard errors with np.sqrt(np.diag(pcov)).
  • Efficiency: curve_fit uses the Levenberg-Marquardt algorithm, which is highly optimized for nonlinear least squares problems—even with large datasets.

内容的提问来源于stack exchange,提问作者jonnyd42

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:17:24