comparing floats

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By sxkod

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 GitHub - sxkod/dbx: An extremely simple database facility for game development in godot .

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

Any help appreciated.

:bust_in_silhouette: Reply From: kidscancode

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.

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.

sxkod | 2018-09-02 02:44

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.

kidscancode | 2018-09-02 03:00

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.

sxkod | 2018-09-02 19:58