0 votes

Hi all

Why does print(5.9>5.12) print true? I know comparing the floats is problematic.

I just uploaded a very simple database like object to github for use in godot. If anyone is interested it is at https://github.com/sxkod/dbx .

However I am struggling with making the comparisons work reliably when dealing with floats.

Any help appreciated.

asked Sep 1, 2018 in Engine by sxkod (68 points)

1 Answer

+2 votes

This is correct: 5.9 is a bigger number than 5.12.

Floats are problematic if you are comparing for equality, due to rounding errors inherent in the binary representation of floating point numbers. Greater/less than comparisons are generally fine.

answered Sep 2, 2018 by kidscancode (17,164 points)

oh ok. Thought I was losing my mind!
You are correct - < and > work fine. It is the equality that causes problems.
Is there a way around it then ?

Thanks and have a good weekend.

If you need to compare the equality of two floating point numbers, you can do so with some epsilon value, a small amount representing the precision you need. The numbers are effectively equal if they're within that tiny amount:

if abs(a - b) < 0.000001:
    print("a equals b")

Another way of handling it is to round the two numbers to a reasonable number of digits, ie 1.0 instead of 1.0000000003

See Wikipedia for more information on floating point arithmetic.

Got it. I decided to go with testing if the field is a real number and then use formatting to 4 points. Thanks for your help.

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.