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

  • Closure Functions in Python

    Closure Functions in Python A closure is a function that remembers values from its enclosing lexical scope even when the program flow is no longer in that scope. Simple Example python def outer_function(x): # This is the enclosing scope def inner_function(y): # inner_function can access ‘x’ from outer_function’s scope return x + y return inner_function…

  • Functions as Parameters in Python

    Functions as Parameters in Python In Python, functions are first-class objects, which means they can be: Basic Concept When we pass a function as a parameter, we’re essentially allowing one function to use another function’s behavior. Simple Examples Example 1: Basic Function as Parameter python def greet(name): return f”Hello, {name}!” def farewell(name): return f”Goodbye, {name}!” def…

  • recursive function

    A recursive function is a function that calls itself to solve a problem. It works by breaking down a larger problem into smaller, identical subproblems until it reaches a base case, which is a condition that stops the recursion and provides a solution to the simplest subproblem. The two main components of a recursive function…

  • Python Exception Handling – Basic Examples

    1. Basic try-except Block python # Basic exception handlingtry: num = int(input(“Enter a number: “)) result = 10 / num print(f”Result: {result}”)except: print(“Something went wrong!”) Example 1: Division with Zero Handling python # Handling division by zero error try: num1 = int(input(“Enter first number: “)) num2 = int(input(“Enter second number: “)) result = num1 /…

  • 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,…

  • Basic Character Classes

    Basic Character Classes Pattern Description Example Matches [abc] Matches any single character in the brackets a, b, or c [^abc] Matches any single character NOT in the brackets d, 1, ! (not a, b, or c) [a-z] Matches any character in the range a to z a, b, c, …, z [A-Z] Matches any character in the range A to Z A, B, C, …, Z [0-9] Matches…

Leave a Reply

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