Find the roots of the polynomials using NumPy

Find the roots of the polynomials using NumPy

To find the roots of a polynomial using numpy, you can utilize the numpy.roots() function. This function returns the roots of a polynomial with coefficients given in a list or array, starting with the coefficient of the highest degree term and ending with the constant term.

Here's how to use it:

  • First, ensure you have numpy installed:
pip install numpy 
  • Then, use the numpy.roots() function:
import numpy as np # For the polynomial x^2 - 4x + 4 which can be represented as (x-2)(x-2) coefficients = [1, -4, 4] # This corresponds to x^2 - 4x + 4 roots = np.roots(coefficients) print(roots) # Outputs: [2. 2.] which are the roots of the polynomial 

In this example, the polynomial is x2−4x+4 and its roots are both 2, which is why the output is [2. 2.].

Just replace the coefficients list with the coefficients of any polynomial you're interested in, and the numpy.roots() function will return its roots.


More Tags

onpress debugging data-annotations adapter photo-upload url-encoding gateway java-native-interface locale apache-zookeeper

More Programming Guides

Other Guides

More Programming Examples