Factoring Polynomials

Mark Dickinson dickinsm at gmail.com
Thu Dec 18 16:09:03 EST 2008


On Dec 18, 8:47 pm, Scott David Daniels <Scott.Dani... at Acm.Org> wrote:
>      else: # a single result (discriminant is zero)
>          return (-b / (2 * a),)

Maybe make that (-b / (2. * a)) to avoid getting funny results
when a and b are integers.  (Or do a from __future__ import
division, or use Python 3.0, or ....)

And to make the function more bullet-proof, you might want to
do something like (untested):

    from math import copysign

    [rest of example as in Scott's post]

    if discriminant: # two results
        root1 = (-b - copysign(discriminant, b))/(2*a)
        root2 = c/(a*root1)
        return (root1, root2)

to avoid numerical problems when b*b is much larger
than abs(a*c). Compare with the results of the usual
formula when a = c = 1, b = 10**9, for example.  But
that still doesn't help you when the computation
of the discriminant underflows or overflows...

Isn't floating-point a wonderful thing!  :)

Mark



More information about the Python-list mailing list