1

When checking a IF evaluation in WHILE in lua:

stopper = 0;
needle = 0.14;
    while stopper < 0.2 do
        if stopper == needle then
        print ("Finally!")
    end
    stopper = stopper + 0.01
end

"Finally!" never gets printed if needle = 0.14 but does if needle = 0.15 (or 0.16, 0.17).

Is there a way to make it work? I suppose that this has to do with how LUA handles floats but I am not sure.

Obs:

  • both counter and needle types are number (when checked like: type(counter))
  • using tonumber(counter) == tonumber(needle) does not help
  • there is a work around using tostring but I do not want it for obvious performance reasons
FredericoR
  • 71
  • 5
  • 2
    Possible duplicate of [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) – EOF Dec 05 '17 at 17:18

1 Answers1

3

The decimal numerals in your source code are converted to binary floating-point, and they are added using binary floating-point.

I am guessing Lua uses 64-bit binary IEEE-754 floating-point, in which case “.01” is converted to 0.01000000000000000020816681711721685132943093776702880859375, and the result of adding it 14 times is 0.1399999999999999855671006798729649744927883148193359375, whereas “.14” is converted to 0.14000000000000001332267629550187848508358001708984375. As you can see, they are not equal.

A solution for you might be to count loop iterations using integers and to use integers for the stopper and needle positions. Convert to floating-point only when necessary. If you need to use floating-point operations beyond simple loop control, you will need to explain further.

Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312
  • Hi Eric, thanks for the answer. I manipulating values from os.clock and os.time in these loops and these return floating-points. – FredericoR Dec 05 '17 at 02:32
  • @FredericoR: You should enter a new question explaining what you are trying to do with os.clock and os.time and asking about that. – Eric Postpischil Dec 05 '17 at 13:24