3

I have a Lua for loop that iterates through numbers from -1 to 1 by increments of 0.01, and is producing numbers as bad as 6.6613381477509e-016 in the range of -0.1 to 0.1 (exclusive)

I am using Lua in the LOVE engine (v 0.9.2), written in C++

I would much rather solve the problem than just receive an info dump of an explanation, but I'd rather that than nothing at all.

(also I do understand the general reason floats are inaccurate, so that may be left out of explanations)

Pixel
  • 35
  • 3

1 Answers1

6

You've already known the reason, here's a possible solution: don't loop with floating point numbers, use integers.

Instead of

for i = -1, 1, 0.01 do

use:

for i = -100, 100 do
  print(i / 100)
end
Yu Hao
  • 119,891
  • 44
  • 235
  • 294