Python Reference ยท Standard Library: Math, Data and Text
The fractions module
Reference for Python's fractions module: create Fraction values, exact arithmetic, limit_denominator, conversion from floats and strings, and common pitfalls.
The fractions module provides the Fraction class: an exact rational number made of an integer numerator and a positive integer denominator. Arithmetic on fractions never loses precision, and results are always reduced to lowest terms, so Fraction(1, 3) + Fraction(1, 6) is exactly Fraction(1, 2).
Use it when you need exact ratios (recipes, probabilities, musical intervals, teaching examples) or to see what a float really contains. For decimal amounts such as prices, decimal is usually the better match.
from fractions import Fraction print(Fraction(1, 3) + Fraction(1, 6))
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Frequently used names
| Name | Description |
|---|---|
Fraction(numerator=0, denominator=1) |
Two ints (or two rationals). Reduces to lowest terms and keeps the sign on the numerator. |
Fraction(value) |
From an int, a float, a Decimal, another Fraction, or a string such as "3/4", "0.125", "1e-2". |
numerator, denominator |
Read-only parts of the reduced fraction. |
limit_denominator(max_denominator=10**6) |
The closest fraction whose denominator does not exceed the limit. Useful for turning floats into nice ratios. |
as_integer_ratio() |
A (numerator, denominator) tuple (3.8+). |
is_integer() |
True when the denominator is 1 (3.12+). |
from_float(x), from_decimal(d) |
Alternative constructors. Passing the value to Fraction() directly works the same. |
+, -, *, /, //, %, **, divmod(), round(), abs(), comparisons |
Work with fractions, ints and (inexactly) floats. |
Usage notes
- Results stay exact only while all operands are exact. Mixing a
Fractionwith afloatgives afloat; mixing with anintor anotherFractiongives aFraction. Fraction(0.1)is not1/10. The float0.1is slightly more than a tenth, so the fraction has a huge denominator. Pass the string"0.1"for the intended value, or uselimit_denominator()to recover a simple ratio from a float.- Equality and hashing match numbers.
Fraction(1, 2) == 0.5is true andhash(Fraction(2, 1)) == hash(2), so fractions can be dictionary keys alongside ints. Comparisons with floats are exact, not approximate. - Denominator zero raises
ZeroDivisionError. Invalid text raisesValueError. Dividing byFraction(0)raisesZeroDivisionErroras well. round()with no digits rounds half to even, as it does for floats, and returns anint. With digits it returns aFraction.- Sizes can explode. Repeated arithmetic can make numerators and denominators very large. Summing 1/1 through 1/1000 produces a denominator with hundreds of digits. Call
limit_denominator()when you only need an approximation. str()andrepr()differ.print(Fraction(4, 2))shows2, whilerepr()showsFraction(2, 1). Usenumeratoranddenominatorwhen you need the pieces.- Alternatives:
decimal.Decimalfor base-10 amounts with a chosen precision;floatwhen speed matters more than exactness;statisticsaccepts fractions and returns exact means.
Related
decimal,math,statistics,divmod(),round()- Lessons: Numbers, Math and random