如何使用np.polyfit拟合无常数项的三次多项式?
Got it, let's work through this. When you use np.polyfit(x, y, 3) directly, it returns 4 coefficients—for $x³, x², x$, and a constant term. But since you need to exclude that constant term (force it to 0), we need to adjust how we set up the fitting problem. Here are two reliable approaches:
Approach 1: Build a Design Matrix & Use Least Squares
This is the most straightforward method, where we manually construct the feature matrix without the constant term column, then solve the least squares problem directly:
import numpy as np # Your input data x = np.array([0.004, 0.005, 0.006, 0.007]) y = np.array([0.001, 0.095, 0.026, 0.307]) # Create design matrix: each row is [x³, x², x] (no constant term) X = np.column_stack((x**3, x**2, x)) # Solve for coefficients a, b, c (corresponding to x³, x², x) coefficients, _, _, _ = np.linalg.lstsq(X, y, rcond=None) # Output the results print("Fitted coefficients (a, b, c):", coefficients)
Approach 2: Trick np.polyfit for Indirect Fitting
If you prefer sticking with np.polyfit, we can reframe the problem to make it work. Since our target polynomial is $y = x(ax² + bx + c)$, we can divide both sides by x (safe here since none of your x values are 0) to get $z = ax² + bx + c$, where $z = y/x$. Then we just fit a quadratic polynomial to z vs x:
import numpy as np x = np.array([0.004, 0.005, 0.006, 0.007]) y = np.array([0.001, 0.095, 0.026, 0.307]) # Create z = y/x to reframe the problem z = y / x # Fit quadratic polynomial to z ~ x: gives [a, b, c] coefficients = np.polyfit(x, z, 2) # These are exactly the coefficients for our original cubic (no constant term) print("Fitted coefficients (a, b, c):", coefficients)
Verify the Fit
To make sure things work, you can generate the fitted y-values and compare them to your original data:
# Calculate fitted y using the coefficients y_fit = coefficients[0] * x**3 + coefficients[1] * x**2 + coefficients[2] * x # Print comparison print("Original y values:", y) print("Fitted y values:", y_fit)
A quick note: Approach 2 won't work if any x values are 0 (since division by zero is undefined), but your dataset doesn't have that issue, so it's totally safe here. Both methods should give nearly identical coefficients—any tiny differences are just from numerical precision in the solvers.
内容的提问来源于stack exchange,提问作者Geet Sethi

