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 Statistics Module

    Python Statistics Module: Complete Methods Guide with Examples Here’s a detailed explanation of each method in the Python statistics module with 3 practical examples for each: 1. Measures of Central Tendency mean() – Arithmetic Average python import statistics as stats # Example 1: Basic mean calculation data1 = [1, 2, 3, 4, 5] result1 = stats.mean(data1) print(f”Mean of…

  • Data hiding

    Data hiding in Python OOP is the concept of restricting access to the internal data of an object from outside the class. 🔐 It’s a way to prevent direct modification of data and protect the object’s integrity. This is typically achieved by using a naming convention that makes attributes “private” or “protected.” 🔒 How Data…

  • re Programs

    The regular expression r’;\s*(.*?);’ is used to find and extract text that is located between two semicolons. In summary, this expression finds a semicolon, then non-greedily captures all characters up to the next semicolon. This is an effective way to extract the middle value from a semicolon-separated string. Title 1 to 25 chars The regular…

  • Iterators in Python

    Iterators in Python An iterator in Python is an object that is used to iterate over iterable objects like lists, tuples, dictionaries, and sets. An iterator can be thought of as a pointer to a container’s elements. To create an iterator, you use the iter() function. To get the next element from the iterator, you…

  • Mutable vs. Immutable Objects in Python 🔄🔒

    Mutable vs. Immutable Objects in Python 🔄🔒 In Python, mutability determines whether an object’s value can be changed after creation. This is crucial for understanding how variables behave. 🤔 Immutable Objects 🔒 Example 1: Strings (Immutable) 💬 Python Example 2: Tuples (Immutable) 📦 Python Mutable Objects 📝 Example 1: Lists (Mutable) 📋 Python Example 2:…

  • Linear vs. Scalar,Homogeneous vs. Heterogeneous 

    Linear vs. Scalar Data Types in Python In programming, data types can be categorized based on how they store and organize data. Two important classifications are scalar (atomic) types and linear (compound) types. 1. Scalar (Atomic) Data Types 2. Linear (Compound/Sequential) Data Types Key Differences Between Scalar and Linear Data Types Feature Scalar (Atomic) Linear (Compound) Stores Single…

Leave a Reply

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