Math confusion (1 < 1 = true)
Okay. So I'm kinda tired and have probably missed something. But check this out please:
test = 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1
if test > 1 then
print(test .. " is more than 1")
elseif test == 1 then
print(test .. " is 1")
elseif test < 1 then
print(test .. " is less than 1")
endThe output I get from the code above is that 1 is less than 1. Why? Shouldn't the output be 1 is 1? What have I missed? Have I fucked up my local Lua installation somehow?
Edit: The following code (in addition to the one above) does not make any sense to me at all...
test2 = test - 1
print(test2)Output:
-1.1102230246252e-1616
Apr 30 '14 edited Apr 30 '14
What do you get when you divide 1 by 3?
0.333333333333333333 (repeating forever)Why so messy?
In base 10 (aka 'decimal'), you can neatly represent 1/10 (.1), 1/100 (.01), 1/1000 (.001), and so on, but not 1/3rd.
In base 3, you can easily represent 1/3 (.1), or 1/9 (.01), and so on, but not 1/10th.
In base 2, you can easily represent 1/2 (.1) or 1/4 (.01) and so on, but not 1/10th.
Computers use base 2 (aka 'binary'), so the base-10 number in your code (0.1) is represented imprecisely inside the machine in binary.
Try running the following code:
-- iterate from .1 to 10 in increments of .1
for i=.1, 10, .1 do
print(string.format("%.17g", i))
end3
25
u/schmetterlingen Apr 29 '14
It looks like a result of floating point arithmetic, which doesn't perfectly represent all numbers.
Look here: http://floating-point-gui.de/
4
3
u/munificent Apr 30 '14
Read this site. It will explain exactly what's going on.
2
May 02 '14
I was reading a little bit. I would like to know if Lua actually happen to deal with these problems internally in some way or do I have to be aware of this most of the time? I mean, I've never had any trouble with this, and seeing how easy to reproduce it is, is just weird how I've never saw it.
3
u/munificent May 02 '14
No, you have to be aware of it.
It doesn't actually cause problems too often in practice. The biggest thing you have to be aware of is that
==will not work reliably for numbers unless you're careful about what arithmetic you perform on them.
0
u/kamicc Apr 30 '14
Could You clarify, which Lua version are You using, please?
2
u/Fledo Apr 30 '14
The one included in the latest LÖVE release.
2
u/smog_alado Apr 30 '14
Lua comes with a global
_VERSIONvariable that can give you this infoprint(_VERSION)without us needing to know what version Love is shipping.
2
u/Fledo Apr 30 '14
5.1!
1
u/C4Cypher Apr 30 '14
Also, if I'm not mistaken, the latest version of LOVE (9) started using luajit.
19
u/fuxoft Apr 30 '14
To put it simply: Whenever you do arithmetics with floating point numbers, don't ever assume that the result is exactly equal to anything. (And this has nothing to do with Lua.)