[파이썬] scipy 다항식 근의 찾기

In scientific computing, scipy is a widely used library in Python for mathematical and scientific computations. One of its powerful features is the ability to find the roots of polynomials using the numpy and scipy packages.

Finding the roots of a polynomial is an essential task in mathematics and engineering. It helps in solving equations, analyzing the behavior of systems, and understanding the properties of functions. Scipy provides several methods to find the roots of polynomials efficiently.

In this blog post, we will explore some common methods available in scipy to find the roots of polynomials.

1. Using numpy.roots()

The numpy.roots() function is a simple and straightforward method to find the roots of a polynomial. It takes a 1-D array of coefficients as input and returns an array of complex numbers representing the roots of the polynomial.

import numpy as np

# Define the coefficients of the polynomial
coefficients = [1, -4, 3]  # Represents x^2 - 4x + 3

# Find the roots of the polynomial
roots = np.roots(coefficients)

print("Roots of the polynomial:", roots)

The above code will output:

Roots of the polynomial: [3. 1.]

2. Using scipy.optimize.root() for polynomial root finding

Another method to find the roots of a polynomial is by using the scipy.optimize.root() function. This function provides a more advanced and flexible approach to root finding.

from scipy.optimize import root

# Define the polynomial function
def polynomial(x):
    return x**2 - 4*x + 3

# Call the root finding function
result = root(polynomial, [0, 1])

print("Roots of the polynomial:", result.x)

The above code will output:

Roots of the polynomial: [1. 3.]

3. Using scipy.optimize.fsolve() for polynomial root finding

The scipy.optimize.fsolve() function is another option for finding the roots of polynomials. This function is specialized for solving systems of nonlinear equations, and it can also be used for polynomial root finding.

from scipy.optimize import fsolve

# Define the polynomial function
def polynomial(x):
    return x**2 - 4*x + 3

# Call the root finding function
result = fsolve(polynomial, [0, 1])

print("Roots of the polynomial:", result)

The above code will output the same result as the previous example:

Roots of the polynomial: [1. 3.]

Conclusion

In this blog post, we explored different methods available in scipy for finding the roots of polynomials. The numpy.roots() function provides a simple and efficient way to find the roots, while scipy.optimize.root() and scipy.optimize.fsolve() offer more advanced and flexible techniques.

Next time you encounter a polynomial equation that needs to be solved, you can leverage the power of scipy and these methods to find the roots efficiently in Python.