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 and PyCharm Installation on Windows: Complete Beginner’s Guide 2025

    Installing Python and PyCharm on Windows is a straightforward process. Below are the prerequisites and step-by-step instructions for installation. Prerequisites for Installing Python and PyCharm on Windows Step-by-Step Guide to Install Python on Windows Step 1: Download Python Step 2: Run the Python Installer Step 3: Verify Python Installation If Python is installed correctly, it…

  • File Handling in Python

    File Handling in Python File handling is a crucial aspect of programming that allows you to read from and write to files. Python provides built-in functions and methods to work with files efficiently. Basic File Operations 1. Opening a File Use the open() function to open a file. It returns a file object. python # Syntax: open(filename,…

  • Random Module?

    What is the Random Module? The random module in Python is used to generate pseudo-random numbers. It’s perfect for: Random Module Methods with Examples 1. random() – Random float between 0.0 and 1.0 Generates a random floating-point number between 0.0 (inclusive) and 1.0 (exclusive). python import random # Example 1: Basic random float print(random.random()) # Output: 0.5488135079477204 # Example…

  • file properties and methods

    1. file.closed – Is the file door shut? Think of a file like a door. file.closed tells you if the door is open or closed. python # Open the file (open the door) f = open(“test.txt”, “w”) f.write(“Hello!”) print(f.closed) # Output: False (door is open) # Close the file (close the door) f.close() print(f.closed) # Output: True (door is…

  • Programs

    Weekly Wages Removing Duplicates even ,odd Palindrome  Rotate list Shuffle a List Python random Module Explained with Examples The random module in Python provides functions for generating pseudo-random numbers and performing random operations. Here’s a detailed explanation with three examples for each important method: Basic Random Number Generation 1. random.random() Returns a random float between 0.0 and 1.0 python import…

  • Date/Time Objects

    Creating and Manipulating Date/Time Objects in Python 1. Creating Date and Time Objects Creating Date Objects python from datetime import date, time, datetime # Create date objects date1 = date(2023, 12, 25) # Christmas 2023 date2 = date(2024, 1, 1) # New Year 2024 date3 = date(2023, 6, 15) # Random date print(“Date Objects:”) print(f”Christmas:…

Leave a Reply

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