We can't find the internet
Attempting to reconnect
Something went wrong!
Attempting to reconnect
medium
primitives
Polynomial Fitting via polyfit
Why this matters
jnp.polyfit(x, y, deg) fits a polynomial of degree deg to (x, y) data
via least squares. It returns coefficients in descending power order:
c[0] * x^deg + c[1] * x^(deg-1) + ... + c[deg].
This is different from NumPyโs Polynomial class, which uses ascending order.
polyfit is used in:
- Trend fitting โ fit a line or curve to noisy measurements.
- Smoothing โ replace noisy data with a smooth polynomial model.
- Model regression โ find polynomial relationships in experimental data.
Key facts:
-
For
npoints anddeg = n-1, you get an exact fit (Vandermonde interpolation). -
High-degree fits can be ill-conditioned โ scale
xto[-1, 1]when needed. -
Output shape is
(deg+1,).
Worked mini-example
import jax.numpy as jnp
x = jnp.array([0.0, 1.0, 2.0])
y = jnp.array([0.0, 1.0, 4.0]) # y = x^2
coeffs = jnp.polyfit(x, y, 2)
# coeffs โ [1.0, 0.0, 0.0] # descending: 1*x^2 + 0*x + 0
Common pitfalls
-
Ascending vs descending โ
jnp.polyfitreturns coefficients in descending power order;jnp.Polynomialuses ascending. Mixing them silently gives wrong results. -
Ill-conditioning โ high-degree polynomials on unscaled
xproduce huge Vandermonde entries; scalexto[-1, 1]to improve numerics. -
deg must be int โ
jnp.polyfitrequires an integer degree; cast withint(deg)if receiving a float scalar.
Problem
Implement polyfit_coeffs(x, y, deg) that fits a polynomial of degree deg
to the data (x, y) via least squares.
-
x,y: 1-D jax arrays of the same length. -
deg: scalar (cast toint). -
Returns: 1-D array of shape
(deg+1,)โ coefficients in descending power order.
Hints
jax
polynomial
polyfit
Sign in to attempt this problem and view the solution.