Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Solving polynomial equations in Python

Up to now I have always Mathematica for solving analytical equations. Now however I need to solve a few hundred equations of this type (characteristic polynomials)

a_20*x^20+a_19*x^19+...+a_1*x+a_0=0 (constant floats a_0,...a_20)

at once which yields awfully long calculation times in Mathematica.

Is there like a ready to use command in numpy or any other package to solve an equation of this type? (up to now I have used Python only for simulations so I don't know much about analytical tools and I couldn't find anything useful in the numpy tutorials).

like image 788
alice Avatar asked May 04 '12 23:05

alice


2 Answers

Here is an example from simpy docs:

>>> from sympy import *
>>> x = symbols('x')
>>> from sympy import roots, solve_poly_system

>>> solve(x**3 + 2*x + 3, x)
           ____          ____
     1   \/ 11 *I  1   \/ 11 *I
[-1, - - --------, - + --------]
     2      2      2      2

>>> p = Symbol('p')
>>> q = Symbol('q')

>>> sorted(solve(x**2 + p*x + q, x))
          __________           __________
         /  2                 /  2
   p   \/  p  - 4*q     p   \/  p  - 4*q
[- - + -------------, - - - -------------]
   2         2          2         2

>>> solve_poly_system([y - x, x - 5], x, y)
[(5, 5)]

>>> solve_poly_system([y**2 - x**3 + 1, y*x], x, y)
                                   ___                 ___
                             1   \/ 3 *I         1   \/ 3 *I
[(0, I), (0, -I), (1, 0), (- - + -------, 0), (- - - -------, 0)]
                             2      2            2      2

(a link to the docs with this example)

like image 53
akaRem Avatar answered Oct 07 '22 11:10

akaRem


You use numpy (apparently), but I've never tried it myself though: http://docs.scipy.org/doc/numpy/reference/generated/numpy.roots.html#numpy.roots.

Numpy also provides a polynomial class... numpy.poly1d.

This finds the roots numerically -- if you want the analytical roots, I don't think numpy can do that for you.

like image 41
mgilson Avatar answered Oct 07 '22 11:10

mgilson