I have the following lines of code
import numpy as np
from numpy.polynomial import Polynomial
x=Polynomial.fit([0,1,2,3,4],[0,1,2,3,4],4)
print(x)
print(x.call(0))
I would expect numpy to fit the data to the polynomial f(x)=x
. But instead it outputs 2.0 + 2.0 x + (1.2915422e-15) x2 - (7.05812123e-16) x3 - (9.57512621e-17) x**4
.
Even stranger when i get it to evaluate at x=0
it gives 1.1102230246251565e-15
which is what i would expected with f(x)=x
but isn't 2.0
. Does anyone know what is going on?
Using the old polynomial features of numpy i.e. np.polyfit I get a correct answer but the rest of my project uses the new features.
If you read the docs, you see that what fit
returns is not literally the coefficients. If you print(x.convert().coef)
, you'll see that it is, indeed, f(x) = x
:
[-1.77635684e-15 1.00000000e+00 1.22916662e-15 -3.08599735e-16
1.95879353e-17]
https://numpy.org/doc/stable/reference/generated/numpy.polynomial.polynomial.Polynomial.fit.html