For loop stops short by 0.01

The following loop prints only as far as 0.99:

for t = 0, 1, 0.01 do
	print(t)
end

What’s that about?

Looks legit to me, it counted 100 times. The first value is 0 which is what you set it at. :slightly_smiling_face:

The issue is caused by Lua’s use of floating point numbers (google it, it’s an interesting topic).

Essentially, while you are telling the loop that you want it to increment by 0.01, the code actually increments it by some number very close to 0.01, like 0.0100000000000000000001 or 0.0099999999999999, etc.

This means that it’ll work until you get to the end, where the number is probably something like 0.9900000…1, so there’s no 0.01 left to add to it until it becomes 1.

You can see this in action by adding a check for the remainder:

for t = 0, 1, 0.01 do
	print( t, t % 0.01 )
end

Since you are dividing the number by the increment, i.e. 0.01, the remainder should always be zero. However, you can see that it veers off zero very early.

So, when doing loops, you should stick to using integers.

4 Likes

Makes sense, Thanks!