Fraction class in Python


Series Overview

This article is part of the series. Below are links to all posts in the series:
  1. Floating-Point Arithmetic
  2. Decimal Class in Python
  3. Fraction Class in Python
  4. Rounding Errors in Java

What's inside this article ⌄
  • How to use Python Fraction class
  • Rational numbers Python implementation
  • Convert fractions to decimals Python
  • Python fraction arithmetic operations

Floating Away: Slightly Unstable World of Real Number Computations. Using Fraction class in Python.


You should already know about rounding errors, floating-point arithmetic, and Decimal class and tolerance-based comparisons.

It’s time to solve the problem of dealing with rational numbers and repeating decimals. Python has a Fraction class designed for this.

Let’s create a rational number:

frac1 = Fraction(1, 3) # Represents 1/3
print(frac1.numerator) # Output: 1
print(frac1.denominator) # Output: 3

And make some operations:

result = Fraction(1, 3) + Fraction(1, 3)
print(result) # Output: 2/3
result = Fraction(2, 3) * Fraction(4, 5)
print(result) # Output: 8/15

We can compare them as well:

if Fraction(1, 2) == Fraction(2, 4):
print("Equal fractions")
if Fraction(1, 3) < Fraction(2, 5):
print("Fraction 1/3 is less than 2/5")

Or convert to float approximately:

float_value = float(Fraction(1, 3)) # 0.3333333333333333