Representing Rational Numbers With Python Fractions

Representing Rational Numbers With Python Fractions

by Bartosz Zaczyński Reading time estimate 48m basics python stdlib

The fractions module in Python is arguably one of the most underused elements of the standard library. Even though it may not be well-known, it’s a useful tool to have under your belt because it can help address the shortcomings of floating-point arithmetic in binary. That’s essential if you plan to work with financial data or if you require infinite precision for your calculations.

Towards the end of this tutorial, you’ll see a few hands-on examples where fractions are the most suitable and elegant choice. You’ll also learn about their weaknesses and how to make the best use of them along the way.

In this tutorial, you’ll learn how to:

  • Convert between decimal and fractional notation
  • Perform rational number arithmetic
  • Approximate irrational numbers
  • Represent fractions exactly with infinite precision
  • Know when to choose Fraction over Decimal or float

The majority of this tutorial goes over the fractions module, which in itself doesn’t require in-depth Python knowledge other than an understanding of its numeric types. However, you’ll be in a good place to work through all the code examples that follow if you’re familiar with more advanced concepts such as Python’s built-in collections module, itertools module, and generators. You should already be comfortable with these topics if you want to make the most out of this tutorial.

Decimal vs Fractional Notation

Let’s take a walk down memory lane to bring back your school knowledge of numbers and avoid possible confusion. There are four concepts at play here:

  1. Types of numbers in mathematics
  2. Numeral systems
  3. Notations of numbers
  4. Numeric data types in Python

You’ll get a quick overview of each of these now to better understand the purpose of the Fraction data type in Python.

Classification of Numbers

If you don’t remember the classification of numbers, here’s a quick refresher: