Handling Fractions in Python: Accurate Rational Number Calculations using the fractions Module

When handling decimals in computers, using floating-point numbers (float) can cause errors because numbers like 1/3 become 0.3333... and cannot be represented exactly.

If you want to maintain and calculate exact values as mathematical “fractions (rational numbers),” use the Python standard library fractions module.

This article explains how to create fractions using the Fraction class and how to implement arithmetic operations.

目次

Creating Fraction Objects

Import the Fraction class from the fractions module to use it. You can create a fraction by specifying the “numerator” and “denominator” as arguments. You can also create one from a string.

Syntax:

from fractions import Fraction

# Method 1: Specify numbers Fraction(numerator, denominator)
f1 = Fraction(1, 3)

# Method 2: Specify a string
f2 = Fraction("1/3")

Automatic Reduction

The Fraction class automatically reduces (simplifies) the fraction upon creation.

from fractions import Fraction

# 2/8 automatically becomes 1/4
f_reduced = Fraction(2, 8)

print(f"Reduced result: {f_reduced}")

Execution Result:

Plaintext

Reduced result: 1/4

Specific Usage Example: Calculating Recipe Quantities

As an example, let’s create a program to calculate cooking ingredients (in cups). We will handle 1/2 cup of flour and 1/3 cup of sugar.

from fractions import Fraction

# Define ingredients
flour_cup = Fraction(1, 2)  # Flour 1/2
sugar_cup = Fraction(1, 3)  # Sugar 1/3

print(f"Flour: {flour_cup} cup")
print(f"Sugar: {sugar_cup} cup")
print("-" * 20)

# 1. Addition (Total amount)
# Calculated with a common denominator (1/2 + 1/3 = 3/6 + 2/6 = 5/6)
total_amount = flour_cup + sugar_cup
print(f"Total: {total_amount} cup")

# 2. Subtraction (Difference)
# (1/2 - 1/3 = 3/6 - 2/6 = 1/6)
diff_amount = flour_cup - sugar_cup
print(f"Difference: {diff_amount} cup")

# 3. Multiplication (Doubling the amount)
# Quadruple the flour (1/2 * 4 = 2)
bulk_flour = flour_cup * 4
print(f"Flour x4: {bulk_flour} cup")

# 4. Division (Distribution)
# Split sugar in half (1/3 / 2 = 1/6)
split_sugar = sugar_cup / 2
print(f"Sugar / 2: {split_sugar} cup")

Execution Result:

Flour: 1/2 cup
Sugar: 1/3 cup
--------------------
Total: 5/6 cup
Difference: 1/6 cup
Flour x4: 2 cup
Sugar / 2: 1/6 cup

As you can see, accurate fraction calculations are performed without worrying about finding common denominators or reducing fractions manually.

Getting Numerator/Denominator and Type Conversion

You can extract the numerator and denominator from the created fraction object, or convert it to a float.

ratio = Fraction(3, 7)

# Get numerator (.numerator)
print(f"Numerator: {ratio.numerator}")

# Get denominator (.denominator)
print(f"Denominator: {ratio.denominator}")

# Convert to float
print(f"Float value: {float(ratio)}")

Execution Result:

Numerator: 3
Denominator: 7
Float value: 0.42857142857142855

Summary

  • Use the Fraction class in the fractions module for accurate numerical calculations.
  • Create fractions using Fraction(numerator, denominator), and they will be automatically reduced.
  • It supports arithmetic operations (+, -, *, /), and the result remains a Fraction type (unless calculated with a float).
  • This is suitable for probability calculations or when you want to maintain exact ratios.
よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次