Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lua for loop does not do all iterations

I am new to lua, and i am using it to automate some tasks in the simulation program femm. In my script i have this type of for loop:

for i=0.1,0.3,0.1
do
  print(i)
end

The problem is it only iterates from 0.1 to 0.2(it does not enter i=0.3).I tried with other values (for example from 0.1 to 0.4) and it works properly. Why does this strange behaviour happen? Is this a floating point number problem?

like image 622
user19955 Avatar asked Oct 17 '22 06:10

user19955


1 Answers

This happens because adding 0.1 to 0.1 three times produces a number that is slightly greater than 0.3. Hence the loop stops before reaching your target end number.

This is the danger of using floating point values for loop iteration. Rewrite the loop in integers instead, and perform a division to get your required number:

for j = 1,3
do
    i = j/10
    print(i)
end

Demo.

like image 176
Sergey Kalinichenko Avatar answered Oct 21 '22 07:10

Sergey Kalinichenko