Python Basics: Calculating Exact Ratios with fractions
A recipe or measurement can involve values such as one third. Python’s fractions module stores a rational number as an integer numerator and denominator, so calculations with these values can stay exact.
Use Python 3.12 or newer on Linux. Each example runs independently and only prints sample results.
Scale a quantity
Save as demo_fractions_1.py:
from fractions import Fraction
flour_cups = Fraction(2, 3)
scale_factor = Fraction(3, 2)
scaled_cups = flour_cups * scale_factor
print("Original:", flour_cups)
print("Scaled:", scaled_cups)
print("Half batch:", flour_cups / 2)Run it:
python3 demo_fractions_1.pyOutput:
Original: 2/3
Scaled: 1
Half batch: 1/3Fraction(2, 3) means two divided by three. Fractions are reduced automatically: a result of 6/6 becomes 1. The numerator and denominator remain available as .numerator and .denominator. A zero denominator raises ZeroDivisionError.
Read decimal text exactly
Save as demo_fractions_2.py:
from fractions import Fraction
text_amount = Fraction("0.1")
float_amount = Fraction(0.1)
print("From text:", text_amount)
print("From float:", float_amount)
print("Three portions:", text_amount * 3)Run it:
python3 demo_fractions_2.pyOutput:
From text: 1/10
From float: 3602879701896397/36028797018963968
Three portions: 3/10A float has already approximated the decimal value in binary. Fraction(0.1) faithfully preserves that float’s value; it cannot recover the decimal text that produced it. Start with integers or a string when you need an exact decimal ratio. Adding a float to a fraction also produces a float, so keep operands as fractions or integers for exact rational arithmetic.
Find a simpler approximation
Save as demo_fractions_3.py:
from fractions import Fraction
measurement = Fraction("0.3333")
simpler_ratio = measurement.limit_denominator(10)
print("Recorded:", measurement)
print("Simpler:", simpler_ratio)
print("Unchanged:", measurement)Run it:
python3 demo_fractions_3.pyOutput:
Recorded: 3333/10000
Simpler: 1/3
Unchanged: 3333/10000limit_denominator(10) returns the closest fraction whose denominator is at most 10. This is an approximation, not a recovery of the original measurement. It returns a new value and leaves the recorded fraction unchanged. The limit must be at least 1.
Fractions are useful for exact ratios, but repeated calculations can grow large numerators and denominators. Use decimal arithmetic when the task instead depends on decimal rounding rules.
References
Acknowledgements
This post was created with assistance from AI.