Factoring Polynomials

Scott David Daniels Scott.Daniels at Acm.Org
Fri Dec 19 15:28:13 EST 2008


Tim Rowe wrote:
> 2008/12/18 Scott David Daniels <Scott.Daniels at acm.org>:
> 
>> def quadsolve(a, b, c):
>>    try:
>>        discriminant = sqrt(b**2 - 4 * a * c)
> 
> The discriminant of a quadratic is more usually just the b**2 - 4 * a
> * c part, not the square root of it. Testing that for negative, zero
> or positive avoids the need to use an exception for a normal case.

Absolutely right.  Blame the oversight on my old CPU-stingy days.  When
the CPU was slow, avoiding a sqrt here or there (if you didn't have a
sqrt opcode) was so important that I do it without thinking these days.
Since I still have that disease, perhaps the variable should be renamed
root_discriminant.

As for the testing, I find using math.sqrt catches the negative cases
and raises an exception by itself, leaving only the issue of whether
or not to return a pair or singleton.  Usually for my purposes, I'd let
the exception fly and not return an (?the?) empty tuple.

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



More information about the Python-list mailing list