Proper way for checking equality of float in Python

Posted by Afsal on 15-Dec-2023

Hi Pythonistas!

Today we will discuss a common cause of bugs in Python which is checking equality of floats. Some fractions need more numbers, sometimes infinite numbers to represent accurately but in machine the number of bits are finite so when we represent floating numbers there will be a slight rounding error. You can read more on this link. Due to this sometimes we get unexpected outputs. Let us dive into the code

Code

>>> a = (0.3 * 3) + 0.1
>>> b = 1.0
>>>
>>> a == b
False
>>>
>>> b
1.0
>>> a
0.9999999999999999

We can see that a and b are not equal but using math they are equally. Logically the code is correct but our code behaves differently. This is a common mistake we make in our code. Then what is the solution

Code

>>> import math
>>>
>>> a = (0.3 * 3) + 0.1
>>> b = 1.0
>>> result = math.isclose(a, b, rel_tol=1e-9)
>>> print(result)
True

In the math module we have a method called isclose, This function checks the equality of 2 numbers with a tolerance. Here we can see that the result is True.

Hope you have learned something from this post. Please share your valuable suggestions with afsal@parseltongue.co.in