float stores numbers in binary, and that is why 0.1 cannot be represented exactly. For money, accounting or calculations that must be exact, Python offers two types in the standard library.
print(0.1 + 0.2) # 0.30000000000000004
print(0.1 + 0.2 == 0.3) # False
from decimal import Decimal, getcontext
print(Decimal("0.1") + Decimal("0.2")) # 0.3
print(Decimal("0.1") + Decimal("0.2") == Decimal("0.3")) # True
getcontext().prec = 30
print(Decimal(1) / Decimal(7)) # 0.142857142857142857142857142857
from fractions import Fraction
f = Fraction(1, 3) + Fraction(1, 6)
print(f, f.numerator, f.denominator) # 1/2 1 2
print(Fraction("3/12")) # 1/4
print(float(Fraction(1, 8))) # 0.125
import math
print(math.isclose(0.1 + 0.2, 0.3)) # True
print(2**200) # integer of unlimited precision
print(math.gcd(84, 36), math.lcm(4, 6)) # 12 12
Decimalworks in base 10 with the precision you choose. Always create it from text (Decimal("0.1")), not from afloat, or you will inherit its error.Fractionstores an integer numerator and denominator and always simplifies them, so operations are exact.- Python
inthas unlimited precision:2**200is exact.math.gcdandmath.lcmcompute the greatest common divisor and the least common multiple. - To compare
floatusemath.isclose, never==.
You practice it in Exact sum of fractions.