Skip to content

numpy/legacy-polynomial

Pack Severity Fix Versions
NumPy info unsafe, with xpd check --fix --unsafe-fixes All versions

np.polyfit and its kin are NumPy's legacy polynomial API, and the docs recommend Polynomial.fit as more stable. Use the np.polynomial classes.

slope, intercept = np.polyfit(x, y, 1)
intercept, slope = np.polynomial.Polynomial.fit(x, y, 1).convert().coef

The rule reports np.polyfit, np.poly1d, np.polyval, np.roots, np.poly, np.polyder, np.polyint, np.polyadd, np.polysub, np.polymul and np.polydiv.

xpd check --fix --unsafe-fixes applies the fixes of this rule. Check the result, because an unsafe fix can change what the code does.

The unsafe fix writes np.polynomial.Polynomial.fit(x, y, deg).convert().coef[::-1] for polyfit, and the numpy.polynomial function on coef[::-1] for poly1d, polyval, roots, poly, polyder and polyint, reversed again where coefficients come out. A poly1d argument raises, whole number coefficients become floats, roots come out sorted, and poly1d becomes a Polynomial with other methods. polyadd, polysub, polymul, polydiv and calls with other arguments have no fix.

Polynomial.fit rescales the input before fitting and can return fewer coefficients if the highest ones are zero. It can also reject a two-dimensional y that polyfit fitted column by column. np.poly on a square matrix computed its characteristic polynomial, while polyfromroots uses matrix entries as roots.

$NP.polyfit is part of NumPy's legacy polynomial API, and its docs recommend Polynomial.fit as more stable numerically. Write $NP.polynomial.Polynomial.fit($X, $Y, $DEG).convert().coef[::-1], which keeps the coefficients from the highest degree down.

See all rules in the NumPy pack.