How do I extract the coefficient vector from a numpy
polynomial?
In Python, when using the numpy
package to construct a polynomial, how do I extract the coefficients of this polynomial as a vector?
The numpy
package has 2 classes of polynomial, the deprecated poly1d
and the recommended Polynomial
.
Let's start with a vector that will become the source of the coefficients of our polynomial:
v = [5, 18, -5]
We can construct a Polynomial
-class object:
from numpy.polynomial import Polynomial
p = Polynomial(v)
we can now obtain the coefficient vector again using coef
p.coef
Which gives:
array([ 5., 18., -5.])
The method for the deprecated poly1d
class objects is the same (coef
), but you would use poly1d
instead of Polynomial
to construct the polynial (which is not recommended anymore, you should use Polynomial
).