5

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?

4
  • 0.3 may be not equal to 0.3 Commented Sep 11, 2017 at 11:14
  • Is this because it is not declared as an integer(i have not used lua before)? Should i use only integer values for the loop variable? Commented Sep 11, 2017 at 11:16
  • Try i=0.1, 0.3+1e-9, 0.1 Commented Sep 11, 2017 at 11:20
  • it sounds like you may need a primer in floating point operations Commented Sep 11, 2017 at 14:16

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.