Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

1st day lua - confused by a for loop [duplicate]

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?

like image 876
user2822265 Avatar asked Sep 06 '25 03:09

user2822265


2 Answers

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.

like image 64
Mankarse Avatar answered Sep 07 '25 21:09

Mankarse


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:

  • Use Lua as the language name, not LUA or lua.
  • Lua has only one number type, that is 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

like image 34
Yu Hao Avatar answered Sep 07 '25 19:09

Yu Hao