Floating Point Arithmetic You may have noticed that when doing arithmetic with floats in Python you sometimes get strange results, like this:
Why this happens Internally your computer stores floats as binary fractions. Many decimal values cannot be stored as exact binary fractions, which means an approximation has to be used.
>>> 0.1 + 0.2 0.30000000000000004
Note that with
>>> math.isclose(0.1 + 0.2, 0.3) True >>> decimal.Decimal('0.1') + decimal.Decimal('0.2') Decimal('0.3')
decimal.Decimalwe enter the number we want as a string so we don't pass on the imprecision from the float.