Fractions Python: Create, Convert, and Calculate

Calculating with fractions in Python lets you work with values as ratios. The fractions module provides Fraction, which represents rational numbers as ratios of integers for arithmetic.

I’ll show how to create fractions from decimal text and add them.

TL;DR

Python’s fractions module represents rational values as integer ratios for exact arithmetic.

  • Import Fraction and pass integers or decimal text.
  • Use Fraction(“0.4”) when the written decimal is the intended value.
  • Use limit_denominator() when a nearby bounded ratio is acceptable.

What Is the Python fractions Module?

The fractions module is part of Python’s standard library. It provides Fraction for rational-number arithmetic, where a rational number is one integer divided by another nonzero integer.

For example, constructing a value from 3 and 6 prints as 1/2. The numerator and denominator properties let code inspect its components. I use Fraction for this ratio because the demo prints its reduced value directly.

A Fraction can also be converted to float for a display or an API that requires floating-point input. That conversion may round a repeating ratio, so keep the Fraction object while later calculations still need the exact rational value. Python’s fractions documentation also describes rounding to an integer or a specified decimal-place multiple, with ties rounded to even.

  • Fraction instances are immutable.
  • Use numerator and denominator to inspect a value’s integer parts.
  • Use as_integer_ratio() when an API needs the pair as a tuple.

How to Create and Calculate Fractions in Python

Construct a Fraction from integer parts or text, then use Python arithmetic operators. The examples below show each input choice and its effect.

Step 1: Create a fraction from integers

Pass the numerator and a nonzero denominator to Fraction. Inspect the properties when another function needs separate integer parts.

from fractions import Fraction

portion = Fraction(3, 6)
print(portion)
print(portion.numerator, portion.denominator)

The two output lines are 1/2 and 1 2. The second line prints the numerator and denominator properties.

Step 2: Convert decimal text without float noise

The example output follows. A string and float constructor differ because the float already stores a binary approximation.

from decimal import Decimal
from fractions import Fraction

ratio = Fraction(3, 6)
print(ratio)
print(Fraction("0.4"))
print(Fraction(0.4))
print(Fraction(Decimal("1.1")))
print(Fraction(0.4).limit_denominator(10))

The output, in order, is 1/2, 2/5, 3602879701896397/9007199254740992, 11/10 and 2/5, each on its own line. Decimal text expresses the written value, while the float constructor uses the exact stored float.

Terminal showing Fraction constructor output
Python output for integer, text, float and Decimal constructors.

Step 3: Add and compare rational values

Fraction values support addition and equality comparisons. This example checks whether two inputs sum to one half.

from fractions import Fraction

first = Fraction("1/3")
second = Fraction("1/6")
total = first + second
print(total)
print(total == Fraction(1, 2))

The two printed values are 1/2 and True. Together they show the computed total and the result of the comparison.

Step 4: Bound a rational approximation

Call limit_denominator(max_denominator) to find a nearby ratio with a denominator no larger than the supplied bound. Set the bound according to the measurement or ratio being modeled.

from fractions import Fraction

measured = Fraction(0.4)
print(measured.limit_denominator(10))

This bound returns 2/5. It does not establish that the original measurement was exactly that ratio.

Edge Cases When Using Fraction

Input type and denominator validity determine how Fraction interprets or rejects a value. I ran the zero-denominator probe, which raised ZeroDivisionError: Fraction(1, 0).

CaseSymptomFix
Float input such as 0.4A large ratio represents the stored binary float.Pass decimal text when its written digits define the intended value.
Zero denominatorFraction(1, 0) raises ZeroDivisionError: Fraction(1, 0).Validate an input denominator before construction.
Repeating decimal displayOne third has no finite decimal representation.Keep a rational value for calculation and convert only for display.
Repeated calculations with large valuesLarge numerators and denominators can increase computation and memory use.Measure the workload and change representation only if the task permits approximation.

Conclusion

Choose the constructor according to whether the input means an integer ratio, written decimal or stored float.

FAQ

These answers cover common conversion and display questions.

How do I convert a decimal to a fraction in Python?

Pass decimal text to Fraction, such as Fraction(“0.4”), to get 2/5. A float input preserves its exact stored binary value.

How do I print a fraction in Python?

Print a Fraction value directly. Python displays its ratio, such as 1/2.

How can I limit a fraction denominator?

Call limit_denominator(max_denominator) to get a nearby fraction whose denominator does not exceed the bound.

Safa Mulani
Safa Mulani

An enthusiast in every forthcoming wonders!

Articles: 189