"Jim Hutchinson" <[EMAIL PROTECTED]> wrote

> program that "should" work but doesn't. It generates a random number
> between 1 and 2 out to 10 decimal places.

Ok, Here's the problem. You are trying to compare two floating
point numbers. But python stores data in binary and displays
it in decimal. A lot of decimal numbers cannot be exactly
represented in binary so what you see displayed is an
approximation of the actual number stored in memory.

> while (guess != number):

So when you try to compare the number you entered with
the number stored in memory they are not quite the same.
The normal way of dealing with this in programs is to define
a very small number (often called epsilon or e) and check if
your guess is plus or minus e from the target. So your
code would become

e = 0.0000000001
while not( guess - e < number < guess + e ):
    # ...your code here

I briefly mention this in the Raw Materials topic of my tutor
when discussing Real numbers

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 


_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

Reply via email to