Factoring Polynomials

Scott David Daniels Scott.Daniels at Acm.Org
Thu Dec 18 21:47:46 CET 2008


eric wrote:
> On Dec 18, 8:37 pm, collin.da... at gmail.com wrote:
>> ...  I dont know how to implement the quadratic equation ...
> 
> with numpy:
> from numpy import *
> 
> s=[1,-1]
> x = -b+s*sqrt( b**2-4*a*c )/(2*a)

Numpy is pretty heavyweight for this.

For built in modules you have a few choices:
For real results:
     from math import sqrt
For complex results:
     from cmath import sqrt
or you can simply use:
     (value) ** .5

Then you can do something like:

def quadsolve(a, b, c):
     try:
         discriminant = sqrt(b**2 - 4 * a * c)
     except ValueError:
         return () # No results at all.
     if discriminant: # two results
         return ((-b - discriminant) / (2 * a),
                 (-b + discriminant) / (2 * a))
     else: # a single result (discriminant is zero)
         return (-b / (2 * a),)



--Scott David Daniels
Scott.Daniels at Acm.Org



More information about the Python-list mailing list