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 on paper; adding and gives exactly . 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.
Two integers:
Fraction(p, q)is the value , soFraction(1, 10)is one tenth. A denominator of 0 raisesZeroDivisionError.A string: an integer such as
'7', a ratio such as'3/7', or a decimal such as'0.1'or'7e-6'. The digits are read as an exact decimal value, soFraction('0.1')is one tenth.A
float: the result is the exact value of that float, the same ratio of integers that the float methodas_integer_ratioreturns. An infinity or a NaN (not a number) raises an exception, because neither is a ratio of integers.A
Decimalvalue of the decimal module §15.26: the result is its exact decimal value.
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 . 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 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 , the one closest to the stored value; is 1,000,000 by default. Fraction(0.1).limit_denominator() returns . 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 , 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 for some integer and some integer . Suppose . Then , 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 and are exact floats, while , and are not.
Which value the literal 0.1 becomes. One tenth lies between and . In that range a binary64 float carries 53 significant bits, the first worth , so the last is worth , and neighboring floats lie apart. The literal therefore becomes the multiple of nearest to one tenth. Since , the nearest whole number is 7205759403792794, and the float is . Dividing numerator and denominator by 2 gives the lowest terms, which is the value Fraction(0.1) returns:
The error. Subtract one tenth: which is about . 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 . So Fraction(0.1) + Fraction(0.2) is exactly Three tenths is , so the exact sum of the two floats is not three tenths. It is not the float 0.3 either, which is . By contrast, Fraction('0.1') + Fraction('0.2') == Fraction(3, 10) is True.
Stated precisely
Let be a finite float. Fraction(x) equals the real number that represents, written as in lowest terms with . Because a finite binary64 value is an integer multiplied by a power of 2, is a power of 2, at most , the denominator of the smallest positive binary64 value. Consequently Fraction(x) == x holds for every finite float .
For integers and , Fraction(p, q) equals . For a decimal string, let be the integer formed by its digits, with the decimal point removed and any sign kept; let be the number of digits after the point; and let be the exponent written after e, or 0 if there is none. Then the Fraction of the string equals exactly. For '1.25e-3', , and , so the value is .
For Fraction values and , the results of , , , with , 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, , 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 is , 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. 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 , which exceeds one tenth by , about , 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].