Section 15.25

fractions module

Definition

The fractions module is the module of the Python §12.23 standard library that provides the class Fraction. A Fraction holds a rational number exactly, as a ratio of two integers: a numerator and a positive denominator with no common factor. Arithmetic and comparison between Fraction values are exact, because Python integers have no fixed size. A Fraction can be built from integers, from a string such as '0.1', or from a binary floating-point §4.49 number; built from a floating-point number, it holds that number’s exact value, not the decimal the programmer typed.

The idea

A program splits quantities into exact proportions and must never round: one tenth plus two tenths must equal three tenths. Python’s built-in float type cannot promise this. A float is a binary floating-point number in the IEEE 754 binary64 format [271]: a whole number of at most 53 binary digits, called the significand, multiplied by a power of 2. One tenth is not of that form, so the literal 0.1 in source code is rounded to the nearest value that is, and 0.1 + 0.2 evaluates to 0.30000000000000004.

Fraction avoids rounding by keeping the numerator and the denominator as integers, the way a person writes 1/101/10 on paper; adding 1/101/10 and 2/102/10 gives exactly 3/103/10. The weak point is the entrance. Fraction(0.1) receives a float, and the rounding already happened when Python read the literal 0.1; the intended one tenth no longer exists anywhere in the program. Fraction records the value it receives exactly, so it keeps the rounding error exactly. A photocopier is a fair picture: a perfect copy of a slightly wrong drawing is still slightly wrong. The picture stops in one respect: here the error is known to the last digit, as the worked example shows.

How it works

Construction. Fraction accepts four kinds of input.

Normalization. The class divides the numerator and the denominator by their greatest common divisor and moves any minus sign to the numerator, so Fraction(6, -4) is stored as −3/2-3/2. Two equal values therefore always have the same numerator and the same denominator.

Arithmetic. Between two Fraction values, or between a Fraction and an integer, addition, subtraction, multiplication, division and comparison are exact. Addition, for example, computes a/b+c/d=(ad+cb)/(bd)a/b + c/d = (ad + cb)/(bd) with integer arithmetic and then reduces the result to lowest terms; Python integers grow as needed, so no step overflows. Two mixtures leave exact arithmetic. A Fraction combined with a float by an arithmetic operator gives a float, because the Fraction is first rounded to a float. A Fraction raised to a power that is not a whole number also gives a float. Comparisons between a Fraction and a float stay exact.

Guessing a simple ratio. The method limit_denominator(n) returns, among all fractions whose denominator is at most nn, the one closest to the stored value; nn is 1,000,000 by default. Fraction(0.1).limit_denominator() returns 1/101/10. This is a guess at the intent, not a recovery of lost information: the intended value need not be the nearest simple ratio. If it was 1/10000031/1000003, a limit of 1,000,000 can never return it.

Worked example

Why one tenth is not a binary floating-point value. Every finite float equals m/2km/2^{k} for some integer mm and some integer k≥0k \ge 0. Suppose 1/10=m/2k1/10 = m/2^{k}. Then 2k=10m=2×5×m2^{k} = 10m = 2 \times 5 \times m, so 5 would divide a power of 2, which is impossible. The same argument shows that a ratio in lowest terms can be stored exactly as a float only if its denominator is a power of 2. So 1/2=0.51/2 = 0.5 and 3/8=0.3753/8 = 0.375 are exact floats, while 1/101/10, 1/51/5 and 1/31/3 are not.

Which value the literal 0.1 becomes. One tenth lies between 2−4=0.06252^{-4} = 0.0625 and 2−3=0.1252^{-3} = 0.125. In that range a binary64 float carries 53 significant bits, the first worth 2−42^{-4}, so the last is worth 2−4−52=2−562^{-4-52} = 2^{-56}, and neighboring floats lie 2−562^{-56} apart. The literal therefore becomes the multiple of 2−562^{-56} nearest to one tenth. Since 0.1×256=7205759403792793.60.1 \times 2^{56} = 7205759403792793.6, the nearest whole number is 7205759403792794, and the float is 7205759403792794/2567205759403792794/2^{56}. Dividing numerator and denominator by 2 gives the lowest terms, which is the value Fraction(0.1) returns: 3602879701896397255=360287970189639736028797018963968.\frac{3602879701896397}{2^{55}} = \frac{3602879701896397}{36028797018963968}.

The error. Subtract one tenth: 3602879701896397255−110=10×3602879701896397−25510×255=36028797018963970−3602879701896396810×255=210×255=15×255=1180143985094819840,\begin{aligned} \frac{3602879701896397}{2^{55}} - \frac{1}{10} &= \frac{10 \times 3602879701896397 - 2^{55}}{10 \times 2^{55}} \\ &= \frac{36028797018963970 - 36028797018963968}{10 \times 2^{55}} \\ &= \frac{2}{10 \times 2^{55}} = \frac{1}{5 \times 2^{55}} = \frac{1}{180143985094819840}, \end{aligned} which is about 5.55×10−185.55 \times 10^{-18}. The float is slightly larger than one tenth, so Fraction(1, 10) < 0.1 is True and Fraction(1, 10) == 0.1 is False.

