Alternative - the :mod:`decimal` module ======================================= .. sectionauthor:: Florian Mayer The decimal module offers you a way to calculate floating-point numbers precisely with any degree of accuracy. Simply put, the :mod:`decimal` module allows you to do maths the way you learnt it in school. :: >>> from decimal import Decimal >>> Decimal(1) / Decimal(3) Decimal("0.3333333333333333333333333333") As you can see, it provides a representation of 1/3 accurate to 28 decimal places, which is the default. You can easily alter the accuracy if you need to. :: >>> from decimal import getcontext, Decimal >>> getcontext().prec = 5 >>> Decimal(1) / Decimal(3) Decimal('0.33333') If you want to create a decimal object out of a float, you first have to convert it to a string. :: >>> Decimal(0.5) Traceback (most recent call last): File "", line 1, in TypeError: Cannot convert float to Decimal. First convert the float to a string >>> Decimal('0.5') Decimal('0.5') The :mod:`fractions` module - a different approach ================================================== Both the decimal and the float type try to represent a floating-point number. The problem is, that there are numbers which cannot be represented by a floating-point number. Let us take 1/3 as an example. No matter how many decimal places you calculate, you can only approximate the real value of 1/3. So what the :mod:`fractions` module does is offering you a way to do fractional arithmetic in Python. This module is the excellent choice if you do not care about the floating-point value of a number, but still want to work with it. They behave the way you would expect fractions to behave and you can use all the arithmetic operations on them. :: >>> from fractions import Fraction >>> Fraction(1, 3) Fraction(1, 3) >>> Fraction(1, 3) * 3 Fraction(1, 1) >>> Fraction(1, 3) ** 3 Fraction(1, 27) You can also use the arithmetic operations on two fractions. :: >>> Fraction(1, 3) + Fraction(2, 3) Fraction(1, 1) >>> Fraction(1) / Fraction(3) Fraction(1, 3) >>> Fraction(3) / Fraction(9) # It even supports reducing Fraction(1, 3) One thing you have to be aware of when comparing Fractions to other numeric values is the representation error of both the decimal and the float type. :: >>> Fraction(1, 3) + Fraction(2, 3) == 1 True >>> Fraction(1, 3) == 1/3 False >>> Fraction(1, 3) == Decimal(1)/Decimal(3) False You can even convert floats and Decimals to Fractions, but be aware that floating-point calculation limitations also apply here. :: >>> from decimal import Decimal >>> Fraction.from_decimal(Decimal(1) / Decimal(3)) Fraction(3333333333333333333333333333, 10000000000000000000000000000) >>> Fraction.from_float(1/3) Fraction(6004799503160661, 18014398509481984) If you are fine with the result of a fraction, the fractions module is probably the best choice for you as it is the only way to accurately represent numbers with periodic decimal expansions.