Floating-point precision

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

print(0.1+0.2 == 0.3) # False
print("%.17f" % (0.1+0.2)) # 0.30000000000000000

For exapmle in Python:
>>> 0.1+0.2
0.30000000000000004

Why the print() function does not show the number correctly?

:bust_in_silhouette: Reply From: Jason Swearingen

This sounds like a formatting issue. I use C#, not GDScript, but I’d assume there’s a way to increase the formatting precision.

additionally, the Mathf function IsEqualApprox() is probably what you want to use when dealing with float equality.

Thanks for your answer. I know about is_equal_approx() function, but I wonder why he compares correctly in this case, and at the end shows garbage :confused:

OrdinaryGuy | 2020-02-02 17:20

Because floating point can’t accurately represent all numbers, which is by design.

To represent all numbers, floating point would have to have an infinite number of bits. Since a single precision floating point number has only 32 bits, there are rounding errors introduced in unintuitive ways.

To check equality, you typically check to see if the numbers are within a given margin of error. This is what is_equal_approx() is for.

stormreaver | 2020-04-25 12:23