why do I get this behavior from a while loop?

Carsten Haese carsten.haese at gmail.com
Fri Nov 27 17:36:02 CET 2009


S. Chris Colbert wrote:
> In [15]: t = 0.
> 
> In [16]: time = 10.
> 
> In [17]: while t < time:
>    ....:     print t    
>    ....:     t += 0.1   
>    ....:                
>    ....:                
> 0.0                     
> 0.1                     
> 0.2                     
> 0.3                     
> <--snip-->
> 9.4
> 9.5
> 9.6
> 9.7
> 9.8
> 9.9
> 10.0
> 
> 
> I would think that second loop should terminate at 9.9, no? 

It would, if a floating point number could represent the number 0.1 and
its multiples precisely, but it can't.

> I am missing something fundamental?
> 

Yes. Read http://docs.python.org/tutorial/floatingpoint.html .

Then, change "print t" to "print repr(t)" to see what's going on.

--
Carsten Haese
http://informixdb.sourceforge.net




More information about the Python-list mailing list