Published on

How to Represent Fractions Using the fractions Module in Python

Authors
  • avatar
    Name
    hwahyeon
    Twitter

This article is based on Python 3.

In Python, you can represent fractions using the fractions module. Since fractions is part of the standard library, you do not need to install it separately.

The module defines the Fraction class, so you can import it as follows.

from fractions import Fraction

Fraction is used in the form Fraction(numerator, denominator). For example, you can calculate 1/3 + 1/3 like this.

from fractions import Fraction

Fraction(1, 3) + Fraction(1, 3)

The result is as follows.

Fraction(2, 3)

In other words, Python calculates 1/3 + 1/3 and returns 2/3.

An expression made up of fractions and integers returns a Fraction object.

Fraction(1, 2) + Fraction(1, 2) + 1

The result is as follows.

Fraction(2, 1)

Fraction(2, 1) is a fraction with 1 as its denominator, so its value is the same as the integer 2.

On the other hand, if an expression includes a floating-point number, the result may not be returned as a Fraction.

Fraction(3, 4) + 2.5

The result is as follows.

3.25

You can access the numerator and denominator of a fraction using the .numerator and .denominator attributes.

f = Fraction(1, 2)

f.numerator

The result is as follows.

1
f.denominator

The result is as follows.

2