pythonfloating-point

Python Floating-Point Arithmetic comparison


I don't really understand why this comparison will still evaluate False even though they are exactly the same.

from decimal import Decimal, getcontext
getcontext().prec = 10 

x1 = 1.1 
x2 = 1.0
print( 0.1*(abs(x2 - x1)) == 0.01) ## evaluates to False. But they are mathematically equal. 
print(0.1*(abs(x2 - x1)))
print(round(Decimal(0.1)*Decimal(abs(x2 - x1)),2) == 0.01) ## evaluates to False still
print(round(Decimal(0.1)*Decimal(abs(x2 - x1)),2))
print(0.01)

How else can I manipulate it such that it compares correctly?


Solution

  • Decimal(0.1)
    

    This does first create float (with all its' limitations w.r.t precision) and then convert it to Decimal instance, use string representation to avoid that, consider that

    from decimal import Decimal
    print(Decimal(0.1)+Decimal(0.1)+Decimal(0.1)==Decimal(0.3))  # False
    print(Decimal("0.1")+Decimal("0.1")+Decimal("0.1")==Decimal("0.3"))  # True