David schreef:
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)
cause an error? I was playing around with the code, but got nowhere.
Here the entire code:
a = 2; b = 1; c = 2
from math import sqrt
q = sqrt(b*b - 4*a*c)
x1 = (-b + q)/2*a
x2 = (-b - q)/2*a
print x1, x2
Many thanks for a pointer!
Apart from the problem of taking the square root of a negative number,
there is another problem in the code in the book: to calculate the roots
of a * x**2 + b*x + c, there should be parentheses around 2*a in the
calculation of x1 and x2:
x1 = (-b + q)/(2*a)
x2 = (-b - q)/(2*a)
Otherwise the code multiplies by a instead while it should instead
divide by a.
--
The saddest aspect of life right now is that science gathers knowledge
faster than society gathers wisdom.
-- Isaac Asimov
Roel Schroeven
_______________________________________________
Tutor maillist - Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor