1 min read

Python Fractions Module

The fractions module provides support for rational number arithmetic. A Fraction instance can be constructed from a pair of integers, from another rational number, or from a string.

Importing the Module

from fractions import Fraction

Creating Fractions

From Integers

You can create a Fraction by passing the numerator and denominator.

from fractions import Fraction

f = Fraction(3, 4)
print(f) # Output: 3/4

From Strings

print(Fraction('3/7')) # Output: 3/7
print(Fraction(' -3/7 ')) # Output: -3/7
print(Fraction('1.41421356')) # Output: 141421356/100000000

From Floats

Creating a Fraction from a float can lead to unexpected results due to floating-point representation issues.

print(Fraction(1.1))
# Output: 2476979795053773/2251799813685248

From Decimals

Creating from a Decimal instance usually gives the expected result.

from decimal import Decimal
print(Fraction(Decimal('1.1'))) # Output: 11/10

Arithmetic Operations

Fractions support standard arithmetic operations.

a = Fraction(1, 2)
b = Fraction(1, 3)

print(a + b) # Output: 5/6
print(a - b) # Output: 1/6
print(a * b) # Output: 1/6
print(a / b) # Output: 3/2

Limiting Denominator

The limit_denominator() method finds the closest rational number to a given float (or Fraction) with a denominator no larger than the argument.

import math
from fractions import Fraction

print(Fraction(math.pi).limit_denominator(10))  # Output: 22/7

programming/python/python