False equation?!

What could be the reason that 0.4 >= 0.4 is false?

Code:

function init(self)
	self.current = 0
	self.addition = 0.05
	self.compare = 0.4
end

function update(self, dt)
	self.current = self.current + self.addition
	if self.current >= self.compare then
		print(self.current .. " >= " .. self.compare .. " -> true")
	else
		print(self.current .. " >= " .. self.compare .. " -> false")
	end
end

Output:

DEBUG:SCRIPT: 0.05 >= 0.4 -> false
DEBUG:SCRIPT: 0.1 >= 0.4 -> false
DEBUG:SCRIPT: 0.15 >= 0.4 -> false
DEBUG:SCRIPT: 0.2 >= 0.4 -> false
DEBUG:SCRIPT: 0.25 >= 0.4 -> false
DEBUG:SCRIPT: 0.3 >= 0.4 -> false
DEBUG:SCRIPT: 0.35 >= 0.4 -> false
DEBUG:SCRIPT: 0.4 >= 0.4 -> false <--- What?
DEBUG:SCRIPT: 0.45 >= 0.4 -> true
DEBUG:SCRIPT: 0.5 >= 0.4 -> true
DEBUG:SCRIPT: 0.55 >= 0.4 -> true

Thanks!

Here you go! :slight_smile:

5 Likes

Oh, thanks! I’ve never tought it causes problem even by 2 decimals and in so few iteration.

When not rounded up:

local a = 0
for i = 1, 8 do
  a = a + 0.05
end
local b = 0.4
print(a, b, a >= b)

Results in

0.39999999999999997	0.4	false
7 Likes

Precision makes all the difference here:

Mikaels-MacBook-Pro% lua                                                                                                                  discourse/. [master]â—Ź
Lua 5.3.4  Copyright (C) 1994-2017 Lua.org, PUC-Rio
> a=0
> b=0.05
> print(string.format("%.20f", a+b+b+b+b+b+b+b+b))
0.39999999999999996669
> print(string.format("%.20f", 0.4))
0.40000000000000002220
7 Likes

Understood, thank you for the detailed answer for both of you!

3 Likes