Friday, May 31, 2013

Polynomials with Python

Seriously, can it be any easier? ;)

If you are not in a pylab session, import the module like this:
In [148]: from numpy import poly1d
 Otherwise, just "import poly1d" should work.
Now let's get a polynomial for the coefficients of [3,2,1] (always in decreasing order!):
In [149]: p = poly1d([3,2,1])
Printing it provides a semi-analytical printout:
In [150]: print p
   2
3 x + 2 x + 1
Applying new x values to it is easy, because the poly1d object is a function:
In [152]: newx = linspace(0,10,10)
In [153]: p(newx)
Out[153]:
array([   1.        ,    6.92592593,   20.25925926,   41.        ,
         69.14814815,  104.7037037 ,  147.66666667,  198.03703704,
        255.81481481,  321.        ])
Lots of other things are possible with this object. IPython's object inspection makes it easy to discover them:
In [154]: p.
p.coeffs    p.deriv     p.integ     p.order     p.variable

In [155]: p.deriv()
Out[155]: poly1d([6, 2])
In [156]: pderiv = p.deriv()
In [157]: print pderiv
6 x + 2
Roots for this polynomial can be either determined by the roots function that is imported in a pylab session (or importable like from numpy import roots)
In [158]: roots(p)
Out[158]: array([-0.33333333+0.47140452j, -0.33333333-0.47140452j])
In [159]: p.r
Out[159]: array([-0.33333333+0.47140452j, -0.33333333-0.47140452j])




PS: One of these days I really have to find out how to do code high-lighting in Blogger, or, preferably, go all the way and do IPython notebook posts.