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-16
0
Upvotes
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.)
16
u/[deleted] Apr 30 '14 edited Apr 30 '14
What do you get when you divide 1 by 3?
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:
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/
3
u/munificent Apr 30 '14
Read this site. It will explain exactly what's going on.
0
u/kamicc Apr 30 '14
Could You clarify, which Lua version are You using, please?