[Tutor] faulty code (maths)

Kent Johnson kent37 at tds.net
Sun Nov 23 16:10:59 CET 2008


On Sun, Nov 23, 2008 at 9:44 AM, David <ldl08 at gmx.net> wrote:

> The working code:
>
> a = 2; b = 1; c = 2
> import math
> q = math.sqrt(math.fabs(b*b - 4*a*c))
> x1 = (-b + q)/2*a
> x2 = (-b - q)/2*a
> print x1, x2

Working in the sense of "completes without an error message and prints
a result", anyway. Not working in the sense of "gives the correct
answer". Using your code above gives
In [17]: print x1, x2
2.87298334621 -4.87298334621

In [18]: a*x1*x1 + b*x1 + c
Out[18]: 21.381049961377752

which should be 0.

Some quadratic equations do not have a solution in the real numbers,
only in complex numbers. You might want to look at cmath.sqrt() which
will take the square root of a negative number, giving a complex
result. Using the above values for a, b, c:

In [19]: import cmath
In [20]: cmath.sqrt(b*b - 4*a*c)
Out[20]: 3.872983346207417j

Kent


More information about the Tutor mailing list