fix(core): an exact division refuses a rounded quotient

`Amount::checked_div_exact` promises the exact quotient or nothing: "never
a rounded share". On Decimal it checked the quotient by multiplying back,
but with rust_decimal's own product, which rounds. A rounded quotient
times the divisor rounds back to the dividend (10 / 3 is 3.333...3 at 28
places, and 3.333...3 x 3 is held as 10), so a third, a seventh and a
ninth all passed as exact.

No figure in the books was wrong: the one caller divides a basis-point
product by 10,000, which is always exact. The contract was broken for
the next caller. The check now multiplies back exactly (K-U10's
`exact_mul`), so a rounded quotient is refused.

The bridge gets the property (a quotient returned, times the divisor, is
the dividend as a rational) and the named cases. The FX rounding
property also takes steps of 5 and 25 units, whose half steps sit one
place below the step: the wide product keeps that digit real.

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
swaitsandClaude committed 2026-11-09 21:05:43 -07:00
1 parent 786e503858
commit e46fa4fc6e
3 files changed
+71 -10

No files matched your search

+5 -1
View File
@@ -151,7 +151,11 @@ impl Amount for Decimal {
}
fn checked_div_exact(self, rhs: Self) -> Option<Self> {
let q = self.checked_div(rhs)?;
(q.checked_mul(rhs) == Some(self)).then_some(q)
// The exact product, not `rust_decimal`'s: a rounded quotient
// times the divisor rounds back to the dividend there (10 / 3 is
// 3.333...3, and 3.333...3 x 3 is held as 10), which would pass a
// rounded share as an exact one.
(super::decimal_exact::exact_mul(q, rhs) == Some(self)).then_some(q)
}
fn checked_div(self, rhs: Self) -> Option<Self> {
Decimal::checked_div(self, rhs)
@@ -376,7 +376,8 @@ proptest! {
#![proptest_config(ProptestConfig::with_cases(30000))]
/// `checked_mul_round_to_step` is the exact product rounded once, in
/// every mode, at the steps the books use (one, a cent, a mill),
/// every mode, at the steps the books use (one, a cent, a mill) and
/// at steps of 5 and 25 of them,
/// whether or not the exact product fits 96 bits, ties and signs
/// included; `None` only for a figure past about 10^23 (the real digits, the
/// sticky digit and the step's places must fit 96 bits).
@@ -385,15 +386,17 @@ proptest! {
foreign in arb_ten_place(26),
rate in arb_ten_place(14),
places in 0u32..=3,
unit in prop_oneof![Just(1i128), Just(5i128), Just(25i128)],
mode in arb_mode(),
negative in any::<bool>(),
) {
let foreign = if negative { -foreign } else { foreign };
let step = Decimal::from_i128_with_scale(1, places);
// A step that is not a power of ten too (a nickel, 0.025): its
// half steps sit one place below it, where the kept digit is real.
let step = Decimal::from_i128_with_scale(unit, places);
let got = Amount::checked_mul_round_to_step(foreign, rate, step, mode);
let scale = BigRational::from_integer(BigInt::from(10u8).pow(places));
let count = round_rational(&(rat(foreign) * rat(rate) * scale.clone()), mode);
let want = BigRational::from_integer(count) / scale;
let count = round_rational(&(rat(foreign) * rat(rate) / rat(step)), mode);
let want = BigRational::from_integer(count) * rat(step);
match got {
Some(g) => prop_assert_eq!(rat(g), want, "{} x {} to {} places, {:?}", foreign, rate, places, mode),
None => prop_assert!(
@@ -447,3 +450,48 @@ fn the_k_u1_edge_books_the_cent_the_exact_product_gives() {
Some("1000000000.10".parse().unwrap())
);
}
// ------------------------------------------------------ exact division
proptest! {
#![proptest_config(ProptestConfig::with_cases(30000))]
/// `checked_div_exact` is the exact quotient or `None`: never a
/// quotient `rust_decimal` rounded (10 / 3), whose product with the
/// divisor rounds back to the dividend.
#[test]
fn div_exact_is_exact_or_none(a in arb_line_amount(), m in 1i128..100_000, s in 0u32..=4) {
let b = Decimal::from_i128_with_scale(m, s);
if let Some(q) = Amount::checked_div_exact(a, b) {
prop_assert_eq!(rat(q) * rat(b), rat(a), "{} / {} gave {}", a, b, q);
}
}
}
/// A third, a seventh, a ninth: no exact quotient, so `None`, where the
/// check through `rust_decimal`'s rounding product let each through. A
/// quarter and a basis-point division are exact and are kept.
#[test]
fn a_rounded_quotient_is_not_an_exact_one() {
let d = |s: &str| s.parse::<Decimal>().unwrap();
for (a, b) in [
("10", "3"),
("20", "3"),
("10", "7"),
("80", "9"),
("10", "6"),
("1000000.00", "3"),
] {
assert_eq!(
Amount::checked_div_exact(d(a), d(b)),
None,
"{a} / {b} has no exact quotient"
);
}
assert_eq!(Amount::checked_div_exact(d("10"), d("4")), Some(d("2.5")));
assert_eq!(
Amount::checked_div_exact(d("123456.78") * d("250"), d("10000")),
Some(d("3086.4195"))
);
assert_eq!(Amount::checked_div_exact(d("1"), d("0")), None);
}
+13 -4
View File
@@ -25,7 +25,16 @@ of mantissa at the operands' scale, or a scale past 28, they return a
| `1e-28 x 1e-28` | 1e-56 | `Some(0)` | K-U1 |
`checked_div` (rounds at 28 significant digits) is the engine's rounding
division and is unchanged, with `checked_div_exact`.
division and is unchanged.
A sixth, found in review of this unit: `checked_div_exact` ("never a
rounded share") checked its quotient by multiplying back with
`rust_decimal`'s product. A rounded quotient times the divisor rounds back
to the dividend (`10 / 3` is 3.333…3 at 28 places, and 3.333…3 x 3 is held
as 10), so `10 / 3`, `10 / 7`, `80 / 9` and `1000000.00 / 3` each came back
`Some`. Its one caller divides a basis-point product by 10,000, which is
always exact, so no figure was wrong. It now multiplies back with
`exact_mul` and refuses them.
## The method
@@ -120,7 +129,8 @@ independent `num_rational::BigRational` reference, over every mantissa to
| `posted_range_sums_are_unchanged` | every line-range figure (≤ 10^15, ≤ 10 places, any raw scale holding it): add and subtract equal the old to the character and are never `None` |
| `posted_range_running_totals_are_unchanged` | a running total of up to 100 line-range figures is unchanged at every step |
| `posted_range_fx_products_are_unchanged_or_refused` | foreign (≤ 10^25 mantissa, ≤ 10 places) x rate (≤ 10 places): identical to the old whenever the mantissa product fits 96 bits; otherwise the old figure only if it was exact, else `None` |
| `the_fx_product_is_rounded_once_from_the_exact_one` | `checked_mul_round_to_step` equals the exact rational product rounded once, in each of four modes, at steps 1, 0.1, 0.01 and 0.001, signs and ties included; `None` only past about 10^23 |
| `the_fx_product_is_rounded_once_from_the_exact_one` | `checked_mul_round_to_step` equals the exact rational product rounded once, in each of four modes, at steps of 1, 5 and 25 units of 1, 0.1, 0.01 and 0.001 (a step that is not a power of ten has its half steps one place below it), signs and ties included; `None` only past about 10^23 |
| `div_exact_is_exact_or_none` | a quotient `checked_div_exact` returns, times the divisor, is the dividend as a rational (`a_rounded_quotient_is_not_an_exact_one` names the thirds, sevenths and ninths) |
Also: the three flipped canaries (below), `an_exact_product_that_only_looks_wide_is_kept`,
`zero_is_exact`, `the_k_u1_edge_books_the_cent_the_exact_products_cent`
@@ -153,8 +163,7 @@ each a rounded figure that is now refused or correctly rounded):
## What did not change
- `checked_div`, `checked_div_exact` (still a rounded product inside
`checked_div_exact`: left alone, division is not this unit's).
- `checked_div`, the engine's rounding division.
- Every golden and every existing test outside the list above.
- Direct calls of the inherent `Decimal::checked_add/_sub/_mul` outside the
kernel (about 70 sites in `reports`, `tax_capital`, `assets`, `arap`,