Python Decimal and fraction

Decimal and fraction

Python provides two additional numeric types in standard library modules — decimal is a fixed-precision, floating-point number, and fraction is a rational type that keeps numerator and denominator explicitly. Both may be used to address inaccuracies of floating-point arithmetic:

0.1 – 0.3 -0.19999999999999998 >>> from decimal import Decimal >>> Decimal(‘0.1’) – Decimal(‘0.3’) Decimal(‘-0.2’) >>> from fractions import Fraction >>> Fraction(1, 10) – Fraction(3, 10) Fraction(-1, 5) >>> Fraction(1, 3) + Fraction(7, 6) Fraction(3, 2)

Fractions automatically simplify results. By fixing precision and supporting various truncation and rounding protocols, decimals are useful for monetary applications. See the Python Library Reference for details.

Fair Use Source: B00HZ41PGC