# [Tutor] faulty code (maths)

Lie Ryan lie.1296 at gmail.com
Sun Nov 23 20:45:18 CET 2008

```On Sun, 23 Nov 2008 19:39:54 +0530, Arun Tomar wrote:

> hi!
>
>
> On Sun, Nov 23, 2008 at 5:07 PM, David <ldl08 at gmx.net> wrote:
>> Hello everybody,
>>
>> I recently came across a book by Prof. Langtangen: Indroduction to
>> Computer Programming:
>> http://folk.uio.no/hpl/INF1100/INF1100-ebook-Aug08.pdf
>>
>> I am trying to solve exercise 1.18 ("Why does the following program not
>> work correctly?"), but I don't find the mistake: why does the line
>>
>> q = sqrt(b*b - 4*a*c)
>
> problem here is that the method sqrt doesn't accepts -negative numbers
> which in this case is the outcome of the expression above. to rectify
> that u can use the following
>
> q = sqrt(math.fabs(b*b - 4*a*c))
>
> basically convert the negative number to absolute number, rest of the
> stuff will work.
>

An alternative solution would be to use the sqrt from cmath module, which
does handle negative root by outputting complex number:

a = 2; b = 1; c = 2
from cmath import sqrt
q = sqrt(b*b - 4*a*c)
x1 = (-b + q)/2*a
x2 = (-b - q)/2*a
print x1, x2

output:
(-1+3.87298334621j) (-1-3.87298334621j)

This would be the most mathematically correct solution without changing
what the program _seems_ to meant.

However, what the program _actually_ meant, I don't know.

Python's math module does not handle complex numbers because many day-to-
day scripters doesn't have strong mathematical background to handle
complex number, or they simply doesn't need to use complex number, or
sometimes complex number solution is -- for their particular problem --
an indication that something is not right.

```