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

  • group() and groups()

    Python re group() and groups() Methods Explained The group() and groups() methods are used with match objects to extract captured groups from regex patterns. They work on the result of re.search(), re.match(), or re.finditer(). group() Method groups() Method Example 1: Basic Group Extraction python import retext = “John Doe, age 30, email: john.doe@email.com”# Pattern with multiple capture groupspattern = r'(\w+)\s+(\w+),\s+age\s+(\d+),\s+email:\s+([\w.]+@[\w.]+)’///The Pattern: r'(\w+)\s+(\w+),\s+age\s+(\d+),\s+email:\s+([\w.]+@[\w.]+)’Breakdown by Capture…

  • Why Python is So Popular: Key Reasons Behind Its Global Fame

    Python’s fame and widespread adoption across various sectors can be attributed to its unique combination of simplicity, versatility, and a robust ecosystem. Here are the key reasons why Python is so popular and widely used in different industries: 1. Easy to Learn and Use 2. Versatility Python supports multiple programming paradigms, including: This versatility allows…

  • ASCII ,Uni Code Related Functions in Python

    ASCII Code and Related Functions in Python ASCII (American Standard Code for Information Interchange) is a character encoding standard that assigns numerical values to letters, digits, punctuation marks, and other characters. Here’s an explanation of ASCII and Python functions that work with it. ASCII Basics Python Functions for ASCII 1. ord() – Get ASCII value of a…

  • Lambda Functions in Python

    Lambda Functions in Python Lambda functions are small, anonymous functions defined using the lambda keyword. They can take any number of arguments but can only have one expression. Basic Syntax python lambda arguments: expression Simple Examples 1. Basic Lambda Function python # Regular function def add(x, y): return x + y # Equivalent lambda function add_lambda =…

  • math Module

    The math module in Python is a built-in module that provides access to standard mathematical functions and constants. It’s designed for use with complex mathematical operations that aren’t natively available with Python’s basic arithmetic operators (+, -, *, /). Key Features of the math Module The math module covers a wide range of mathematical categories,…

Leave a Reply

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