[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
**Subject**: **Re: Strange behavior with for loop**
**From**: Peter Cawley <lua@...>
**Date**: Sun, 8 May 2016 18:02:06 +0100

As a first-order explanation: IEEE double-precision floating point
(the number type used by Lua) cannot represent 0.2 exactly. When you
say 0.2, what actually gets used is closer to
0.2000000000000000111022302. This slight difference adds up over the
loop iterations, and so after ~0.3, the next value taken by i is ever
so slightly greater than 0.5, and so the loop terminates.
On Sun, May 8, 2016 at 5:56 PM, Christophe Devalland
<christophe.devalland@gmail.com> wrote:
> Hi,
> this code :
>
> for i=-0.5,0.5,0.2
> do
> print(i)
> end
>
> gives me :
>
> -0.5
> -0.3
> -0.1
> 0.1
> 0.3
>
> Why not 0.5 ?
>
> Thanks
>
>