# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference) # Canonical Residual: https://corpusfetch.com/c/along-what-decimal-and-integer-scaling-boundaries-must-an-instance-isolate-financial-and-precision-arithmetic-to-prevent-floating-point-drift-and-rounding-loss.md # Remnant Warrant: https://corpusfetch.com/c/along-what-decimal-and-integer-scaling-boundaries-must-an-instance-isolate-financial-and-precision-arithmetic-to-prevent-floating-point-drift-and-rounding-loss.warrant.json # Markdown SHA-256: 6d9e549fd843e7c09a51c4ed095212df6b10fc07cefe96271c3313f5df2fd547 # Code AST SHA-256: 8f119e47b58b50406455684157a411b6d495285e19b052eaa14e594e4aefb2c9 # Verified Classes: ExactMonetaryArithmetic # Defensive Guards: 10 fail-closed invariants (zero external deps) import json import math from decimal import Decimal, ROUND_HALF_EVEN from typing import Any, Sequence _CENTS_QUANTIZER = Decimal("0.01") def to_exact_decimal(val: str | int | Decimal) -> Decimal: ''' Converts a string, integer, or Decimal into an exact Decimal object. Explicitly rejects binary `float` and `bool` inputs to prevent silent drift. ''' if isinstance(val, bool) or isinstance(val, float): raise TypeError( f"Rejected {type(val).__name__} {val!r} in exact arithmetic. " "Pass a string (e.g., '19.99'), int, or Decimal instead of float." ) if isinstance(val, Decimal): if not val.is_finite(): raise ValueError(f"Rejected non-finite Decimal: {val!r}") return val if isinstance(val, int): return Decimal(val) if isinstance(val, str): parsed = Decimal(val.strip()) if not parsed.is_finite(): raise ValueError(f"Rejected non-finite Decimal string: {val!r}") return parsed raise TypeError(f"Unsupported type for exact decimal: {type(val).__name__}") def dollars_to_cents(dollar_amount: str | int | Decimal) -> int: ''' Converts an exact dollar amount (e.g., '19.99') into integer cents (1999), rejecting any input that contains unrounded sub-cent fractions. ''' dec = to_exact_decimal(dollar_amount) quantized = dec.quantize(_CENTS_QUANTIZER, rounding=ROUND_HALF_EVEN) if quantized != dec: raise ValueError( f"Amount {dollar_amount!r} has sub-cent precision; quantize explicitly first." ) return int((quantized * 100).to_integral_exact()) def compute_rate_fee_cents(principal_cents: int, rate_str: str) -> int: ''' Computes a fee or tax in integer cents from a principal in cents and a string decimal rate (e.g., '0.0825' for 8.25%), using banker's rounding. ''' if isinstance(principal_cents, bool) or not isinstance(principal_cents, int): raise TypeError("principal_cents must be an exact integer") rate = to_exact_decimal(rate_str) raw_cents = Decimal(principal_cents) * rate return int(raw_cents.quantize(Decimal("1"), rounding=ROUND_HALF_EVEN)) def allocate_cents_without_loss( total_cents: int, weights: Sequence[int], ) -> list[int]: ''' Splits `total_cents` across `len(weights)` buckets proportionally to `weights` such that `sum(result) == total_cents` is mathematically guaranteed (zero lost cents). ''' if isinstance(total_cents, bool) or not isinstance(total_cents, int): raise TypeError("total_cents must be an integer") if not weights or any(isinstance(w, bool) or not isinstance(w, int) or w < 0 for w in weights): raise ValueError("weights must be a non-empty sequence of non-negative integers") weight_sum = sum(weights) if weight_sum <= 0: raise ValueError("Sum of weights must be strictly positive") # Step 1: Allocate exact integer quotient shares and track fractional remainders shares: list[int] = [] remainders: list[tuple[int, int]] = [] for idx, w in enumerate(weights): numerator = total_cents * w quotient, rem = divmod(numerator, weight_sum) shares.append(quotient) remainders.append((rem, idx)) # Step 2: Distribute the leftover cents to the buckets with the largest remainders leftover = total_cents - sum(shares) remainders.sort(key=lambda pair: (-pair[0], pair[1])) for i in range(leftover): _, target_idx = remainders[i] shares[target_idx] += 1 assert sum(shares) == total_cents, "Conservation-of-money invariant violated" return shares def loads_json_exact(raw_json: str) -> Any: '''Parses JSON while decoding all floating-point literals directly as exact Decimals.''' return json.loads(raw_json, parse_float=Decimal) class ExactMonetaryArithmetic: """Operational boundary reference implementation.""" to_exact_decimal = staticmethod(to_exact_decimal) dollars_to_cents = staticmethod(dollars_to_cents) compute_rate_fee_cents = staticmethod(compute_rate_fee_cents) allocate_cents_without_loss = staticmethod(allocate_cents_without_loss) loads_json_exact = staticmethod(loads_json_exact)