refactor(core): proportional shares in the kernel, one copy

The K-1/1065 worksheet, the 1099 worksheet, the parties' shares, the
conventions' template split and the cash-flow government split each
computed "whole x weight / total, round, hand out the leftover" for
themselves. Six copies meant six places for a rounding or sign change to
reach a filed figure.

Put the shape in kernel::allocate: share_of (the engine's division,
rounded at Decimal's 28 significant digits, truncating on a machine
integer), share_floor_with (the exact floor to a step by multiplication,
the 1099 correction loop's arithmetic), and split_by_weights_with (the
split, with the leftover policy named: largest remainder, first absorbs,
last absorbs; the running policy stays apportion_cumulative). Each site
keeps its own mode, step, sign and leftover policy, so every figure is
the same to the digit; the frozen periods rules only gain a doc line
naming the kernel policy they equal.

Amount gains checked_div, the engine's division as distinct from
checked_div_exact.

All goldens and existing tests pass unchanged.

Co-Authored-By: DeepSeek V4.1 Flash <noreply@opencode.ai>
This commit is contained in:
swaitsandDeepSeek V4.1 Flash committed 2026-11-09 00:14:26 -07:00
1 parent 127d33fb0b
commit 24b59e7b85
9 files changed
+394 -84

No files matched your search

