+1 vote

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)) outputs0.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).

asked Jul 18, 2017 in Engine by Daniel Mircea (79 points)

1 Answer

+8 votes
Best answer

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.

answered Jul 19, 2017 by avencherus (4,686 points)
selected Jul 19, 2017 by Daniel Mircea

Good rule to remember: Floats Are Never Equal.

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.

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.

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.