Problem comparing floats

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Daniel Mircea
:warning: Old Version Published before Godot 3 was released.

I’m having a hard time comparing two floats:

float(21) / float(120) == 0.175

It should be true, but godot says it’s false.
Just to be clear, print(float(21) / float(120)) outputs 0.175

typeof(float(21) / float(120)) is the same as typeof(0.175)

Certainly these two should be true:

(float(21) / float(120)) * 1000 == float(0.175) * 1000

But they’re not, however they provide a hint of what’s going on:

175 == 174.999997

0.175 * 1000 was actually the culprit. I would had been ok with comparing it to 0.175 / 1.0 however it won’t work.

I think I’ll typecast the values a strings, but am I missing something? Doesn’t look like godot supports big decimal (though it shouldn’t be necessary for something so trivial).

:bust_in_silhouette: Reply From: avencherus

This isn’t a problem with Godot or what it supports. It is the nature of how floating point numbers are stored. You will run into situations where bits end up doing funny things on the end of the data type. There is a lot to discuss about the issue, but the general idea is that you want to compare floats with a threshold value.

You can do this comparison in-line or write a function something like this:

const FLOAT_EPSILON = 0.00001

static func compare_floats(a, b, epsilon = FLOAT_EPSILON):
	return abs(a - b) <= epsilon

The float epsilon is the factor you may need to adjust, and where a lot of the technical discussion arises. This here is the basic general purpose one.

Good rule to remember: Floats Are Never Equal.

whooshfrosted | 2017-07-19 00:55

Thanks for the answer. I’m aware I should had used integers. However, main issue is that godot doesn’t show the right value. 0.1 + 0.2 is 0.30000000000000004 in most languages. And this is godot’s case as well, however it formats it to 0.3 thus being misleading.

Daniel Mircea | 2017-07-19 11:06

Oh, I see what you mean, it looks like there is some truncation in the debugger values, but I do see the full precision in a print line.

Maybe it is worth opening an issue on Github.

avencherus | 2017-07-19 12:51