The Fractions module

The Fractions module in Python is a built-in module that provides support for rational number arithmetic. It allows you to work with fractions (like 1/2, 3/4, etc.) exactly, without the precision issues that can occur with floating-point numbers.

What Problems Does It Solve?

Problem with Floating-Point Numbers:

python

# Floating-point precision issue
print(0.1 + 0.2)  # Output: 0.30000000000000004 (not exact!)

Solution with Fractions:

python

from fractions import Fraction

# Exact arithmetic
print(Fraction(1, 10) + Fraction(2, 10))  # Output: 3/10 (exact!)

Key Features

1. Exact Representation

python

from fractions import Fraction

# Fractions represent numbers exactly
f1 = Fraction(1, 3)  # Exactly 1/3
f2 = Fraction(2, 3)  # Exactly 2/3

print(f1 + f2)  # Output: 1 (exactly)

2. Automatic Simplification

python

# Fractions are automatically reduced
f = Fraction(4, 8)   # Becomes 1/2
print(f)  # Output: 1/2

f = Fraction(9, 12)  # Becomes 3/4
print(f)  # Output: 3/4

3. Multiple Ways to Create Fractions

python

from fractions import Fraction

# Different creation methods
a = Fraction(1, 2) # From numerator/denominator
b = Fraction('3/4') # From string
c = Fraction(0.25) # From float (be careful!)
d = Fraction(5) # From integer (5/1)

print(a) # 1/2
print(b) # 3/4
print(c) # 1/4
print(d) # 5

Importing the Module

python

from fractions import Fraction

Creating Fractions

1. From integers (numerator/denominator)

python

# Create fraction 1/2
f1 = Fraction(1, 2)
print(f1)  # Output: 1/2

# Create fraction 3/4
f2 = Fraction(3, 4)
print(f2)  # Output: 3/4

2. From strings

python

# From string representation
f3 = Fraction('1/3')
print(f3)  # Output: 1/3

f4 = Fraction('2/5')
print(f4)  # Output: 2/5

3. From floats (be careful with this!)

python

# From float - may have precision issues
f5 = Fraction(0.5)
print(f5)  # Output: 1/2

f6 = Fraction(0.25)
print(f6)  # Output: 1/4

4. From single number (numerator with denominator 1)

python

f7 = Fraction(5)      # 5/1
print(f7)  # Output: 5

f8 = Fraction(-3)     # -3/1
print(f8)  # Output: -3

Basic Arithmetic Operations

python

# Create some fractions
a = Fraction(1, 2)  # 1/2
b = Fraction(1, 4)  # 1/4

# Addition
print(a + b)  # Output: 3/4

# Subtraction
print(a - b)  # Output: 1/4

# Multiplication
print(a * b)  # Output: 1/8

# Division
print(a / b)  # Output: 2

Accessing Numerator and Denominator

python

f = Fraction(3, 8)

print(f.numerator)    # Output: 3
print(f.denominator)  # Output: 8
print(float(f))       # Output: 0.375

Automatic Simplification

python

# Fractions are automatically simplified
f1 = Fraction(2, 4)   # Becomes 1/2
print(f1)  # Output: 1/2

f2 = Fraction(4, 8)   # Becomes 1/2
print(f2)  # Output: 1/2

f3 = Fraction(6, 9)   # Becomes 2/3
print(f3)  # Output: 2/3

Comparing Fractions

python

f1 = Fraction(1, 2)
f2 = Fraction(2, 4)
f3 = Fraction(3, 4)

print(f1 == f2)  # Output: True (both are 1/2)
print(f1 < f3)   # Output: True (1/2 < 3/4)
print(f3 > f1)   # Output: True (3/4 > 1/2)

Practical Examples

Example 1: Recipe Scaling

python

# Original recipe: 3/4 cup flour, 1/2 cup sugar
# Double the recipe
flour = Fraction(3, 4)
sugar = Fraction(1, 2)

double_flour = flour * 2
double_sugar = sugar * 2

print(f"Double flour: {double_flour} cups")  # 3/2 cups
print(f"Double sugar: {double_sugar} cups")  # 1 cup

Example 2: Pizza Sharing

python

# 3 friends sharing 2 pizzas
pizzas = Fraction(2, 1)
friends = 3

each_gets = pizzas / friends
print(f"Each friend gets: {each_gets}")  # Output: 2/3 of a pizza

Example 3: Mixed Numbers

python

# Convert improper fraction to mixed number
def to_mixed_number(fraction):
    whole = fraction.numerator // fraction.denominator
    remainder = fraction.numerator % fraction.denominator
    if whole == 0:
        return f"{remainder}/{fraction.denominator}"
    elif remainder == 0:
        return str(whole)
    else:
        return f"{whole} {remainder}/{fraction.denominator}"

f = Fraction(7, 3)  # 7/3 = 2 1/3
print(to_mixed_number(f))  # Output: 2 1/3

Important Notes

  1. Fractions are automatically reduced to their simplest form
  2. Use strings instead of floats when possible to avoid precision issues
  3. You can mix fractions with integers in calculations
  4. Negative fractions work as expected

python

# Mixing with integers
f = Fraction(1, 3)
result = f + 1  # 1/3 + 1 = 4/3
print(result)   # Output: 4/3

# Negative fractions
neg_f = Fraction(-1, 2)
print(neg_f)    # Output: -1/2

The fractions module is perfect when you need exact rational arithmetic without the rounding errors that can occur with floating-point numbers!

Similar Posts

  • Python Functions

    A function is a block of organized, reusable code that is used to perform a single, related action. Functions provide better modularity for your application and a high degree of code reusing. Defining a Function In Python, a function is defined using the def keyword, followed by the function name, a set of parentheses (),…

  • Positional-Only Arguments in Python

    Positional-Only Arguments in Python Positional-only arguments are function parameters that must be passed by position (order) and cannot be passed by keyword name. Syntax Use the / symbol in the function definition to indicate that all parameters before it are positional-only: python def function_name(param1, param2, /, param3, param4): # function body Simple Examples Example 1: Basic Positional-Only Arguments python def calculate_area(length,…

  • Vs code

    What is VS Code? 💻 Visual Studio Code (VS Code) is a free, lightweight, and powerful code editor developed by Microsoft. It supports multiple programming languages (Python, JavaScript, Java, etc.) with: VS Code is cross-platform (Windows, macOS, Linux) and widely used for web development, data science, and general programming. 🌐📊✍️ How to Install VS Code…

  • binary files

    # Read the original image and write to a new file original_file = open(‘image.jpg’, ‘rb’) # ‘rb’ = read binary copy_file = open(‘image_copy.jpg’, ‘wb’) # ‘wb’ = write binary # Read and write in chunks to handle large files while True: chunk = original_file.read(4096) # Read 4KB at a time if not chunk: break copy_file.write(chunk)…

  • positive lookahead assertion

    A positive lookahead assertion in Python’s re module is a zero-width assertion that checks if the pattern that follows it is present, without including that pattern in the overall match. It is written as (?=…). The key is that it’s a “lookahead”—the regex engine looks ahead in the string to see if the pattern inside…

  • Python Variables: A Complete Guide with Interview Q&A

    Here’s a detailed set of notes on Python variables that you can use to explain the concept to your students. These notes are structured to make it easy for beginners to understand. Python Variables: Notes for Students 1. What is a Variable? 2. Rules for Naming Variables Python has specific rules for naming variables: 3….

Leave a Reply

Your email address will not be published. Required fields are marked *