Very simple question, but I'm really confused :P
> for x = 0, 5, 0.2 do
print (x)
end
This loop counts only to 4.8 (one step more with 0.2 would result exactly 5, wouldn't it?)
But the following for-loop counts to 5
> for x = 0, 5, 1 do
print (x)
end
Can someone explain or refer to the manual, the reason behind these outputs. Maybe I should define the variable as float?
Lua usually represents numbers in ieee754 binary64 format ("usually" because the representation actually depends on the underlying C implementation). The closest number to 0.2 in binary64 is 0x3FC999999999999A, or approximately 0.200000000000000011102230246252.
The 0.2 in your source code is rounded to this number before the calculation takes place.
Since 0.200000000000000011102230246252 is larger than 2, the number becomes larger than 5 in the final step, and so the loop ends at approximately 4.8.
for x = 0, 5, 0.2 do print (x) end
This numeric for loop will add the step 0.2 to initial value 0, do the processing (print(x)) until the value is <=5. The problem is, for floating point numbers, 0.2 can't be represented precisely, so there is a little bit rounding. So when you think it should sum as 5, it probably is a little bit bigger.
For integers that isn't very big, it can be represented precisely in a double precision floating point number, so that's no problem.
For your first day of learning Lua, a little tip:
double by default. * see below*:This is no longer true. Lua 5.3 introduced a new integer subtype for numbers. See Changes in the Language
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With