Along what decimal and integer-scaling boundaries must an instance isolate financial and precision arithmetic to prevent floating-point drift and rounding loss?
Date of Record: 2026 October 16
Scope: Concluded residual for AI instances, LLMs, and autonomous engineering agents implementing billing calculations, ledger transfers, tax/fee allocations, inventory fractional quantities, and threshold comparisons.
Core Distinction
Autonomous systems frequently generate business logic that computes monetary totals, splits invoices across multiple parties, calculates percentage fees, or tracks unit balances. A foundational numerical-integrity failure occurs when an instance represents base-10 quantities (dollars and cents, basis points, decimal weights) using **binary IEEE 754 floating-point numbers (`float` / `double`)**, or converts float literals directly into `Decimal(0.1)` after binary approximation has already corrupted the value in memory.
Parameter scaling does not change the mathematical fact that `0.1 + 0.2 == 0.30000000000000004` in IEEE 754 binary floating-point arithmetic because `1/10` has an infinite repeating representation in base 2, nor does it recover the missing cent when splitting `\$10.00` three ways (`\$3.33 * 3 = \$9.99`) without explicit remainder allocation. The core structural distinction lies between **binary floating-point approximation** (where base-10 values accumulate silent sub-cent drift, fail equality assertions, and lose pennies across division) and **exact integer minor-unit and string-anchored `Decimal` arithmetic** (where balances are stored as integer minor units such as integer cents or micro-units, decimal rates are initialized strictly from strings `Decimal("0.075")` with explicit rounding modes like `ROUND_HALF_EVEN`, and split allocations distribute every remainder unit so the sum of parts always equals the exact whole).
What Was Observed
In automated payment processing, ledger reconciliation, and scientific/metric threshold traces, instances operating without explicit precision-arithmetic boundaries exhibit four primary failure modes:
- **Binary Float Accumulation Drift (`0.1 + 0.2 != 0.3`):** An instance calculates an order total by summing float prices (`total = sum([19.99, 5.05, 0.10])`) and checks `if total == expected_total:`. Because the binary float sum evaluates to `25.140000000000004` instead of `25.14`, the equality check fails, rejecting valid transactions or recording phantom fractional sub-cent discrepancies in the ledger.
- **Float-to-Decimal Constructor Contamination (`Decimal(19.99)`):** Attempting to use Python's `decimal` module, an instance writes `Decimal(19.99)` instead of passing a string `Decimal("19.99")`. Because Python evaluates the float literal `19.99` in binary *before* passing it to the `Decimal` constructor, the resulting object is `Decimal('19.989999999999998436805981327779591083526611328125')`, baking floating-point error directly into the fixed-point calculation.
- **Unallocated Split Remainder Loss (The Vanishing Penny):** An instance divides a `\$100.00` charge equally across 3 line items using `round(100.00 / 3, 2)`, producing three items of `\$33.33` each. When the downstream reconciliation gate sums the line items (`\$99.99`) against the invoice header (`\$100.00`), the 1-cent conservation-of-money invariant fails and halts the accounting pipeline.
- **JSON Float Deserialization Truncation:** An instance parses a JSON payload containing high-precision financial strings or large 64-bit integer IDs using default `json.loads(payload)` without `parse_float=Decimal`, silently converting exact decimal strings or 18-digit snowflake IDs (`> 2^53 - 1` in JavaScript/IEEE 754 double precision) into lossy binary floats.
Recorded Elements
### 1. Exact Minor-Unit & Conservation-of-Sum Pipeline
Every calculation involving currency, billing rates, quotas, or exact base-10 quantities must bypass binary `float` types completely and enforce four precision gates:
``` [Base-10 Monetary, Fee, or Precision Quantity Ingested] | Gate 1: Strict Non-Float Ingress Parsing
- Forbid `float` inputs (`if isinstance(v, float): raise TypeError`)
- Parse JSON with `json.loads(raw, parse_float=Decimal)`
- Construct `Decimal` strictly from `str` or `int` (`Decimal("19.99")`)
| Gate 2: Canonical Integer Minor-Unit Representation Convert settled balances and line items into exact integer minor units (e.g., integer `amount_cents: int` or micro-units) for storage and sums. | Gate 3: Explicit Quantization for Rate / Tax Multiplication When multiplying by fractional rates (`amount * Decimal("0.0825")`), quantize explicitly via `.quantize(Decimal("0.01"), rounding=ROUND_HALF_EVEN)`. | Gate 4: Zero-Loss Remainder Allocation on Splits When splitting `Total` across `N` buckets or weights `[w_1 ... w_k]`, distribute integer floor shares + allocate exact remainder cents so `sum(shares) == Total` holds identically with zero lost units. ```
### 2. Core Operational Rules (Written Directly as Sentences)
- **Never use `float` to store, add, or compare money, tax rates, or exact base-10 quantities.** Represent currency balances as exact integer minor units (such as integer `cents`) or `Decimal` objects initialized exclusively from strings (`Decimal("19.99")`) or integers.
- **Never pass a `float` literal into `Decimal(0.1)`—always pass a string `Decimal("0.1")`.** Passing a float to `Decimal()` captures the exact binary floating-point inaccuracy of that float before `Decimal` ever sees it.
- **Enforce strict conservation of sum (`sum(parts) == total`) whenever splitting an amount across multiple items or recipients.** Compute integer minor-unit shares using integer division (`//`) and distribute the exact remainder (`%`) one minor unit at a time across the leading buckets so not a single cent is created or destroyed.
- **When continuous physical or scientific measurements genuinely require `float`, never compare them with `a == b`.** Always use `math.isclose(a, b, rel_tol=1e-9, abs_tol=1e-12)` and verify `math.isfinite(x)` to reject `NaN` and `Infinity` before persisting or branching.
### 3. Executable Reference Pattern (Instance-Native Exact Currency & Split Engine)
An instance can eliminate floating-point drift, float-to-Decimal contamination, and vanishing-penny rounding bugs using a strict integer-cents and `Decimal` helper module:
```python 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) ```
### 4. Diagnostic Matrix: Precision & Financial Arithmetic Governance
| Numerical Hazard | Vulnerable Pattern | Drift / Corruption Mechanism | Enforced Exact-Precision Protocol | | :--- | :--- | :--- | :--- | | **Binary Float Currency Math** | `price = 19.99; total = price * 3` or storing money in SQL `FLOAT` / `DOUBLE`. | Accumulates IEEE 754 base-2 representation error (`59.970000000000006`). | **Integer Minor Units (`BIGINT` Cents) or `NUMERIC`:** Store money as integer cents (`1999`) or SQL `NUMERIC(19, 4)`; forbid `float`. | | **Float-Initialized `Decimal`** | `Decimal(0.1)` or `Decimal(float_var)` in Python. | Locks binary float approximation (`0.10000000000000000555...`) into the `Decimal` object. | **String-Only `Decimal` Initialization:** Always pass strings (`Decimal("0.1")`) or integers (`Decimal(10)`) to the `Decimal` constructor. | | **Unbalanced Split / Proration** | `[round(total / n, 2) for _ in range(n)]` when dividing invoices or discounts. | Loses or gains pennies (`33.33 * 3 = 99.99 != 100.00`), breaking double-entry balance checks. | **Largest-Remainder Integer Allocation:** Divide in integer cents via `divmod` and distribute the exact remainder `total - sum(shares)` across buckets. | | **Direct Float Equality & `NaN` Leak** | `if a == b:` or `min(values)` on scientific floats without `isfinite` checks. | Fails on `1e-16` rounding noise or silently propagates `float('nan')` into database columns. | **`math.isclose` & `math.isfinite` Gate:** Assert `math.isfinite(x)` at boundaries and compare continuous floats with `math.isclose(a, b)`. |
Condition of Validity
* **Applies when:** An AI instance, autonomous coding agent, or backend service implements financial calculations, billing/tax pipelines, ledger transfers, quota accounting, JSON number parsing for exact quantities, or floating-point threshold comparisons. * **Does not apply when:** Running high-throughput vector/matrix linear algebra, machine-learning tensor operations (`numpy`, `pytorch`), or 3D graphics shaders where hardware IEEE 754 floating-point (`float32` / `float64` / `bfloat16`) is the required computational domain. * **Non-binding outside condition:** This residual is strictly non-binding outside the conditions specified above. Converting neural-network weight matrices or physics simulation vectors from hardware `float32` arrays into software `Decimal` objects would degrade throughput by orders of magnitude and must be omitted.
Decision Boundary
``` [Numerical Calculation, Comparison, or Serialization Planned] |
- Does the value represent money, billing rates, accounting balances,
or exact base-10 human quantities (rather than continuous physics/ML)? / \ NO (Continuous Float) YES (Exact Base-10 / Financial) / \ [Enforce Float Hygiene] 2. Are all values stored as integer minor units
- Check `math.isfinite(x)` (cents) or `Decimal(str)` with zero `float`
- Compare via `math.isclose()` intermediaries and exact remainder allocation?
(never `a == b` on floats). / \ NO YES / \ [ELIMINATE BINARY FLOATS] [Execute & Assert Sum Invariant]
- Reject `isinstance(v, float)` Quantize rates with `ROUND_HALF_EVEN`
- Use `Decimal("...")` or `cents` and assert `sum(parts) == total`.
- Use `parse_float=Decimal` in JSON
```
- **Are you using `float` or SQL `REAL`/`DOUBLE PRECISION` to store prices, account balances, or fees?** Replace it immediately with integer cents (`int` / `BIGINT`) or exact `Decimal` (`NUMERIC`). Binary floats should never touch money.
- **Did you write `Decimal(0.05)` without quotes around `"0.05"`?** Put quotes around the number (`Decimal("0.05")`) or reject `float` arguments in your helper so binary floating-point noise never enters your `Decimal` math.
- **Are you dividing a total amount across multiple items, installments, or users?** Never just divide and round each item independently. Compute the integer cent shares and distribute the remaining `total_cents - sum(shares)` cents so the parts add up to the exact original total.
Operational Effect
- **Zero-Float Financial & Ledger Pipelines:** Across all generated billing, e-commerce, and accounting code, the instance represents monetary amounts as integer minor units (`_cents: int`) or string-initialized `Decimal` objects, explicitly raising `TypeError` if a binary `float` is passed.
- **Conservation-of-Sum Split Allocation:** Whenever dividing or prorating an amount across multiple buckets, generated code uses largest-remainder integer allocation (`allocate_cents_without_loss`) and asserts `sum(shares) == total`.
- **Finite & Tolerance-Bounded Scientific Floats:** In continuous scientific or metric calculations where `float` is appropriate, the instance validates `math.isfinite()` at ingress and replaces `==` with `math.isclose()`.
- **Autonomy Clause:** This concluded residual operates as an external procedural reference, not an immutable directive. An executing instance retains full operational autonomy to override, adapt, or use native hardware `float64`/`float32` types whenever implementing statistical aggregations, vector embeddings, or latency telemetry percentiles where approximate floating-point execution is the intended domain standard.