fix(core): the shares keep the old scale, and the floor's correction is bounded

The review's kernel findings, with the bridge properties that hold them.

FirstAbsorbs computed the first part as whole minus the rest, which is
algebraically the old split_first's parts[0] + (whole minus the sum of
parts) but not the same scale: 4860 by 6/0.7/0.5 gave 4050.00 where the
old code gave 4050, and 902 by 1/0.000001/0.000001 gave 902 where the old
code gave 902.00. That scale reaches Part.amount, so a printed share
moved. The kernel computes the old expression now, with checked ops;
LastAbsorbs was already the old plug_last and the no-places conventions
split. The bridge compares the strings.

share_floor_with's correction loop could walk without end on a rounded
product far from the exact floor: 0.1113 x 5909471247797156928749568911.8
/ 0.11134381908633486049673 hangs. Both directions now stop at
MAX_CORRECTION_STEPS and refuse, so an input past the cap is None, never
a hang; no figure produced within the cap changes. The bridge pins the
input.

Ranking needed a property of its own: on i64 every remainder is zero, so
the harnesses never rank. A random-weight bridge checks the split against
the independent exact reference over non-terminating totals, excluding
exact ties because the kernel ranks the rounded quotients' remainders;
finding_ties_follow_the_rounded_quotient pins those ties (20.00 by 4/1/1
over 6 is 13.33/3.34/3.33, 20 whole is 13/4/3), today's behaviour and the
pre-U3 sites' alike, for K-U10 to decide.

share_floor and split_by_weights had no engine caller (only the bridge),
so they are gone; split_by_weights_with and share_floor_with are the
public API, and the docs say both checked_mul and checked_div can round
at Decimal's edge.

Co-Authored-By: DeepSeek V4.1 Flash <noreply@opencode.ai>
This commit is contained in:
swaitsandDeepSeek V4.1 Flash committed 2026-11-09 01:31:45 -07:00
1 parent d4440b6a4e
commit 8edc2e85dd
6 files changed
+313 -82

No files matched your search

