Python - Floating-point number comparisons

Introduction

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:

Demo

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:
# ww w . ja v  a  2 s  .c  o  m

Result

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