Python - Floating-point number comparisons


Numeric comparisons are based on magnitudes, floating-point numbers may not always work as you'd expect.

You may need conversions before you can compare them meaningfully:


print( 1.1 + 2.2 == 3.3 )             # Should be True
print( 1.1 + 2.2 )                    # Close to 3.3, but not exactly: limited precision 
print( int(1.1 + 2.2) == int(3.3) )   # OK if convert:
# from   w  w  w  .j ava 2 s  .  c  o  m


This is because floating-point numbers cannot represent some values exactly due to their limited number of bits.

Python has decimals and fractions that can address such limitations.

Related Topics