Python Fractions Module for Rational Numbers
Python's built-in fractions module provides support for
rational number arithmetic, allowing numbers to be represented precisely
as ratios of integers. This module resolves the inherent rounding errors
associated with floating-point calculations by storing values as
explicit numerators and denominators. This article covers the core
capabilities of the fractions.Fraction class, how to create
and manipulate rational numbers, and how it handles arithmetic
operations with mathematical exactness.
The Fraction Class
The primary component of the module is the Fraction
class, which implements the numbers.Rational abstract base
class. A Fraction instance represents an exact rational
number \(a / b\), where \(a\) (the numerator) and \(b\) (the denominator) are integers, and
\(b \neq 0\).
Instantiation and Input Types
The Fraction constructor can accept multiple data types
to create a rational number:
- Two Integers: Passing a numerator and a denominator
directly.
from fractions import Fraction f = Fraction(3, 4) # Represents 3/4
* **Strings:** Parsing fractional strings or decimal strings.
```python
f1 = Fraction("3/4") # 3/4
f2 = Fraction("0.75") # 3/4
- Floats and Decimals: Converting existing
floating-point values or
decimal.Decimalobjects into rational equivalents.f = Fraction(0.5) # 1/2
When passing a float, the constructor translates the exact binary representation into a fraction. Because standard floats cannot represent values like `0.1` precisely in binary, `Fraction(0.1)` yields `3602879701896397 / 36028797018963968`. Passing a string such as `Fraction('0.1')` avoids this issue and yields `1/10`.
### Automatic Simplification and Sign Normalization
The `fractions` module automatically simplifies values to their lowest terms using the greatest common divisor (GCD). It also normalizes negative signs so that the denominator is always strictly positive:
```python
f = Fraction(10, 20) # Automatically reduced to 1/2
negative_f = Fraction(5, -10) # Normalized to -1/2
Accessing Numerator and Denominator
Every Fraction object exposes read-only properties to
access its components:
Fraction.numerator: Returns the integer numerator.Fraction.denominator: Returns the integer denominator.
f = Fraction(7, 3)
print(f.numerator) # Output: 7
print(f.denominator) # Output: 3Exact Arithmetic Operations
The Fraction class integrates with Python’s standard
mathematical operators, including +, -,
*, /, //, %, and
**. Operations between two fractions produce an exact
fraction:
a = Fraction(1, 3)
b = Fraction(1, 6)
print(a + b) # Output: 1/2
print(a * b) # Output: 1/18When combined with integers, the result remains a
Fraction. However, combining a Fraction with a
float coerces the result into a standard
float, discarding exact rational precision.
Approximating
Floats with limit_denominator()
The module provides the
limit_denominator(max_denominator=1000000) method, which
finds the closest rational approximation to a given fraction or
floating-point value whose denominator does not exceed the specified
limit:
import math
pi_fraction = Fraction(math.pi).limit_denominator(10) # Output: 22/7
precise_pi = Fraction(math.pi).limit_denominator(1000) # Output: 355/113This method is especially useful for recovering simple fractions from imprecise floating-point inputs.