The numpy roots()
function is used to find the roots of a polynomial equation using the coefficient values.
The syntax of the function is as follows:
numpy.roots([n])
The roots accept an array of polynomial coefficients as [n, n, ...]
and return the roots of the equation.
If the array length is n+1
then the polynomial is described by:
p[0] * x**n + p[1] * x**(n-1) + ... + p[n-1]*x + p[n]
For example, if you have the following equation: x2 - 5x + 6
The coefficients are 1
, -5
, and 6
.
Use the root()
function to solve find the roots:
import numpy as np
np.roots([1, -5, 6])
# array([3., 2.])
So x = 3, 2
You can also pass a floating number as one of the coefficient values:
import numpy as np
coeff = [3.7, 2, 1]
np.roots(coeff)
The output will be:
array([-0.27027027+0.44409937j, -0.27027027-0.44409937j])
And that’s how the numpy.roots()
function works.