Exact arithmetic keeps the error. By the same method, the float 0.2 is 7205759403792794/2557205759403792794/2^{55}. So Fraction(0.1) + Fraction(0.2) is exactly 3602879701896397+7205759403792794255=10808639105689191255.\frac{3602879701896397 + 7205759403792794}{2^{55}} = \frac{10808639105689191}{2^{55}}. Three tenths is 10808639105689190.4/25510808639105689190.4/2^{55}, so the exact sum of the two floats is not three tenths. It is not the float 0.3 either, which is 10808639105689190/25510808639105689190/2^{55}. By contrast, Fraction('0.1') + Fraction('0.2') == Fraction(3, 10) is True.

Stated precisely

Let xx be a finite float. Fraction(x) equals the real number that xx represents, written as p/qp/q in lowest terms with q>0q > 0. Because a finite binary64 value is an integer multiplied by a power of 2, qq is a power of 2, at most 210742^{1074}, the denominator of the smallest positive binary64 value. Consequently Fraction(x) == x holds for every finite float xx.

For integers pp and q≠0q \ne 0, Fraction(p, q) equals p/qp/q. For a decimal string, let DD be the integer formed by its digits, with the decimal point removed and any sign kept; let kk be the number of digits after the point; and let EE be the exponent written after e, or 0 if there is none. Then the Fraction of the string equals D×10E−kD \times 10^{E-k} exactly. For '1.25e-3', D=125D = 125, k=2k = 2 and E=−3E = -3, so the value is 125×10−5=1/800125 \times 10^{-5} = 1/800.

For Fraction values aa and bb, the results of a+ba + b, a−ba - b, a×ba \times b, a/ba / b with b≠0b \ne 0, and of every comparison, are the exact rational results. This guarantee has one assumption: the computer has enough memory and time for the integers involved, whose size the module does not limit.

No function can recover from a float alone the decimal that a programmer intended, because many decimals round to the same float: the literals 0.1 and 0.10000000000000000555 produce the same float.

Limits and common mistakes

Exactness applies to the value supplied. Build a Fraction from integers or from a decimal string, not from a float that already holds a rounded value. A Fraction computed from float data is an exact record of the rounded values, not of the quantities they approximate.

Mixing types leaves exact arithmetic without warning. Fraction(1, 10) + 0.2 returns the float 0.30000000000000004. Combining a Fraction with a Decimal by an arithmetic operator raises TypeError.

Irrational results are out of reach. Square roots, π\pi, logarithms and the other functions of the math module return float values, and Fraction(2) ** Fraction(1, 2) returns the float 1.4142135623730951.

Numerators and denominators can grow quickly. The exact sum 1/1+1/2+…+1/301/1 + 1/2 + \dots + 1/30 is 9304682830147/23290895628009304682830147/2329089562800, whose denominator already has 13 digits, and long calculations can produce integers with thousands of digits. Each operation costs more as the integers grow, so a program that accepts fractions from untrusted input should limit their size; otherwise crafted inputs can make it very slow, an algorithmic complexity attack §15.35.

Exact is not the same as decimal. 1/31/3 is exact as a Fraction but has no finite decimal form, so printing it as a decimal number, or paying it out as an amount of money, still needs a rounding rule. For decimal amounts rounded by a stated rule, the decimal module fits better.

Questions answered

Why is Fraction constructed from a float not always the intended decimal ratio?

A Fraction constructed from a float holds the exact value of that float, and that value is usually not the decimal the programmer wrote, because the decimal was rounded to binary when the float was created. A Python float is a binary floating-point number: an integer of at most 53 bits multiplied by a power of 2. A ratio in lowest terms can therefore be a float only if its denominator is a power of 2. The literal 0.5 is exact, but 0.1 becomes 3602879701896397/2553602879701896397/2^{55}, which exceeds one tenth by 1/1801439850948198401/180143985094819840, about 5.55×10−185.55 \times 10^{-18}, and Fraction(0.1) returns exactly that ratio.

Fraction cannot undo the earlier rounding, because many different decimals round to the same float. To get the intended ratio, build it from integers, as Fraction(1, 10), or from the decimal string, as Fraction('0.1').

Related entries: decimal module (§15.26), JSON (§12.26), NumPy (§12.29), Binary floating-point representation, special values, and rounding (§4.49), Algorithmic complexity attack (§15.35). Further reading: [142, 187, 271].