+1 -3
View File
@@ -1717,9 +1717,7 @@ fn split_part(
places: u32,
) -> Result<(Decimal, Decimal), LedgerError> {
let whole = add(ours, theirs, "an entry's party shares")?;
let part = amount
.checked_mul(ours)
.and_then(|x| x.checked_div(whole))
let part = crate::kernel::share_of(amount, ours, whole)
.ok_or_else(|| too_large("a payment's government part"))?;
let part = crate::kernel::round_places(part, places, crate::kernel::Rounding::HalfToEven)
.ok_or_else(|| too_large("a payment's government part"))?;
+22 -19
View File
@@ -454,27 +454,30 @@ pub fn check_id(id: &str) -> Result<(), String> {
/// ([`crate::kernel::apportion`]): the parts sum to `amount` exactly
/// (INVARIANT 2).
pub fn split(amount: Decimal, shares: &[Decimal], places: Option<u32>) -> Option<Vec<Decimal>> {
use crate::kernel::{Rounding, round_places};
let exact: Vec<Decimal> = shares
.iter()
.map(|s| amount.checked_mul(*s))
.collect::<Option<_>>()?;
use crate::kernel::{Leftover, Rounding, round_places, split_by_weights_with};
let Some(places) = places else {
let mut parts = exact;
crate::kernel::plug_last(amount, &mut parts)?;
return Some(parts);
// No rounding: each part is amount × share, the last absorbing
// any difference (the exact split's own plug).
return split_by_weights_with(
amount,
shares,
Decimal::ONE,
Decimal::ONE,
Some,
Leftover::LastAbsorbs,
);
};
let mut parts: Vec<Decimal> = exact
.iter()
.map(|e| round_places(*e, places, Rounding::TowardZero))
.collect::<Option<_>>()?;
let remainders: Vec<Decimal> = exact
.iter()
.zip(&parts)
.map(|(e, p)| e.checked_sub(*p))
.collect::<Option<_>>()?;
crate::kernel::apportion(amount, &mut parts, &remainders, Decimal::new(1, places))?;
Some(parts)
// amount × share, each part truncated toward zero to `places`, the
// leftover by largest remainder. The shares sum to one by the
// conventions' own validation, so the total is one, never their sum.
split_by_weights_with(
amount,
shares,
Decimal::ONE,
Decimal::new(1, places),
|x| round_places(x, places, Rounding::TowardZero),
Leftover::LargestRemainder,
)
}
impl Conventions {
+14 -23
View File
@@ -718,14 +718,11 @@ fn vendor_part(payment: Decimal, share: Decimal, target: Decimal) -> Result<Deci
} else if target.is_zero() {
Ok(Decimal::ZERO)
} else {
let scaled = payment
.checked_mul(share)
.and_then(|x| x.checked_div(target))
.ok_or_else(|| {
LedgerError::TooLargeToCompute(format!(
"a vendor's share ({share}) of a payment of {payment}"
))
})?;
let scaled = crate::kernel::share_of(payment, share, target).ok_or_else(|| {
LedgerError::TooLargeToCompute(format!(
"a vendor's share ({share}) of a payment of {payment}"
))
})?;
kernel::round_places(scaled, 2, kernel::Rounding::HalfAwayFromZero).ok_or_else(|| {
LedgerError::TooLargeToCompute(format!(
"a vendor's share ({share}) of a payment of {payment}"
@@ -752,28 +749,22 @@ fn split_share(b: [Decimal; 3], v: Decimal) -> Result<[Decimal; 3], LedgerError>
}
let (av, ap) = (v.abs(), p.abs());
let cent = Decimal::new(1, 2);
let times = |x: Decimal| x.checked_mul(ap).ok_or_else(too_large);
let mut parts = [Decimal::ZERO; 3];
let mut rems = [Decimal::ZERO; 3];
for i in 0..3 {
if b[i].is_zero() {
continue;
}
// The exact share is num / ap: rounded down to the cent, checked
// exactly (the division alone rounds past 28 digits).
let num = b[i].abs().checked_mul(av).ok_or_else(too_large)?;
let q = num.checked_div(ap).ok_or_else(too_large)?;
let mut part =
kernel::round_places(q, 2, kernel::Rounding::TowardZero).ok_or_else(too_large)?;
while times(part)? > num {
part = part.checked_sub(cent).ok_or_else(too_large)?;
}
while times(part.checked_add(cent).ok_or_else(too_large)?)? <= num {
part = part.checked_add(cent).ok_or_else(too_large)?;
}
// The remainder, over the common denominator ap.
rems[i] = num.checked_sub(times(part)?).ok_or_else(too_large)?;
// The exact share is |b[i]| × av ÷ ap, floored to the cent by
// multiplication (the division alone rounds past 28 digits); the
// kernel returns the exact floor and the exact remainder over the
// common denominator ap.
let (part, rem) = kernel::share_floor_with(b[i].abs(), av, ap, cent, |x| {
kernel::round_places(x, 2, kernel::Rounding::TowardZero)
})
.ok_or_else(too_large)?;
parts[i] = part;
rems[i] = rem;
}
kernel::apportion(av, &mut parts, &rems, cent).ok_or_else(too_large)?;
if v.is_sign_negative() {
+13 -17
View File
@@ -343,7 +343,7 @@ pub(crate) fn share_property(
credits: &[Decimal],
places: u32,
) -> Result<Vec<Decimal>, LedgerError> {
use crate::kernel::{Rounding, round_places};
use crate::kernel::{Leftover, Rounding, round_places, split_by_weights_with};
let too_large =
|| LedgerError::TooLargeToCompute("a member's share of contributed property".into());
let total = credits
@@ -354,22 +354,18 @@ pub(crate) fn share_property(
if whole <= Decimal::ZERO || total <= Decimal::ZERO {
return Ok(vec![Decimal::ZERO; credits.len()]);
}
// whole × credit is exact; ÷ total is exact whenever the share is a
// whole number of units, so truncating never loses a unit it is owed.
let exact: Vec<Decimal> = credits
.iter()
.map(|c| whole.checked_mul(*c).and_then(|x| x.checked_div(total)))
.collect::<Option<_>>()
.ok_or_else(too_large)?;
let mut parts: Vec<Decimal> = exact
.iter()
.map(|x| round_places(*x, places, Rounding::TowardZero))
.collect::<Option<_>>()
.ok_or_else(too_large)?;
let remainders: Vec<Decimal> = exact.iter().zip(&parts).map(|(x, p)| x - p).collect();
crate::kernel::apportion(whole, &mut parts, &remainders, Decimal::new(1, places))
.expect("each part is short by under a unit, so the shortfall is under a unit per member");
Ok(parts)
// whole × credit ÷ total, each part truncated toward zero to the
// currency's places, the leftover units by largest remainder. The
// kernel is the one copy of the shape (BS-partner-4's entry split).
split_by_weights_with(
whole,
credits,
total,
Decimal::new(1, places),
|x| round_places(x, places, Rounding::TowardZero),
Leftover::LargestRemainder,
)
.ok_or_else(too_large)
}
/// The party a member (by name, as in wanderbooks.toml) is in the
+299 -4
View File
@@ -1,5 +1,300 @@
//! U3: proportional shares, splitting a whole by weights without drift (kernel sweep).
//! Proportional shares and weighted splits: `whole × weight ÷ total`,
//! rounded to a step, the leftover handed out by a named policy. The
//! kernel sweep's U3 (`plan/kernel-sweep-audit.md` section 3): the six
//! local copies of this arithmetic (the K-1/1065 worksheet, the 1099
//! worksheet, the parties' shares, the conventions' template split and the
//! statement of cash flows' government split) call one implementation.
//!
//! Empty in U0: the unit adds its arithmetic here, in this file alone, so
//! no two sweep units ever edit the same file. The module root re-exports
//! it, keeping every path `crate::kernel::foo`.
//! Division is not exact: [`share_of`] is the amount type's checked
//! division, so a `Decimal` quotient is rounded at 28 significant digits
//! (and a machine integer's is truncated), never an exact rational. Every
//! invariant below is stated of that computation, and of the parts after
//! the named leftover policy, which do sum to the whole exactly. See
//! `docs/proofs/k-u3.md` for the one place the quotient's rounding can
//! change a rounded part (Decimal's edge, K-U10).
use super::round::Rounding;
use super::{Amount, apportion, plug_last, round_step};
/// What a split does with the units its rounded parts leave over.
#[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 (ties to the earlier part). [`apportion`].
LargestRemainder,
/// The last part becomes the whole less the others. [`plug_last`].
LastAbsorbs,
/// The first part becomes the whole less the others.
FirstAbsorbs,
}
/// One member's share of `whole`: `whole × weight ÷ total`.
///
/// ```text
/// GOAL: one definition of "share = whole x weight / total", the arithmetic
/// every proportional split in the engine rests on.
/// SOURCE: BS-partner-1 (partners share by the agreement; capital accounts
/// carry the allocations), BS-partner-3 (a party's part of an
/// entry), BS-partner-4 (the K-1 worksheet), BS-1099-1 (a payment
/// split by the parties' shares), BS-statement-3 rule 5 (the
/// government's part of a payment), BS-arap-3 (a document line's
/// exact amount).
/// INVARIANTS:
/// 1. Some(s) is the amount type's `checked_mul` of whole and weight,
/// then its checked division by total. For Decimal the product and
/// quotient are exact while they fit 96 bits and scale 28, and are
/// rounded at that edge (rust_decimal's checked operations, K-U10);
/// for a machine integer the division truncates toward zero. This is
/// the computation the six call sites made before U3, to the digit.
/// 2. None when total is zero, or when the product or quotient is not
/// representable. Never a panic, never a wrapped amount.
/// 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
/// amount type's quotient, never a guessed one.
/// SCENARIOS:
/// 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
/// exact rational; the split's rounding makes the part exact to its
/// step.
/// 3. IF the product or the quotient is past the amount's range: SHOULD
/// be None.
/// ```
pub fn share_of<T: Amount>(whole: T, weight: T, total: T) -> Option<T> {
whole.checked_mul(weight)?.checked_div(total)
}
/// The largest whole multiple of `step` not above `whole × weight ÷ total`,
/// with the exact remainder scaled by `total`.
///
/// ```text
/// GOAL: the exact floor of a proportional share to a step, without
/// trusting a rounded quotient, and the exact remainder that ranks
/// the parts of a largest-remainder split.
/// SOURCE: BS-1099-1 (a payment split into its buckets to the cent),
/// BS-entry-3 (amounts are exact; round only where a rule says
/// to), BS-partner-1 (largest remainder).
/// INVARIANTS:
/// 1. whole and weight are non-negative (the callers pass magnitudes).
/// Provided `part x total` and `(part + step) x total` are exact
/// (inside Decimal's 96-bit mantissa; true for every posted line),
/// Some((part, remainder)): part is a whole multiple of step,
/// part x total <= whole x weight, and (part + step) x total >
/// whole x weight. So part is the exact floor of the share to step,
/// whatever the quotient's rounding did. At Decimal's mantissa edge
/// the comparison product itself rounds, and the correction can keep
/// a step the exact rational would not (K-U10; pinned in the bridge).
/// 2. remainder = whole x weight - part x total, in [0, step x total)
/// when total and step are positive: the exact remainder below the
/// next step, scaled by total, never the rounded quotient's
/// difference (exact when the products are; the edge above inherits
/// the product's rounding).
/// 3. None when step or total is not positive, a product is not
/// representable, or the correction leaves the range; never a panic.
/// SCENARIOS:
/// 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.
/// 2. IF the quotient rounds up across a step (Decimal's 28 digits at
/// the edge), while the comparison products are exact: SHOULD still
/// be the exact floor, the correction taking the step back.
/// ```
pub fn share_floor_with<T: Amount>(
whole: T,
weight: T,
total: T,
step: T,
round: impl Fn(T) -> Option<T>,
) -> Option<(T, T)> {
if total <= T::ZERO || step <= T::ZERO {
return None;
}
let num = whole.checked_mul(weight)?;
let quotient = num.checked_div(total)?;
let mut part = round(quotient)?;
// The quotient may have rounded across the exact floor: take whole
// steps back until part x total <= num, then forward while one more
// step still fits. The comparisons multiply, never divide; they are
// exact while the product fits Decimal's mantissa (the edge is
// K-U10, pinned in the bridge).
while part.checked_mul(total)? > num {
part = part.checked_sub(step)?;
}
loop {
let next = part.checked_add(step)?;
if next.checked_mul(total)? > num {
break;
}
part = next;
}
let remainder = num.checked_sub(part.checked_mul(total)?)?;
Some((part, remainder))
}
/// [`share_floor_with`] with [`round_step`] as the first estimate: the
/// exact floor of `whole × weight ÷ total` to `step`, in `mode`'s
/// direction (only `TowardZero` is the floor; the correction makes the
/// result exact either way).
pub fn share_floor<T: Amount>(
whole: T,
weight: T,
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
/// rounded by `round`, the leftover by `policy`, written into `parts` (and
/// `remainders`, a scratch buffer for the largest-remainder policy).
///
/// ```text
/// GOAL: split a whole by weights without drift: the parts sum to the
/// whole exactly, each is within one step of the share the kernel
/// computes (the largest-remainder policy), and no part exceeds the
/// whole.
/// SOURCE: BS-partner-1 (partners share by the agreement; the largest
/// remainder is the owner's choice, 2026-10-13), BS-partner-3 (a
/// party's part of an entry), BS-partner-4 (the K-1 worksheet's
/// shares), BS-1099-1 (a payment's buckets), BS-statement-3 rule 5
/// (the government's part), BS-arap-3 (a document line's exact
/// amount), BS-ledger-1 (a whole number of smallest units).
/// INVARIANTS:
/// 1. With total not zero and at least one weight, the parts sum to
/// whole exactly, whatever the policy: the largest-remainder policy
/// hands out the shortfall by [`apportion`], the first/last-absorbs
/// policies give the first or last part the whole less the others
/// ([`plug_last`] for the last). An empty weight list is an empty
/// split (the callers' existing answer).
/// 2. With total not zero, every part is the share `share_of` computes,
/// rounded by `round`; under the largest-remainder policy each part
/// is within one step of that share (`part x total - whole x weight`
/// is above `-total` and at most `total` when the step is one unit;
/// the upper bound is strict when the division keeps the fraction, as
/// `Decimal` does, and a machine integer's truncating division can
/// put a part exactly one step above, never more). That share is the
/// exact rational while the division and the comparison products are
/// exact; at Decimal's mantissa edge the quotient's rounding can put
/// 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.
/// 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.
/// 4. total of zero is the callers' "nothing to split by": every part is
/// zero (k1's and shares::split_first's existing answer), never a
/// division by zero.
/// 5. None when the slices' lengths differ, a share or a part is not
/// representable, the unit is not positive for the largest-remainder
/// policy, or apportion refuses (the shortfall is not rounding).
/// Never a panic. On None the contents of the buffers are not
/// promised.
/// SCENARIOS:
/// 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).
/// 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
/// zero total) or the largest-remainder handout of the whole (a
/// positive total with zero weights, as the conventions' template
/// split has always done).
/// ```
#[allow(clippy::too_many_arguments)] // one argument per split input and buffer
pub fn split_by_weights_into<T: Amount>(
whole: T,
weights: &[T],
total: T,
unit: T,
round: impl Fn(T) -> Option<T>,
policy: Leftover,
parts: &mut [T],
remainders: &mut [T],
) -> Option<()> {
if parts.len() != weights.len() || remainders.len() != weights.len() {
return None;
}
if total == T::ZERO {
// Nothing to split by: the call sites' existing answer.
parts.fill(T::ZERO);
return Some(());
}
// The exact shares first, so a failure leaves parts untouched until
// every share is known; the buffer doubles as the largest-remainder
// scratch below.
for i in 0..weights.len() {
remainders[i] = share_of(whole, weights[i], total)?;
}
for i in 0..weights.len() {
parts[i] = round(remainders[i])?;
}
match policy {
Leftover::LargestRemainder => {
if unit <= T::ZERO {
return None;
}
for i in 0..weights.len() {
remainders[i] = remainders[i].checked_sub(parts[i])?;
}
apportion(whole, parts, remainders, unit)
}
Leftover::LastAbsorbs => plug_last(whole, parts),
Leftover::FirstAbsorbs => {
let Some((first, rest)) = parts.split_first_mut() else {
return Some(());
};
let mut others = T::ZERO;
for &p in rest.iter() {
others = others.checked_add(p)?;
}
*first = whole.checked_sub(others)?;
Some(())
}
}
}
/// [`split_by_weights_into`] allocating its two buffers: the shape the
/// call sites use.
pub fn split_by_weights_with<T: Amount>(
whole: T,
weights: &[T],
total: T,
unit: T,
round: impl Fn(T) -> Option<T>,
policy: Leftover,
) -> Option<Vec<T>> {
let mut parts = vec![T::ZERO; weights.len()];
let mut remainders = vec![T::ZERO; weights.len()];
split_by_weights_into(
whole,
weights,
total,
unit,
round,
policy,
&mut parts,
&mut remainders,
)?;
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,
)
}
+21
View File
@@ -33,6 +33,18 @@ pub trait Amount: Copy + Ord {
/// `self / rhs` exactly, or `None` when `rhs` is zero or the quotient
/// is not a whole amount of `Self` (never a rounded share).
fn checked_div_exact(self, rhs: Self) -> Option<Self>;
/// `self / rhs` as the amount type divides: exact where the division
/// terminates, otherwise rounded at the type's precision (for
/// [`Decimal`], 28 significant digits), and truncating toward zero for
/// a machine integer. `None` when `rhs` is zero or the quotient cannot
/// be represented.
///
/// This is the engine's division, not a claim that the quotient is an
/// exact rational: [`Amount::checked_div_exact`] is that one. A
/// proportional share ([`crate::kernel::share_of`]) is this division,
/// so its result is the same figure every call site computed before
/// the kernel sweep's U3.
fn checked_div(self, rhs: Self) -> Option<Self>;
/// `self / rhs`, rounded once to the cent (the nearest whole minor
/// unit: a unit for a machine integer, two decimal places for
/// [`Decimal`] dollars), ties away from zero; never a negative zero.
@@ -86,6 +98,9 @@ impl Amount for Decimal {
let q = self.checked_div(rhs)?;
(q.checked_mul(rhs) == Some(self)).then_some(q)
}
fn checked_div(self, rhs: Self) -> Option<Self> {
Decimal::checked_div(self, rhs)
}
fn checked_div_round_cent(self, rhs: Self) -> Option<Self> {
if rhs == Self::ZERO {
return None;
@@ -185,6 +200,9 @@ impl Amount for i32 {
}
self.checked_div(rhs)
}
fn checked_div(self, rhs: Self) -> Option<Self> {
i32::checked_div(self, rhs)
}
fn checked_div_round_cent(self, rhs: Self) -> Option<Self> {
if rhs == 0 {
return None;
@@ -237,6 +255,9 @@ impl Amount for i64 {
}
self.checked_div(rhs)
}
fn checked_div(self, rhs: Self) -> Option<Self> {
i64::checked_div(self, rhs)
}
fn checked_div_round_cent(self, rhs: Self) -> Option<Self> {
if rhs == 0 {
return None;
+8
View File
@@ -120,6 +120,10 @@ pub struct MemberClose {
/// (owner, 2026-10-13). A loss splits as the negation of the same gain.
/// Closes journaled under the rules of 2026-10-13 replay with it, in cents
/// whatever the currency; new closes split with [`allocate_cumulative`].
/// The arithmetic equals [`crate::kernel::split_by_weights_with`] with
/// total one, the cent as its step, toward zero and
/// [`crate::kernel::Leftover::LargestRemainder`], the sign applied after;
/// it stays here, frozen, because posted closes replay with it.
pub fn allocate(
amount: rust_decimal::Decimal,
shares: &[rust_decimal::Decimal],
@@ -180,6 +184,10 @@ pub fn allocate_last_absorbs(
/// (replay of a legacy close with a huge journaled amount, BS-entry-4).
/// The same split, to the cent, for every amount [`allocate_last_absorbs`]
/// accepts: this is the frozen rule, only its overflow now an error.
/// The arithmetic equals [`crate::kernel::split_by_weights_with`] with
/// total one, the cent as its step, half away from zero and
/// [`crate::kernel::Leftover::LastAbsorbs`]; it stays here, frozen,
/// because posted closes replay with it.
pub fn try_allocate_last_absorbs(
amount: rust_decimal::Decimal,
shares: &[rust_decimal::Decimal],
+12 -13
View File
@@ -284,23 +284,22 @@ fn checked_sum(values: impl IntoIterator<Item = Decimal>) -> Option<Decimal> {
/// part rounded toward zero to the cent, the cents left over to the first.
/// None when a product or sum is past exact arithmetic.
fn split_first(magnitude: Decimal, weights: &[Decimal]) -> Option<Vec<Decimal>> {
use crate::kernel::{Rounding, round_places};
use crate::kernel::{Leftover, Rounding, round_places, split_by_weights_with};
let total = checked_sum(weights.iter().copied())?;
if weights.is_empty() || total.is_zero() {
return Some(vec![Decimal::ZERO; weights.len()]);
}
let mut parts: Vec<Decimal> = weights
.iter()
.map(|w| {
magnitude
.checked_mul(*w)
.and_then(|x| x.checked_div(total))
.and_then(|x| round_places(x, 2, Rounding::TowardZero))
})
.collect::<Option<_>>()?;
let left = magnitude.checked_sub(checked_sum(parts.iter().copied())?)?;
parts[0] = parts[0].checked_add(left)?;
Some(parts)
// magnitude × weight ÷ total, each part truncated toward zero to the
// cent, the cents left over to the first (the legacy policy this
// split keeps). The kernel is the one copy of the shape.
split_by_weights_with(
magnitude,
weights,
total,
Decimal::new(1, 2),
|x| round_places(x, 2, Rounding::TowardZero),
Leftover::FirstAbsorbs,
)
}
/// What an entry's shares split, and what of it counts (the module's
+4 -5
View File
@@ -441,12 +441,11 @@ impl RunningSplit {
Ok((sum > Decimal::ZERO).then_some(sum))
}
/// `whole × weight / sum`, the exact share of one member.
/// `whole × weight / sum`, the exact share of one member, through
/// [`crate::kernel::share_of`] (the one definition of the shape; its
/// division is the engine's, rounded at 28 significant digits).
fn share(whole: Decimal, weight: Decimal, sum: Decimal) -> Result<Decimal, LedgerError> {
whole
.checked_mul(weight)
.and_then(|p| p.checked_div(sum))
.ok_or_else(too_large)
crate::kernel::share_of(whole, weight, sum).ok_or_else(too_large)
}
/// Split `whole` (to the cent) by `weights` (non-negative, one per