why do I get this behavior from a while loop?
Diez B. Roggisch
deets at nospam.web.de
Fri Nov 27 11:19:03 EST 2009
S. Chris Colbert schrieb:
> This seems strange to me, but perhaps I am just missing something:
>
> In [12]: t = 0.
> In [13]: time = 10.
>
> In [14]: while t < time:
> ....: print t
> ....: t += 1.
> ....:
> ....:
> 0.0
> 1.0
> 2.0
> 3.0
> 4.0
> 5.0
> 6.0
> 7.0
> 8.0
> 9.0
>
> 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?
>
> I am missing something fundamental?
Yes. The lack of precision that floating points suffer from (nothing
python-specific), and the rounding-behavior of printing them.
>>> t = 0.
>>> time = 10.
>>> while t < time:
... print repr(t)
... t += .1
...
0.0
0.10000000000000001
<snip/>
9.8999999999999808
9.9999999999999805
>>>
Diez
More information about the Python-list
mailing list