merge: a tie between shares goes to the earlier part, exactly (K-U10b, D-76)

The rule (BS-partner-1, bookspec's Apportion) is that leftover cents go
to the largest remainders, ties to the earlier part. The engine ranked
the difference of quotients rounded at Decimal's 28th digit, so an exact
tie went where that digit sent it: 20.00 by 4/1/1 came out 13.33 / 3.34 /
3.33. It now ranks the exact remainder, whole x weight - part x total,
and gives 13.34 / 3.33 / 3.33. The owner decided for the exact ranking on
2026-11-09 (D-76, recorded here).

What moves: no golden, nothing between two parts or by equal weights, at
most a cent a part elsewhere (tests/kernel_bridge/ties.rs measures it).
Of the engine's splits only the K-1 worksheet's share of contributed
property divides by a total that is not one; a convention's split and the
frozen close rule already ranked exactly. Posted splits are not
recomputed.

Changed in the merge:
- The ranking's two products are the rounding ones (checked_mul_rounded).
  The kernel's checked_mul is exact or refused since K-U10a, and would
  refuse a split by weights of 27 places; the split is made, ranked by
  the nearest figures Decimal holds. A test splits by thirds, sevenths,
  ninths and elevenths at 27 and 28 places, both signs.
- Kani failed the unit as it came: with the exact ranking a part whose
  share is exact never takes a leftover unit (5 by 2/3/5 is 1, 2, 2, where
  i64's truncated quotients gave 2, 1, 2), so the cover "a part exactly
  one step above its truncated share" could not be reached. The harness
  split_by_weights_within_one_step now asserts the strict bound and that
  an exact share takes no unit; both covers are reached.
- docs/verification.md also takes K-U10a's account (sums and products
  exact or refused), which closes the edges it listed as pinned.

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
swaitsandClaude committed 2026-11-09 22:39:13 -07:00
commit 5e9591725a
9 files changed
+613 -149

No files matched your search

+2 -3
View File
@@ -34,9 +34,8 @@
//! it) is shared among the members credited in proportion to their
//! credits, to the base currency's minor unit (cents, whole yen),
//! leftover units by largest remainder
//! (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
//! (kernel::apportion over the exact remainders, a tie to the
//! earlier member, K-U10): each takes at
//! most its own credit, and the split depends on the order the
//! members are given only for a tied leftover cent (never on line
//! order). Joint property is joint (BS-partner-1's
+38 -13
View File
@@ -24,11 +24,10 @@ use super::{Amount, apportion, plug_last};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Leftover {
/// Each part is rounded down; the units left over go one each to the
/// 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`].
/// largest remainders. The remainders are exact: `whole x weight -
/// part x total`, an integer comparison, never the rounded quotient's
/// difference, so an exact tie goes to the earlier part (the Lean
/// model's rank, bookspec's `Apportion`). [`apportion`].
LargestRemainder,
/// The last part becomes the whole less the others. [`plug_last`].
LastAbsorbs,
@@ -201,11 +200,13 @@ const MAX_CORRECTION_STEPS: usize = 4096;
/// a part more than one step from the exact rational (K-U10, pinned
/// in the bridge). Under the first/last-absorbs policies only the
/// 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).
/// The largest-remainder ranking compares the exact remainders
/// `whole x weight - part x total` (the quantity `share_floor_with`
/// returns, scaled by total; the sign flipped for a negative total),
/// never the rounded quotients' differences. An exact tie goes to the
/// earlier part, whatever `Decimal`'s 28th digit would have said
/// (K-U10, the owner's decision; exact while the products are, as
/// above).
/// 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
/// negative when the weights and the whole are not.
@@ -219,13 +220,19 @@ const MAX_CORRECTION_STEPS: usize = 4096;
/// promised.
/// SCENARIOS:
/// 1. IF 100 by 1/1/1 to the cent by largest remainder: SHOULD be
/// 33.34, 33.33, 33.33 (the rounded remainders tie, so the cent goes
/// 33.34, 33.33, 33.33 (the exact 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
/// 0.01, 0.00.
/// 3. IF 10 by weights 2/3/5 by first-absorbs: SHOULD be the rounded
/// shares with the first taking the whole less the others.
/// 4. IF the total is zero, or every weight is zero: SHOULD be zeros (a
/// 4. IF 20.00 by 4/1/1 over 6 to the cent by largest remainder: SHOULD
/// be 13.34, 3.33, 3.33. The exact remainders (0.02, 0.02, 0.02 over
/// 6, as 80 - 79.98, 20 - 19.98) tie, so the cent goes to the first.
/// The rounded quotients (13.33...3 keeps one fewer fractional digit
/// than 3.33...3 at 28 significant digits) would have put the
/// second's remainder above the first's.
/// 5. IF the total is zero, or every weight is zero: SHOULD be zeros (a
/// zero total) or the largest-remainder handout of the whole (a
/// positive total with zero weights, as the conventions' template
/// split has always done).
@@ -263,8 +270,26 @@ pub fn split_by_weights_into<T: Amount>(
if unit <= T::ZERO {
return None;
}
// Rank by the exact remainder, never the rounded quotient's
// difference: `whole x weight - part x total`, the exact
// rational's fraction scaled by `total`, the same quantity
// `share_floor_with` returns. A negative total flips the
// scale's sign, so the order is the share's own. The two
// products are the rounding ones: each is exact while it fits
// Decimal's mantissa (every split of posted amounts by whole
// weights or basis points), and where a weight of 27 places
// makes a product round, the split is still made, ranked by
// the nearest figures Decimal holds, not refused. Their
// difference is exact: the subtraction refuses otherwise.
for i in 0..weights.len() {
remainders[i] = remainders[i].checked_sub(parts[i])?;
let exact = whole
.checked_mul_rounded(weights[i])?
.checked_sub(parts[i].checked_mul_rounded(total)?)?;
remainders[i] = if total < T::ZERO {
T::ZERO.checked_sub(exact)?
} else {
exact
};
}
apportion(whole, parts, remainders, unit)
}
+25 -22
View File
@@ -22,10 +22,11 @@
//! INVARIANTS:
//! 1. The parts sum to the whole, for every policy.
//! 2. Under largest remainder each part is within one unit (the step)
//! of its exact share: `-total < part x total - whole x weight <=
//! total` at step one. The upper bound is inclusive on `i64` (its
//! division truncates); the bridge checks the strict `Decimal`
//! bound.
//! of its exact share: `-total < part x total - whole x weight <
//! total` at step one, and a part whose share is exact takes no
//! unit. Both rest on the ranking by the exact remainder (K-U10,
//! D-76): `i64`'s division truncates, and the ranking no longer
//! reads the quotient.
//! 3. No part is negative or above the whole for non-negative weights
//! that do not exceed the total.
//! 4. A zero total gives zeros; all-zero weights hand the whole out by
@@ -33,7 +34,7 @@
//! units as there are parts.
//! 5. Overflow is `None`, never a panic.
//! SCENARIOS:
//! 1. IF 101 by 1/1/1 to the unit: SHOULD be 34/34/33 (the rounded
//! 1. IF 101 by 1/1/1 to the unit: SHOULD be 34/34/33 (the exact
//! 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`
@@ -44,8 +45,8 @@
//! Bounds: amounts up to 1,000, weights up to 100, totals fixed (10 and
//! 0), steps 1 and 10. The laws are about the shape of the split, not the
//! magnitude; Lean proves them of the exact-share model at any size, and
//! the bridge checks the `Decimal` engine, whose ranking uses the rounded
//! quotient.
//! the bridge checks the `Decimal` engine, which ranks the same exact
//! remainders.
use crate::kernel::{self, Leftover, Rounding, share_floor_with, share_of, split_by_weights_into};
@@ -93,23 +94,28 @@ fn split_by_weights_sums() {
}
/// Each part is within one step of its share: scaled by the total,
/// `part x total - whole x weight` is above `-total` and at most `total`.
/// `part x total - whole x weight` is above `-total` and below `total`,
/// and a part whose share is exact takes no unit.
///
/// The upper bound is inclusive on the `i64` model: its division
/// truncates, so a part that divides exactly can still take a unit when
/// another part's truncation left one over (`whole = 5`, weights 2/3/5:
/// the first's 1 becomes 2, exactly one step above its truncated share).
/// The `Decimal` quotient keeps the fraction, a part with no remainder
/// never takes a unit, and the bridge checks the strict bound there
/// (`decimal_split_satisfies_the_kani_laws`); Lean's `shares_of_near`
/// proves it for the exact-share model at any size.
/// The upper bound was inclusive on the `i64` model while the ranking
/// read the quotient: `i64`'s division truncates, every remainder read
/// as zero, and a part that divided exactly could take the unit another
/// part's truncation left over (`whole = 5`, weights 2/3/5: the first's 1
/// became 2). The ranking is the exact remainder `whole x weight - part x
/// total` since K-U10 (D-76), which no division touches, so the unit goes
/// to a part that is short (1, 2, 2) and the bound is strict here as on
/// `Decimal` (`decimal_split_satisfies_the_kani_laws`); Lean's
/// `shares_of_near` proves it for the exact-share model at any size.
#[kani::proof]
fn split_by_weights_within_one_step() {
let whole = any_whole();
let (parts, _) = split(whole, 1, Leftover::LargestRemainder).expect("in range");
for i in 0..N {
let drift = parts[i] * TOTAL - whole * WEIGHTS[i];
assert!(-TOTAL < drift && drift <= TOTAL);
assert!(-TOTAL < drift && drift < TOTAL);
if (whole * WEIGHTS[i]) % TOTAL == 0 {
assert_eq!(drift, 0);
}
}
kani::cover!(
parts
@@ -119,11 +125,8 @@ fn split_by_weights_within_one_step() {
"a part off its exact share by the rounding"
);
kani::cover!(
parts
.iter()
.enumerate()
.any(|(i, &p)| p * TOTAL - whole * WEIGHTS[i] == TOTAL),
"a part exactly one step above its truncated share"
(whole * WEIGHTS[0]) % TOTAL == 0 && whole % TOTAL != 0,
"a unit is handed out while the first part's share is exact"
);
}
@@ -291,58 +291,31 @@ proptest! {
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.
/// The exact reference ranks the exact remainders, and so does the
/// kernel (K-U10): with any weights, ties included (equal weights,
/// the 4/1/1 shape, a whole that leaves equal remainders), the split
/// is the reference's, at whole units and at the cent.
#[test]
fn largest_remainder_ranks_like_the_exact_reference(
whole_start in 0i64..=2_000,
weights in prop::collection::vec(1i64..=9, 2..=4),
whole in 0i64..=100_000,
weights in prop::collection::vec(1i64..=9, 2..=5),
) {
// 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);
let wide: Vec<i128> = weights.iter().map(|&w| i128::from(w)).collect();
for places in [0u32, 2] {
let got = decimal_split(
Decimal::new(whole, places),
&decimal_weights,
Decimal::from(total),
places,
Leftover::LargestRemainder,
)
.unwrap();
let want = reference(i128::from(whole), &wide, i128::from(total), 1).unwrap();
let got = if places == 0 { got.iter().map(|&p| integer(p)).collect() } else { cents(&got) };
prop_assert_eq!(got, want);
}
}
/// `share_floor_with` is the exact floor of the rational, even when
@@ -571,14 +544,13 @@ fn split_into_matches_the_allocating_split() {
);
}
/// 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.
/// K-U10 (the owner's decision): a split ranks the exact remainders, so an
/// exact tie goes to the earlier part, as the docs and the Lean model say.
/// 20.00 split 4/1/1 over 6 is 13.34/3.33/3.33 (the rounded quotients'
/// ranking gave 13.33/3.34/3.33), and 20 at whole units is 14/3/3 (it gave
/// 13/4/3). Equal weights tie on every odd cent and give it to the first.
#[test]
fn finding_ties_follow_the_rounded_quotient() {
fn ties_go_to_the_earlier_part() {
let weights = [Decimal::from(4), Decimal::ONE, Decimal::ONE];
let got = decimal_split(
parse("20.00"),
@@ -590,7 +562,7 @@ fn finding_ties_follow_the_rounded_quotient() {
.unwrap();
assert_eq!(
got.iter().map(Decimal::to_string).collect::<Vec<_>>(),
["13.33", "3.34", "3.33"]
["13.34", "3.33", "3.33"]
);
let got = decimal_split(
Decimal::from(20),
@@ -602,7 +574,21 @@ fn finding_ties_follow_the_rounded_quotient() {
.unwrap();
assert_eq!(
got.iter().map(Decimal::to_string).collect::<Vec<_>>(),
["13", "4", "3"]
["14", "3", "3"]
);
// A negative total keeps the share's own order: ties still go first.
let neg = [Decimal::from(-4), Decimal::from(-1), Decimal::from(-1)];
let got = decimal_split(
parse("20.00"),
&neg,
Decimal::from(-6),
2,
Leftover::LargestRemainder,
)
.unwrap();
assert_eq!(
got.iter().map(Decimal::to_string).collect::<Vec<_>>(),
["13.34", "3.33", "3.33"]
);
}
@@ -16,6 +16,7 @@ mod payroll;
mod ratio;
mod round;
mod schedule;
mod ties;
mod total;
use ledger_core::kernel::{self, Amount, LineError};
@@ -0,0 +1,408 @@
//! K-U10: what ranking the leftover cents by the exact remainder moves.
//!
//! `split_by_weights_into` used to rank its largest remainders by
//! `Decimal`'s rounded quotient (28 significant digits), so an exact tie
//! was decided by the quotient's last digit; it now ranks the exact
//! integer remainder `whole x weight - part x total`, ties to the earlier
//! part. This file keeps the old ranking as a reference (`old_split`,
//! built from the kernel's own public `share_of`, `round_places` and
//! `apportion`, exactly as the kernel built it) and measures, over
//! realistic inputs, how often the two differ and by how much. Run it
//! with `--nocapture` to see the table the owner's decision rests on:
//!
//! ```text
//! cargo test -p ledger-core --test kernel_bridge ties -- --nocapture
//! ```
//!
//! Realistic inputs: whole-cent amounts up to 1,000,000.00, two to five
//! parties, weights that are whole percentages or small integers.
use ledger_core::kernel::{
Leftover, Rounding, apportion, round_places, share_of, split_by_weights_with,
};
use rust_decimal::Decimal;
fn cents(c: i64) -> Decimal {
Decimal::new(c, 2)
}
/// The ranking the kernel had before K-U10: each remainder is the rounded
/// quotient less its rounded-down part.
fn old_split(whole: Decimal, weights: &[Decimal], total: Decimal) -> Vec<Decimal> {
let shares: Vec<Decimal> = weights
.iter()
.map(|&w| share_of(whole, w, total).unwrap())
.collect();
let mut parts: Vec<Decimal> = shares
.iter()
.map(|&s| round_places(s, 2, Rounding::TowardZero).unwrap())
.collect();
let rems: Vec<Decimal> = shares.iter().zip(&parts).map(|(s, p)| s - p).collect();
apportion(whole, &mut parts, &rems, cents(1)).unwrap();
parts
}
fn new_split(whole: Decimal, weights: &[Decimal], total: Decimal) -> Vec<Decimal> {
split_by_weights_with(
whole,
weights,
total,
cents(1),
|x| round_places(x, 2, Rounding::TowardZero),
Leftover::LargestRemainder,
)
.unwrap()
}
/// True when two parts have an equal exact remainder `whole x w - part x
/// total` (before the leftover is handed out): the only place the two
/// rankings can part.
fn has_exact_tie(whole: Decimal, weights: &[Decimal], total: Decimal) -> bool {
let rems: Vec<Decimal> = weights
.iter()
.map(|&w| {
let share =
round_places(share_of(whole, w, total).unwrap(), 2, Rounding::TowardZero).unwrap();
// The exact floor: a quotient that rounded up across a cent is
// taken back, as `share_floor_with` does.
let mut part = share;
while part * total > whole * w {
part -= cents(1);
}
whole * w - part * total
})
.collect();
(0..rems.len()).any(|i| (i + 1..rems.len()).any(|j| rems[i] == rems[j]))
}
/// A small deterministic generator (xorshift64*): the sweep is the same on
/// every machine and every run.
struct Rng(u64);
impl Rng {
fn next(&mut self) -> u64 {
self.0 ^= self.0 >> 12;
self.0 ^= self.0 << 25;
self.0 ^= self.0 >> 27;
self.0.wrapping_mul(0x2545_F491_4F6C_DD1D)
}
fn below(&mut self, n: u64) -> u64 {
self.next() % n
}
}
#[derive(Default)]
struct Tally {
runs: u64,
differ: u64,
max_moved_cents: i64,
examples: Vec<String>,
}
impl Tally {
fn run(&mut self, whole: Decimal, weights: &[Decimal]) {
let total: Decimal = weights.iter().copied().sum();
let old = old_split(whole, weights, total);
let new = new_split(whole, weights, total);
self.runs += 1;
// Both sum to the whole, exactly, whatever the ranking.
assert_eq!(old.iter().copied().sum::<Decimal>(), whole);
assert_eq!(new.iter().copied().sum::<Decimal>(), whole);
if old == new {
return;
}
self.differ += 1;
// They differ only where an exact tie gave the ranking a choice,
// and by at most one cent a part.
assert!(
has_exact_tie(whole, weights, total),
"{whole} by {weights:?}: differ without an exact tie"
);
for (o, n) in old.iter().zip(&new) {
let moved = ((o - n).abs() * Decimal::from(100)).trunc();
let moved = i64::try_from(moved.mantissa()).unwrap();
assert!(moved <= 1, "{whole} by {weights:?}: moved {moved} cents");
self.max_moved_cents = self.max_moved_cents.max(moved);
}
if self.examples.len() < 3 {
let show = |v: &[Decimal]| {
v.iter()
.map(|d| d.to_string())
.collect::<Vec<_>>()
.join(" / ")
};
self.examples.push(format!(
"{whole} by {} -> was {}, now {}",
weights
.iter()
.map(|d| d.to_string())
.collect::<Vec<_>>()
.join("/"),
show(&old),
show(&new)
));
}
}
fn report(&self, name: &str) {
println!(
"{name:<44} {:>8} runs {:>8} differ {:>7.3}% max {} cent/part",
self.runs,
self.differ,
100.0 * self.differ as f64 / self.runs as f64,
self.max_moved_cents
);
for e in &self.examples {
println!(" e.g. {e}");
}
}
}
const RUNS: u64 = 60_000;
/// A random whole of 0.01 to 1,000,000.00; `dollars` rounds it to whole
/// dollars (round amounts are the realistic ones, and tie more).
fn random_whole(rng: &mut Rng, dollars: bool) -> Decimal {
let c = 1 + rng.below(100_000_000) as i64;
if dollars {
cents(((c + 99) / 100) * 100)
} else {
cents(c)
}
}
fn random_percentages(rng: &mut Rng) -> Vec<Decimal> {
let n = 2 + rng.below(4) as usize;
// A random composition of 100 into n positive whole percentages.
let mut cuts: Vec<u64> = Vec::new();
while cuts.len() < n - 1 {
let c = 1 + rng.below(99);
if !cuts.contains(&c) {
cuts.push(c);
}
}
cuts.sort_unstable();
let mut prev = 0;
let mut out = Vec::new();
for c in cuts.iter().copied().chain(std::iter::once(100)) {
out.push(Decimal::from(c - prev));
prev = c;
}
out
}
fn random_small_integers(rng: &mut Rng) -> Vec<Decimal> {
let n = 2 + rng.below(4) as usize;
(0..n).map(|_| Decimal::from(1 + rng.below(5))).collect()
}
/// The splits an agreement is likely to name.
const COMMON: &[&[i64]] = &[
&[50, 50],
&[60, 40],
&[70, 30],
&[75, 25],
&[80, 20],
&[90, 10],
&[34, 33, 33],
&[40, 30, 30],
&[50, 25, 25],
&[60, 20, 20],
&[25, 25, 25, 25],
&[40, 20, 20, 20],
&[20, 20, 20, 20, 20],
];
/// Equal weights: every remainder is `w x (whole - n x part)`, equal for
/// every part, so both rankings give the leftover cents to the earliest
/// parts and never differ. Two 50/50 members, thirds, quarters: no cent
/// moves, ever.
#[test]
fn equal_weights_never_differ() {
let mut rng = Rng(0x9E37_79B9_7F4A_7C15);
let mut t = Tally::default();
for i in 0..RUNS {
let n = 2 + rng.below(4) as usize;
let w = Decimal::from(1 + rng.below(100));
let weights = vec![w; n];
t.run(random_whole(&mut rng, i % 2 == 0), &weights);
}
t.report("equal weights (2-5 parties)");
assert_eq!(t.differ, 0);
}
/// Two parties never differ, whatever the weights. With two parts the
/// leftover is at most one cent, and the two remainders sum to `total` times
/// that cent, so they tie only at exactly half a cent over `total` each:
/// both shares then end in exactly half a cent, the quotient terminates,
/// and the rounded quotient ranks them as the exact one does. A two-member
/// company (the live books' shape) is therefore unmoved by K-U10.
#[test]
fn two_parties_never_differ() {
let mut rng = Rng(0x2545_F491_4F6C_DD1D);
let mut t = Tally::default();
for i in 0..RUNS {
let weights = [
Decimal::from(1 + rng.below(10_000)),
Decimal::from(1 + rng.below(10_000)),
];
t.run(random_whole(&mut rng, i % 2 == 0), &weights);
}
// And the smallest weights, where ties are the most frequent.
for a in 1..=12u64 {
for b in 1..=12u64 {
for c in 1..=300 {
t.run(cents(c), &[Decimal::from(a), Decimal::from(b)]);
}
}
}
t.report("two parties, any weights");
assert_eq!(t.differ, 0);
}
/// The measurement: how often the old and new rankings differ, by class
/// of weights and of amount. Asserts only the structure (both sum to the
/// whole; a difference needs an exact tie and is at most a cent a part);
/// the rates are printed for the owner.
#[test]
fn what_exact_tie_ranking_moves() {
println!();
for dollars in [false, true] {
let kind = if dollars {
"whole dollars"
} else {
"any cents"
};
let mut rng = Rng(0xD1B5_4A32_D192_ED03);
let mut t = Tally::default();
for _ in 0..RUNS {
let w = random_percentages(&mut rng);
t.run(random_whole(&mut rng, dollars), &w);
}
t.report(&format!("whole percentages, {kind}"));
let mut t = Tally::default();
for _ in 0..RUNS {
let w: Vec<Decimal> = COMMON[rng.below(COMMON.len() as u64) as usize]
.iter()
.map(|&p| Decimal::from(p))
.collect();
t.run(random_whole(&mut rng, dollars), &w);
}
t.report(&format!("common agreements, {kind}"));
let mut t = Tally::default();
for _ in 0..RUNS {
let w = random_small_integers(&mut rng);
t.run(random_whole(&mut rng, dollars), &w);
}
t.report(&format!("small integers 1-5, {kind}"));
}
// The K-1 property split's real shape: weights are the members'
// credits in one entry (whole dollars to 10,000), the whole at most
// their sum.
let mut rng = Rng(0xA076_1D64_78BD_642F);
let mut t = Tally::default();
for _ in 0..RUNS {
let n = 2 + rng.below(4) as usize;
let w: Vec<Decimal> = (0..n)
.map(|_| Decimal::from(1 + rng.below(10_000)))
.collect();
let total: Decimal = w.iter().copied().sum();
let pool = cents(1 + rng.below(total.mantissa() as u64 * 100) as i64);
t.run(pool, &w);
}
t.report("K-1 credits, whole dollars to 10,000");
// The 4/1/1 shape, every whole-dollar amount to 100.
let mut t = Tally::default();
for d in 1..=100 {
t.run(
Decimal::from(d),
&[Decimal::from(4), Decimal::ONE, Decimal::ONE],
);
}
t.report("4/1/1, $1 to $100 whole dollars");
}
/// The pinned examples, in dollars and cents, with both answers.
#[test]
fn the_pinned_examples_move_as_the_owner_was_told() {
let w = [Decimal::from(4), Decimal::ONE, Decimal::ONE];
let six = Decimal::from(6);
let show = |v: Vec<Decimal>| v.iter().map(Decimal::to_string).collect::<Vec<_>>();
assert_eq!(
show(old_split(cents(2000), &w, six)),
["13.33", "3.34", "3.33"]
);
assert_eq!(
show(new_split(cents(2000), &w, six)),
["13.34", "3.33", "3.33"]
);
}
/// Weights of `places` places that sum to `total` exactly: `n - 1` of
/// `total / n` rounded down, and a last one taking what is left. Built on
/// the mantissas: `Decimal` cannot hold the running sum of percents of 27
/// places (88.888...8 has 29 digits and passes its 96 bits), and would
/// round it without a word, which is the fault K-U10 closed in the kernel.
fn even_weights(total: i128, n: u32, places: u32) -> Vec<Decimal> {
let whole = total * 10i128.pow(places);
let w = whole / i128::from(n);
let last = whole - w * i128::from(n - 1);
let mut weights = vec![Decimal::from_i128_with_scale(w, places); n as usize];
*weights.last_mut().unwrap() = Decimal::from_i128_with_scale(last, places);
assert_eq!(weights.iter().map(Decimal::mantissa).sum::<i128>(), whole);
weights
}
/// K-U10 made the kernel's product exact or refused. A split by shares
/// of 28 places that sum to one (as a convention's shares do) or by
/// percents of 27 places that sum to 100 (thirds, sevenths, ninths) has
/// products past `Decimal`'s 28 digits, so the ranking uses the rounding
/// product there: the split is made, not refused, the parts sum to the
/// whole, and each is within a cent of its share. A negative whole is
/// rounded down, as apportioning requires (the parts rounded toward zero
/// would pass the whole, which `apportion` refuses).
#[test]
fn a_split_by_weights_of_27_places_is_made_not_refused() {
let cent = cents(1);
for (total, places) in [(1i128, 28u32), (100, 27)] {
for n in [3u32, 6, 7, 9, 11] {
let weights = even_weights(total, n, places);
let total = Decimal::from_i128_with_scale(total, 0);
let amounts = (1..=400_000i64)
.step_by(37)
.chain([23_769, 99_999_999_999_999_999, 100_000_000_000_000_000])
.flat_map(|c| [c, -c]);
for c in amounts {
let whole = cents(c);
let mode = if c < 0 {
Rounding::TowardNegativeInfinity
} else {
Rounding::TowardZero
};
let parts = split_by_weights_with(
whole,
&weights,
total,
cent,
|x| round_places(x, 2, mode),
Leftover::LargestRemainder,
)
.unwrap_or_else(|| panic!("{whole} by {n} parts of {places} places was refused"));
assert_eq!(
parts.iter().copied().sum::<Decimal>(),
whole,
"{whole} by {n}"
);
for (p, &wt) in parts.iter().zip(&weights) {
let share = share_of(whole, wt, total).unwrap();
assert!(
(*p - share).abs() < cent,
"{whole} by {n}: {p} for a share of {share}"
);
}
}
}
}
}