[Tutor] faulty code (maths)

David ldl08 at gmx.net
Sun Nov 23 15:44:01 CET 2008


Hello,

yes, that did the trick, though I had to change the "from math import ~" 
line to "import math". I also changed in line three the sqrt() function 
to math.sqrt(). Otherwise there would be complaints:

<type 'exceptions.NameError'>: name 'sqrt' is not defined
WARNING: Failure executing file: <ex1.18.py>

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

Thanks a lot!

David


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.
>
>   
>> 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!
>>
>> David
>> _______________________________________________
>> Tutor maillist  -  Tutor at python.org
>> http://mail.python.org/mailman/listinfo/tutor
>>
>>     
>
>
>
>   



More information about the Tutor mailing list