Really basic problem

Dan Stromberg dstromberglists at gmail.com
Thu Oct 11 00:37:26 CEST 2007


On Mon, 08 Oct 2007 12:23:27 +0200, A.T.Hofkamp wrote:

> On 2007-10-08, Andreas Tawn <andreas.tawn at ubisoft.com> wrote:
>>> i know this example is stupid and useless, but that's not the answer
>>> to my question.
>>> here it goes:
>>> 
>> You've just discovered the joys of floating point number comparisons.
>>
>> Consider this snippet:
>>
>> status = 0.0
>> print (repr(status))
>>
>> for i in range(10):
>>     status += 0.1
>>     print (repr(status))
>>
>> Output:
>>
>> 0.0
>> 0.10000000000000001
>> 0.20000000000000001
>> 0.30000000000000004
>> 0.40000000000000002
>> 0.5
>> 0.59999999999999998
>> 0.69999999999999996
>> 0.79999999999999993
>> 0.89999999999999991
>> 0.99999999999999989
>>
>> The issue is that 0.1 etc don't have an exact representation as floating
>> point.
>>
>> Interestingly:
>>
>>>>> 0.10000000000000001 == 0.1
>> True
>>>>> 0.30000000000000004 == 0.3
>> False
>>
>> I guess this means that Python has some concept of "close enough", but
>> I'll have to defer to someone more knowledgeable to explain that.
> 
> It's not Python, it is the computer, ie you have this problem with any program
> that uses floating point calculations. However, some programs hide it from you
> so you think there is no problem...
> 
> Plz read the FAQ for an answer to this and many other questions:
> http://www.python.org/doc/faq/general/#why-are-floating-point-calculations-so-inaccurate

It's not even the computer precisely - it's the underlying math.  The
computer is just doing the best it can with the math, but you'll see the
same thing if you do this with pencil and paper.

Some numbers have a rational (finite) representation in a given radix and
some don't, and which numbers are rational in radix a may be irrational in
a different radix b.

Oh, and some numbers that are rational in a given radix may require too
many digits to be represented precisely anyway.





More information about the Python-list mailing list