fractions
The Python fractions module provides support for rational number arithmetic. It allows you to create and manipulate fractions with numerators and denominators, enabling precise calculations without floating-point errors.
Here’s a quick example:
Python
>>> from fractions import Fraction
>>> Fraction(1, 3) + Fraction(2, 3) # 1/3 + 2/3
Fraction(1, 1)
Key Features
Frequently Used Classes and Functions
| Object | Type | Description |
|---|---|---|
fractions.Fraction |
Class | Represents a rational number as a fraction |
Fraction.limit_denominator() |
Method | Finds the closest Fraction with a denominator at most a given value |
Fraction.as_integer_ratio() |
Method | Returns a tuple of two integers, whose ratio is equal to the original Fraction |
Examples
Creating fractions from integers:
Python
>>> Fraction(3, 4)
Fraction(3, 4)
Creating fractions from floats:
Python
>>> Fraction(0.75)
Fraction(3, 4)
Creating fractions from strings:
Python
>>> Fraction("0.75")
Fraction(3, 4)
Common Use Cases
- Performing precise arithmetic operations with fractions
- Converting decimal numbers to fractions
- Simplifying fractions to their lowest terms
Real-World Example
Suppose you want to calculate the total cost of ingredients in a recipe, expressed as fractions to ensure precision when scaling:
Python
>>> from fractions import Fraction
>>> ingredient_costs = [Fraction("1/3"), Fraction("2/5"), Fraction("1/2")]
>>> total_cost = sum(ingredient_costs)
>>> total_cost
Fraction(31, 30)
This calculation ensures that the total cost is computed accurately without rounding errors, thanks to the fractions module.