Fraction stores a rational number as a reduced integer numerator and a positive integer denominator.
Python Fraction: exact ratios require an exact input representation
Operation contract
The invoice allocation uses three tenths as an exact ratio and applies it to a bounded integer amount. Multiplication produces a rational result, so a nonintegral minor-unit amount remains visible rather than being rounded silently. Fraction constructed from the string 0.1 represents one tenth; Fraction constructed from the float 0.1 preserves that float’s binary value instead. limit_denominator selects an approximation under its cap. It does not recover the sender’s intent.
Failure and ownership boundary
A payment ledger still needs an allocation remainder and rounding policy. Reject Boolean values, unbounded denominators and nonpositive divisors before invoking rational arithmetic. Exactness can increase retained digits when repeated operations combine unrelated denominators. Python Decimal money: parse decimal text and choose rounding explicitly and NumPy floating-point checks: finite values and declared tolerances address different numeric domains.
Working program
from fractions import Fraction
def allocation(amount, numerator, denominator):
if any(type(value) is not int for value in (amount, numerator, denominator)):
raise ValueError("exact integer fields")
if not 0 <= amount <= 100000 or not 0 <= numerator <= denominator <= 1000 or denominator == 0:
raise ValueError("allocation bounds")
return amount * Fraction(numerator, denominator)
print("allocation:", allocation(125, 3, 10))
print("text exact:", Fraction("0.1") == Fraction(1, 10))
print("float exact:", Fraction(0.1) == Fraction(1, 10))
print("approximation:", Fraction(0.1).limit_denominator(10))
try:
allocation(125, 1, 0)
except ValueError:
print("zero denominator rejected")Output
allocation: 75/2
text exact: True
float exact: False
approximation: 1/10
zero denominator rejectedCosts and limits
Reduction performs integer arithmetic and a greatest-common-divisor operation. Cost depends on digit length, not only the count of fields. The accepted bounds cap this fixture’s operands; a general rational accumulator needs its own digit and batch limits.
Common Mistakes
- Constructing a Fraction from float preserves the float’s value.
- Exact arithmetic does not decide how a fractional minor unit should be posted.
Connected lessons
Python Decimal money: parse decimal text and choose rounding explicitly, Python type conversion: parsing success is not field validity, NumPy floating-point checks: finite values and declared tolerances.
