Count Down to Zero
Peter Hansen
peter at engcorp.com
Sat Sep 23 11:31:20 EDT 2000
Curtis Jensen wrote:
> >>> i = 1.0
> >>> while i >= 0.0:
> ... print i
> ... i = i - 0.1
> ...
> 1.0
> 0.9
> 0.8
> 0.7
> 0.6
> 0.5
> 0.4
> 0.3
> 0.2
> 0.1
> 1.38777878078e-16
> >>>
>
> The last one should be 0.0
See the other well-considered responses, which give you the background
on how your hardware and the nature of floating point representations,
not Python, is the source of your problem. One obvious "solution" is to
do something like this:
>>> i = 10
>>> while i >= 0:
... print i/10.0
... i = i - 1
...
1.0
0.9
0.8
0.7
0.6
0.5
0.4
0.3
0.2
0.1
0.0
>>>
--
Peter Hansen
More information about the Python-list
mailing list