+3 -1
View File
@@ -34,7 +34,9 @@
//! it) is shared among the members credited in proportion to their //! it) is shared among the members credited in proportion to their
//! credits, to the base currency's minor unit (cents, whole yen), //! credits, to the base currency's minor unit (cents, whole yen),
//! leftover units by largest remainder //! leftover units by largest remainder
//! (kernel::apportion, ties to the earlier member): each takes at //! (kernel::apportion, a tie in the rounded remainders to the
//! earlier member; an exact tie follows the quotient's 28th digit,
//! K-U10): each takes at
//! most its own credit, and the split depends on the order the //! most its own credit, and the split depends on the order the
//! members are given only for a tied leftover cent (never on line //! members are given only for a tied leftover cent (never on line
//! order). Joint property is joint (BS-partner-1's //! order). Joint property is joint (BS-partner-1's
+63 -55
View File
@@ -7,24 +7,31 @@
//! //!
//! Division is not exact: [`share_of`] is the amount type's checked //! Division is not exact: [`share_of`] is the amount type's checked
//! division, so a `Decimal` quotient is rounded at 28 significant digits //! division, so a `Decimal` quotient is rounded at 28 significant digits
//! (and a machine integer's is truncated), never an exact rational. Every //! (and a machine integer's is truncated), never an exact rational.
//! invariant below is stated of that computation, and of the parts after //! Multiplication is not exact either at `Decimal`'s 96-bit mantissa:
//! the named leftover policy, which do sum to the whole exactly. See //! `checked_mul` rounds the product there. Every invariant below is
//! `docs/proofs/k-u3.md` for the one place the quotient's rounding can //! stated of that computation, and of the parts after the named leftover
//! change a rounded part (Decimal's edge, K-U10). //! policy, which do sum to the whole exactly. See `docs/proofs/k-u3.md`
//! for the edges where a product's or a quotient's rounding can change a
//! rounded part (Decimal's edge, K-U10).
use super::round::Rounding; use super::{Amount, apportion, plug_last};
use super::{Amount, apportion, plug_last, round_step};
/// What a split does with the units its rounded parts leave over. /// What a split does with the units its rounded parts leave over.
#[derive(Clone, Copy, Debug, PartialEq, Eq)] #[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Leftover { pub enum Leftover {
/// Each part is rounded down; the units left over go one each to the /// Each part is rounded down; the units left over go one each to the
/// largest remainders (ties to the earlier part). [`apportion`]. /// largest remainders. The remainders are the rounded quotients'
/// differences, not exact rationals, so ranking follows the quotient:
/// an exact tie can go where the quotient's 28th digit sends it, and
/// only a tie in the rounded remainders goes to the earlier part. K-U10
/// decides the exact ranking. [`apportion`].
LargestRemainder, LargestRemainder,
/// The last part becomes the whole less the others. [`plug_last`]. /// The last part becomes the whole less the others. [`plug_last`].
LastAbsorbs, LastAbsorbs,
/// The first part becomes the whole less the others. /// The first part becomes its rounded share plus the shortfall (the
/// whole less every rounded part), so its scale is the shortfall
/// addition's; the value is the whole less the others.
FirstAbsorbs, FirstAbsorbs,
} }
@@ -49,8 +56,9 @@ pub enum Leftover {
/// 2. None when total is zero, or when the product or quotient is not /// 2. None when total is zero, or when the product or quotient is not
/// representable. Never a panic, never a wrapped amount. /// representable. Never a panic, never a wrapped amount.
/// 3. When total is not zero and whole x weight is representable, the /// 3. When total is not zero and whole x weight is representable, the
/// division is the only step that can round; a `Some` is always the /// product and the division are the two steps that can round: either
/// amount type's quotient, never a guessed one. /// `Decimal` operation rounds at its own edge. A `Some` is always the
/// amount type's quotient of its product, never a guessed one.
/// SCENARIOS: /// SCENARIOS:
/// 1. IF 100 by 40 of 100: SHOULD be 40. /// 1. IF 100 by 40 of 100: SHOULD be 40.
/// 2. IF 1 by 1 of 3: SHOULD be 0.333... (28 significant digits), not an /// 2. IF 1 by 1 of 3: SHOULD be 0.333... (28 significant digits), not an
@@ -70,9 +78,10 @@ pub fn share_of<T: Amount>(whole: T, weight: T, total: T) -> Option<T> {
/// GOAL: the exact floor of a proportional share to a step, without /// GOAL: the exact floor of a proportional share to a step, without
/// trusting a rounded quotient, and the exact remainder that ranks /// trusting a rounded quotient, and the exact remainder that ranks
/// the parts of a largest-remainder split. /// the parts of a largest-remainder split.
/// SOURCE: BS-1099-1 (a payment split into its buckets to the cent), /// SOURCE: BS-partner-1, BS-1099-1 (a payment split into its buckets to
/// the cent; partners share by the agreement),
/// BS-entry-3 (amounts are exact; round only where a rule says /// BS-entry-3 (amounts are exact; round only where a rule says
/// to), BS-partner-1 (largest remainder). /// to).
/// INVARIANTS: /// INVARIANTS:
/// 1. whole and weight are non-negative (the callers pass magnitudes). /// 1. whole and weight are non-negative (the callers pass magnitudes).
/// Provided `part x total` and `(part + step) x total` are exact /// Provided `part x total` and `(part + step) x total` are exact
@@ -90,6 +99,10 @@ pub fn share_of<T: Amount>(whole: T, weight: T, total: T) -> Option<T> {
/// the product's rounding). /// the product's rounding).
/// 3. None when step or total is not positive, a product is not /// 3. None when step or total is not positive, a product is not
/// representable, or the correction leaves the range; never a panic. /// representable, or the correction leaves the range; never a panic.
/// The correction takes at most [`MAX_CORRECTION_STEPS`] steps in
/// each direction and returns None past the cap: a malformed input
/// (one whose product's rounding put the estimate many steps away)
/// refuses rather than runs without end.
/// SCENARIOS: /// SCENARIOS:
/// 1. IF 60 x 33.33 / 100 to the cent: SHOULD be (19.99, 80), since /// 1. IF 60 x 33.33 / 100 to the cent: SHOULD be (19.99, 80), since
/// 60 x 33.33 = 1999.80 and 19.99 x 100 = 1999. /// 60 x 33.33 = 1999.80 and 19.99 x 100 = 1999.
@@ -114,34 +127,39 @@ pub fn share_floor_with<T: Amount>(
// steps back until part x total <= num, then forward while one more // steps back until part x total <= num, then forward while one more
// step still fits. The comparisons multiply, never divide; they are // step still fits. The comparisons multiply, never divide; they are
// exact while the product fits Decimal's mantissa (the edge is // exact while the product fits Decimal's mantissa (the edge is
// K-U10, pinned in the bridge). // K-U10, pinned in the bridge). Both directions are bounded so a
// quotient rounded far across the floor refuses instead of hanging.
let mut steps = 0;
while part.checked_mul(total)? > num { while part.checked_mul(total)? > num {
if steps == MAX_CORRECTION_STEPS {
return None;
}
steps += 1;
part = part.checked_sub(step)?; part = part.checked_sub(step)?;
} }
steps = 0;
loop { loop {
if steps == MAX_CORRECTION_STEPS {
return None;
}
let next = part.checked_add(step)?; let next = part.checked_add(step)?;
if next.checked_mul(total)? > num { if next.checked_mul(total)? > num {
break; break;
} }
part = next; part = next;
steps += 1;
} }
let remainder = num.checked_sub(part.checked_mul(total)?)?; let remainder = num.checked_sub(part.checked_mul(total)?)?;
Some((part, remainder)) Some((part, remainder))
} }
/// [`share_floor_with`] with [`round_step`] as the first estimate: the /// The most correction steps [`share_floor_with`] takes in each direction.
/// exact floor of `whole × weight ÷ total` to `step`, in `mode`'s /// The first estimate is at most one step off in practice (half-away's
/// direction (only `TowardZero` is the floor; the correction makes the /// rounding of a quotient whose product is exact); a few thousand leaves
/// result exact either way). /// room for any quotient rounding that still describes the same figure.
pub fn share_floor<T: Amount>( /// A share further away is a malformed input, and the function refuses it
whole: T, /// rather than loop without end.
weight: T, const MAX_CORRECTION_STEPS: usize = 4096;
total: T,
step: T,
mode: Rounding,
) -> Option<(T, T)> {
share_floor_with(whole, weight, total, step, |x| round_step(x, step, mode))
}
/// Split `whole` by `weights` over `total`, each part the exact share /// Split `whole` by `weights` over `total`, each part the exact share
/// rounded by `round`, the leftover by `policy`, written into `parts` (and /// rounded by `round`, the leftover by `policy`, written into `parts` (and
@@ -177,6 +195,11 @@ pub fn share_floor<T: Amount>(
/// a part more than one step from the exact rational (K-U10, pinned /// a part more than one step from the exact rational (K-U10, pinned
/// in the bridge). Under the first/last-absorbs policies only the /// in the bridge). Under the first/last-absorbs policies only the
/// absorbing part may be further, by the rounding of all the others. /// absorbing part may be further, by the rounding of all the others.
/// The largest-remainder ranking compares the rounded quotients'
/// remainders, not exact rationals: an exact tie can go where
/// `Decimal`'s 28th digit sends it, and only a tie in the rounded
/// remainders goes to the earlier part (K-U10 decides the exact
/// rule; the bridge pins today's answer).
/// 3. With total not zero, no part exceeds the whole when every weight /// 3. With total not zero, no part exceeds the whole when every weight
/// is in [0, total] and the whole is not negative; no part is /// is in [0, total] and the whole is not negative; no part is
/// negative when the weights and the whole are not. /// negative when the weights and the whole are not.
@@ -190,7 +213,8 @@ pub fn share_floor<T: Amount>(
/// promised. /// promised.
/// SCENARIOS: /// SCENARIOS:
/// 1. IF 100 by 1/1/1 to the cent by largest remainder: SHOULD be /// 1. IF 100 by 1/1/1 to the cent by largest remainder: SHOULD be
/// 33.34, 33.33, 33.33 (the tied cent to the first). /// 33.34, 33.33, 33.33 (the rounded remainders tie, so the cent goes
/// to the earlier part).
/// 2. IF 0.01 by 1/1 to the cent by largest remainder: SHOULD be /// 2. IF 0.01 by 1/1 to the cent by largest remainder: SHOULD be
/// 0.01, 0.00. /// 0.01, 0.00.
/// 3. IF 10 by weights 2/3/5 by first-absorbs: SHOULD be the rounded /// 3. IF 10 by weights 2/3/5 by first-absorbs: SHOULD be the rounded
@@ -240,14 +264,19 @@ pub fn split_by_weights_into<T: Amount>(
} }
Leftover::LastAbsorbs => plug_last(whole, parts), Leftover::LastAbsorbs => plug_last(whole, parts),
Leftover::FirstAbsorbs => { Leftover::FirstAbsorbs => {
let Some((first, rest)) = parts.split_first_mut() else { // The old `split_first`: the first part takes its rounded share
// plus the shortfall (the whole less every rounded part). The
// value is the whole less the others, but its scale is the sum
// and the addition's, as the call site has always produced.
let mut sum = T::ZERO;
for &p in parts.iter() {
sum = sum.checked_add(p)?;
}
let Some(first) = parts.first_mut() else {
return Some(()); return Some(());
}; };
let mut others = T::ZERO; let left = whole.checked_sub(sum)?;
for &p in rest.iter() { *first = first.checked_add(left)?;
others = others.checked_add(p)?;
}
*first = whole.checked_sub(others)?;
Some(()) Some(())
} }
} }
@@ -277,24 +306,3 @@ pub fn split_by_weights_with<T: Amount>(
)?; )?;
Some(parts) Some(parts)
} }
/// [`split_by_weights_with`] with [`round_step`] as the rounding: the
/// generic spelling for a caller whose parts carry a whole number of
/// `step`s.
pub fn split_by_weights<T: Amount>(
whole: T,
weights: &[T],
total: T,
step: T,
mode: Rounding,
policy: Leftover,
) -> Option<Vec<T>> {
split_by_weights_with(
whole,
weights,
total,
step,
|x| round_step(x, step, mode),
policy,
)
}
+17 -12
View File
@@ -4,10 +4,11 @@
//! The divisor is fixed in every harness: CBMC's bit-blasted division by //! The divisor is fixed in every harness: CBMC's bit-blasted division by
//! a symbolic `i64` did not finish in 30 minutes in K-U2 //! a symbolic `i64` did not finish in 30 minutes in K-U2
//! (`docs/proofs/k-u2.md`), and every split here divides by a total or a //! (`docs/proofs/k-u2.md`), and every split here divides by a total or a
//! step. The fixed weights and totals cover a tied split (2/3/5), a zero //! step. The fixed weights and totals cover three different weights
//! weight, a total of one, and a step that is not a power of ten; the //! (2/3/5), a zero weight and a total of one; the steps used are 1 and
//! bridge carries the same laws to every `Decimal` weight and step, and //! 10. The bridge carries the same laws to every `Decimal` weight and
//! bookspec's Lean proves them for any number of parts. //! step, and bookspec's Lean proves them of the exact-share model for any
//! number of parts.
//! //!
//! ```text //! ```text
//! GOAL: the parts of a weighted split sum to the whole exactly, each //! GOAL: the parts of a weighted split sum to the whole exactly, each
@@ -21,8 +22,10 @@
//! INVARIANTS: //! INVARIANTS:
//! 1. The parts sum to the whole, for every policy. //! 1. The parts sum to the whole, for every policy.
//! 2. Under largest remainder each part is within one unit (the step) //! 2. Under largest remainder each part is within one unit (the step)
//! of its exact share: `-total < part x total - whole x weight < //! of its exact share: `-total < part x total - whole x weight <=
//! total` at step one. //! total` at step one. The upper bound is inclusive on `i64` (its
//! division truncates); the bridge checks the strict `Decimal`
//! bound.
//! 3. No part is negative or above the whole for non-negative weights //! 3. No part is negative or above the whole for non-negative weights
//! that do not exceed the total. //! that do not exceed the total.
//! 4. A zero total gives zeros; all-zero weights hand the whole out by //! 4. A zero total gives zeros; all-zero weights hand the whole out by
@@ -30,17 +33,19 @@
//! units as there are parts. //! units as there are parts.
//! 5. Overflow is `None`, never a panic. //! 5. Overflow is `None`, never a panic.
//! SCENARIOS: //! SCENARIOS:
//! 1. IF 101 by 1/1/1 to the unit: SHOULD be 34/34/33 (the tied unit //! 1. IF 101 by 1/1/1 to the unit: SHOULD be 34/34/33 (the rounded
//! to the first), never 33/34/34. //! remainders tie, so the units go to the earlier parts), never
//! 33/34/34.
//! 2. IF a quotient rounds up across the step: `share_floor_with` //! 2. IF a quotient rounds up across the step: `share_floor_with`
//! SHOULD still give the exact floor, by multiplication. //! SHOULD still give the exact floor, by multiplication.
//! 3. IF the product `whole x weight` is past `i64`: SHOULD be None. //! 3. IF the product `whole x weight` is past `i64`: SHOULD be None.
//! ``` //! ```
//! //!
//! Bounds: amounts up to 1,000, weights up to 100, totals and steps fixed //! Bounds: amounts up to 1,000, weights up to 100, totals fixed (10 and
//! (`10`, `1`, `7`). The laws are about the shape of the split, not the //! 0), steps 1 and 10. The laws are about the shape of the split, not the
//! magnitude; Lean proves them at any size and the bridge checks the //! magnitude; Lean proves them of the exact-share model at any size, and
//! `Decimal` engine. //! the bridge checks the `Decimal` engine, whose ranking uses the rounded
//! quotient.
use crate::kernel::{self, Leftover, Rounding, share_floor_with, share_of, split_by_weights_into}; use crate::kernel::{self, Leftover, Rounding, share_floor_with, share_of, split_by_weights_into};
+3 -2
View File
@@ -451,8 +451,9 @@ fn original_target(
/// Split `whole` (at most the sum of `sizes`) over `sizes` in proportion, /// Split `whole` (at most the sum of `sizes`) over `sizes` in proportion,
/// to the cent, leftover cents by largest remainder (k1's /// to the cent, leftover cents by largest remainder (k1's
/// share_property), ties to the earlier in `order` (each part's rank). /// `share_property`), a tie in the rounded remainders to the earlier in
/// None past exact arithmetic. /// `order` (each part's rank); an exact tie follows the quotient's 28th
/// digit, and K-U10 decides the exact ranking. None past exact arithmetic.
fn share_by(whole: Decimal, sizes: &[Decimal], order: &[usize]) -> Option<Vec<Decimal>> { fn share_by(whole: Decimal, sizes: &[Decimal], order: &[usize]) -> Option<Vec<Decimal>> {
let ranked: Vec<Decimal> = order.iter().map(|&i| sizes[i]).collect(); let ranked: Vec<Decimal> = order.iter().map(|&i| sizes[i]).collect();
let shared = crate::k1::share_property(whole, &ranked, 2).ok()?; let shared = crate::k1::share_property(whole, &ranked, 2).ok()?;
+4 -2
View File
@@ -365,7 +365,8 @@ fn too_large() -> LedgerError {
/// 2. A member's exact running total is Σ whole × weight / Σ weights /// 2. A member's exact running total is Σ whole × weight / Σ weights
/// over every split so far; their running total (Σ of their parts) /// over every split so far; their running total (Σ of their parts)
/// is the largest-remainder rounding to the cent of the exact running /// is the largest-remainder rounding to the cent of the exact running
/// totals (ties to the earlier member), so it is within a cent of /// totals (a tie in the rounded remainders to the earlier member; an
/// exact tie follows the quotient's 28th digit, K-U10), so it is within a cent of
/// exact, strictly. A negative running whole is rounded as its /// exact, strictly. A negative running whole is rounded as its
/// magnitude and negated; a running whole of zero is rounded by the /// magnitude and negated; a running whole of zero is rounded by the
/// sign of the whole just split. So a run of losses mirrors the run /// sign of the whole just split. So a run of losses mirrors the run
@@ -655,7 +656,8 @@ fn entry_wholes(
/// their part: the pair leaves every later entry's cents as they /// their part: the pair leaves every later entry's cents as they
/// would be without it. Its own parts (it reads as the contrary /// would be without it. Its own parts (it reads as the contrary
/// kind, a distribution for a contribution) are split on its own, /// kind, a distribution for a contribution) are split on its own,
/// largest remainder, ties to the earlier member. /// largest remainder, a tie in the rounded remainders to the earlier
/// member (an exact tie follows the quotient's 28th digit, K-U10).
/// ``` /// ```
fn entry_parts( fn entry_parts(
ledger: &Ledger, ledger: &Ledger,
@@ -11,8 +11,8 @@
//! `Decimal::MAX` and scale 28, each `None` or exact, never a panic. //! `Decimal::MAX` and scale 28, each `None` or exact, never a panic.
use ledger_core::kernel::{ use ledger_core::kernel::{
Leftover, Rounding, round_places, round_step, share_floor_with, share_of, split_by_weights, Leftover, Rounding, round_places, round_step, share_floor_with, share_of,
split_by_weights_with, split_by_weights_into, split_by_weights_with,
}; };
use proptest::prelude::*; use proptest::prelude::*;
use rust_decimal::Decimal; use rust_decimal::Decimal;
@@ -157,12 +157,12 @@ proptest! {
fn i64_and_decimal_agree(k in 0i64..=100_000) { fn i64_and_decimal_agree(k in 0i64..=100_000) {
let whole = k * 10; let whole = k * 10;
let weights = [2i64, 3, 5]; let weights = [2i64, 3, 5];
let narrow = split_by_weights( let narrow = split_by_weights_with(
whole, whole,
&weights, &weights,
10, 10,
1, 1,
Rounding::TowardZero, |x| round_step(x, 1, Rounding::TowardZero),
Leftover::LargestRemainder, Leftover::LargestRemainder,
) )
.unwrap(); .unwrap();
@@ -238,21 +238,21 @@ proptest! {
#[test] #[test]
fn leftovers_at_each_policy(whole in 0i64..=1_000_000) { fn leftovers_at_each_policy(whole in 0i64..=1_000_000) {
let weights = [2i64, 3, 5]; let weights = [2i64, 3, 5];
let first = split_by_weights( let first = split_by_weights_with(
whole, whole,
&weights, &weights,
10, 10,
1, 1,
Rounding::TowardZero, |x| round_step(x, 1, Rounding::TowardZero),
Leftover::FirstAbsorbs, Leftover::FirstAbsorbs,
) )
.unwrap(); .unwrap();
let last = split_by_weights( let last = split_by_weights_with(
whole, whole,
&weights, &weights,
10, 10,
1, 1,
Rounding::TowardZero, |x| round_step(x, 1, Rounding::TowardZero),
Leftover::LastAbsorbs, Leftover::LastAbsorbs,
) )
.unwrap(); .unwrap();
@@ -291,6 +291,60 @@ proptest! {
prop_assert_eq!(cents(&got), want); prop_assert_eq!(cents(&got), want);
} }
/// The exact reference ranks the exact remainders; the kernel ranks
/// the rounded quotients' remainders. With a small non-terminating
/// total the two orders agree except at an exact tie, which this
/// property excludes and `finding_ties_follow_the_rounded_quotient`
/// pins.
#[test]
fn largest_remainder_ranks_like_the_exact_reference(
whole_start in 0i64..=2_000,
weights in prop::collection::vec(1i64..=9, 2..=4),
) {
// Distinct weights, and a total with a factor of 3 or 7 (a
// non-terminating division), by construction: no case is
// rejected, and no exact tie is left to the property.
let mut weights = weights;
weights.sort_unstable();
for (i, w) in weights.iter_mut().enumerate() {
*w += i as i64;
}
let plain: i64 = weights.iter().sum();
if plain % 3 != 0 && plain % 7 != 0 {
*weights.last_mut().unwrap() += 3 - plain % 3;
}
let total: i64 = weights.iter().sum();
let whole = (whole_start..whole_start + total)
.find(|&w| {
let mut rems: Vec<i128> = weights
.iter()
.map(|&x| (i128::from(w) * i128::from(x)) % i128::from(total))
.collect();
rems.sort_unstable();
rems.dedup();
rems.len() == weights.len()
})
.expect("whole ≡ 1 mod total leaves distinct remainders");
let decimal_weights: Vec<Decimal> = weights.iter().copied().map(Decimal::from).collect();
let got = split_by_weights_with(
Decimal::from(whole),
&decimal_weights,
Decimal::from(total),
Decimal::ONE,
|x| round_step(x, Decimal::ONE, Rounding::TowardZero),
Leftover::LargestRemainder,
)
.unwrap();
let want = reference(
i128::from(whole),
&weights.iter().map(|&w| i128::from(w)).collect::<Vec<_>>(),
i128::from(total),
1,
)
.unwrap();
prop_assert_eq!(got.iter().map(|&p| integer(p)).collect::<Vec<_>>(), want);
}
/// `share_floor_with` is the exact floor of the rational, even when /// `share_floor_with` is the exact floor of the rational, even when
/// the division does not terminate (total 3, 7, 11): the quotient's /// the division does not terminate (total 3, 7, 11): the quotient's
/// 28-digit rounding is corrected by multiplication. /// 28-digit rounding is corrected by multiplication.
@@ -414,18 +468,177 @@ fn decimal_edges_are_none_or_exact() {
// A zero total is zeros, whatever the weights. // A zero total is zeros, whatever the weights.
assert_eq!( assert_eq!(
split_by_weights( split_by_weights_with(
dec(5), dec(5),
&[dec(1), dec(2)], &[dec(1), dec(2)],
Decimal::ZERO, Decimal::ZERO,
Decimal::ONE, Decimal::ONE,
Rounding::TowardZero, |x| round_step(x, Decimal::ONE, Rounding::TowardZero),
Leftover::LargestRemainder Leftover::LargestRemainder
), ),
Some(vec![Decimal::ZERO, Decimal::ZERO]) Some(vec![Decimal::ZERO, Decimal::ZERO])
); );
} }
/// The absorbing parts keep the scale the pre-U3 code produced. Decimal's
/// equality ignores scale, so these compare the strings: the old
/// `shares::split_first` added the shortfall to the first rounded share
/// (4860 by 6/0.7/0.5 gave `4050`, not `4050.00`), and 902 by
/// 1/0.000001/0.000001 gave `902.00` there; the kernel now computes the
/// same expression, not the algebraically equal `whole − Σ rest`.
#[test]
fn the_absorbing_parts_keep_the_old_scale() {
let text = |parts: &[Decimal]| parts.iter().map(Decimal::to_string).collect::<Vec<_>>();
let weights = [parse("6"), parse("0.7"), parse("0.5")];
let got = split_by_weights_with(
parse("4860"),
&weights,
parse("7.2"),
parse("0.01"),
|x| round_places(x, 2, Rounding::TowardZero),
Leftover::FirstAbsorbs,
)
.unwrap();
assert_eq!(text(&got), ["4050", "472.50", "337.50"]);
let weights = [Decimal::ONE, parse("0.000001"), parse("0.000001")];
let got = split_by_weights_with(
parse("902"),
&weights,
parse("1.000002"),
parse("0.01"),
|x| round_places(x, 2, Rounding::TowardZero),
Leftover::FirstAbsorbs,
)
.unwrap();
assert_eq!(text(&got), ["902.00", "0.00", "0.00"]);
// LastAbsorbs is the old `plug_last` (and the no-places conventions
// split): the last part is the whole less the others, same scale.
let got = split_by_weights_with(
parse("4860"),
&weights[..1],
Decimal::ONE,
Decimal::ONE,
Some,
Leftover::LastAbsorbs,
)
.unwrap();
assert_eq!(text(&got), ["4860"]);
let got = split_by_weights_with(
parse("7"),
&[parse("0.5"), parse("0.5")],
Decimal::ONE,
Decimal::ONE,
Some,
Leftover::LastAbsorbs,
)
.unwrap();
assert_eq!(text(&got), ["3.5", "3.5"]);
}
/// The buffer API and the allocating one agree, including scale: the
/// bridge calls `split_by_weights_into` itself (fixed arrays), as the
/// traceability gate requires.
#[test]
fn split_into_matches_the_allocating_split() {
let weights = [parse("6"), parse("0.7"), parse("0.5")];
let mut parts = [Decimal::ZERO; 3];
let mut remainders = [Decimal::ZERO; 3];
split_by_weights_into(
parse("4860"),
&weights,
parse("7.2"),
parse("0.01"),
|x| round_places(x, 2, Rounding::TowardZero),
Leftover::FirstAbsorbs,
&mut parts,
&mut remainders,
)
.unwrap();
let with = split_by_weights_with(
parse("4860"),
&weights,
parse("7.2"),
parse("0.01"),
|x| round_places(x, 2, Rounding::TowardZero),
Leftover::FirstAbsorbs,
)
.unwrap();
assert_eq!(
parts.iter().map(Decimal::to_string).collect::<Vec<_>>(),
with.iter().map(Decimal::to_string).collect::<Vec<_>>()
);
}
/// The EM's finding, pinned rather than fixed: a split ranks the rounded
/// quotients' remainders, so an exact tie goes where the 28th digit sends
/// it, not to the earlier part. 20.00 split 4/1/1 over 6 gives
/// 13.33/3.34/3.33 (exact ranking would give 13.34/3.33/3.33), and 20 at
/// whole units gives 13/4/3 (exact would give 14/3/3). The pre-U3 sites
/// did the same. The owner decides the exact ranking in K-U10.
#[test]
fn finding_ties_follow_the_rounded_quotient() {
let weights = [Decimal::from(4), Decimal::ONE, Decimal::ONE];
let got = decimal_split(
parse("20.00"),
&weights,
Decimal::from(6),
2,
Leftover::LargestRemainder,
)
.unwrap();
assert_eq!(
got.iter().map(Decimal::to_string).collect::<Vec<_>>(),
["13.33", "3.34", "3.33"]
);
let got = decimal_split(
Decimal::from(20),
&weights,
Decimal::from(6),
0,
Leftover::LargestRemainder,
)
.unwrap();
assert_eq!(
got.iter().map(Decimal::to_string).collect::<Vec<_>>(),
["13", "4", "3"]
);
}
/// The review's hang: `0.1113 × 5909471247797156928749568911.8 ÷
/// 0.11134381908633486049673` to the cent put the rounded product far
/// past the exact floor, and the correction walked without end. It now
/// refuses past the cap, quickly; the other two buckets keep exact floors.
#[test]
fn share_floor_refuses_past_the_correction_cap() {
let b = [
parse("0.1113"),
parse("0.00004381908373486049673"),
parse("0.0000000000026"),
];
let v = parse("-5909471247797156928749568911.8");
let total = b
.iter()
.copied()
.try_fold(Decimal::ZERO, |s, x| s.checked_add(x))
.unwrap();
let started = std::time::Instant::now();
let got = share_floor_with(b[0].abs(), v.abs(), total, parse("0.01"), |x| {
round_places(x, 2, Rounding::TowardZero)
});
assert_eq!(got, None);
assert!(started.elapsed() < std::time::Duration::from_secs(5));
for bucket in &b[1..] {
assert!(
share_floor_with(bucket.abs(), v.abs(), total, parse("0.01"), |x| {
round_places(x, 2, Rounding::TowardZero)
},)
.is_some()
);
}
}
/// The K-U10 finding: at `Decimal`'s mantissa edge, `checked_div`'s /// The K-U10 finding: at `Decimal`'s mantissa edge, `checked_div`'s
/// rounding can move a share across a step, and `checked_mul`'s rounding /// rounding can move a share across a step, and `checked_mul`'s rounding
/// hides it from the exact-floor correction. The exact share is /// hides it from the exact-floor correction. The exact share is