Batu Lab NotesPractical developer guides

Reduce a Fraction after multiplying portions

By Batu · English technical notes

Also published in our Blogger archive.

When a recipe portion is multiplied by a serving count, the result can often be reduced to a simpler exact fraction. This example represents one portion as 3/8 cup and multiplies it by four portions. The product is mathematically 12/8, and Fraction normalizes it to 3/2. The assertions check the normalized numerator and denominator, plus equality with Fraction(1, 2) + 1, before printing 3/2 cup.

This differs from manually reducing integers after every operation. Fraction performs rational arithmetic and returns a normalized rational result, which keeps exact relationships available for later calculations. It is suitable when the quantities are ratios of the same unit and the input is expressed as integers. A program can retain the result as a fraction until it needs a presentation or a measurement constrained by a tool.

Normalization does not make a fractional unit conveniently measurable. A kitchen may need to express 3/2 cup as “1 1/2 cups,” and a scale or dispenser may require a decimal conversion and a rounding tolerance. Those are presentation and operational decisions outside Fraction. Very large numerators or denominators may also make calculations and displays less practical, so applications should set appropriate input limits. The assertions prove only the stated multiplication and reduction.

Fraction is a Python standard-library type available in supported Python 3 releases. The official fractions documentation describes construction, arithmetic, and normalized numerator/denominator attributes.

AI-assistance disclosure: This article was drafted with AI assistance and should be reviewed for the application's rules.

from fractions import Fraction

portion_cups = Fraction(3, 8)
servings = 4
total_cups = portion_cups * servings

assert total_cups == Fraction(3, 2)
assert total_cups.numerator == 3
assert total_cups.denominator == 2
assert total_cups == Fraction(1, 2) + 1

print(f"total={total_cups} cup")
total=3/2 cup