Files
pplus-library/modules/stats/mean/proof/mean.dfy
T
alexmandClaude df12b2a008 Start pplus-library: 16 verified routines in six modules
Routines written once in pseudo and checked at every level, so programs
can use them by name instead of rewriting and re-verifying them:

- stats: Mean, Variance (two-pass)
- numerics: KahanSum, LinearInterp, Trapezoid
- align: LinearGapPenalty, AffineGapPenalty, MatchScore,
  NeedlemanWunschScore
- md: LennardJones, LennardJonesForce, MinimumImage, PairDistance
- seq: GCContent, HammingDistance
- special: ErfApprox (Abramowitz and Stegun 7.1.26)

Each has contracts, cases, reference implementations in Python, Mojo
and (for the numerical ones) C at more than one level, and nine have a
Dafny proof over exact numbers. status.json and STATUS.md are written by
pplus-core's library-check: every check passes or is open/unverified as
listed there. The Mojo references still need the pinned compiler's
answers (library-verify-mojo, network).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FgvbRdoEheAHqsRmr2WuKZ
2026-10-05 11:58:22 +00:00

50 lines
1.3 KiB
Plaintext

// Mean, over real numbers. The FLOAT version rounds; this one does not.
function Sum(x: seq<real>): real
{
if |x| == 0 then 0.0 else Sum(x[..|x| - 1]) + x[|x| - 1]
}
method Mean(x: seq<real>) returns (m: real)
requires |x| > 0
ensures m == Sum(x) / (|x| as real)
{
var total := 0.0;
var i := 0;
while i < |x|
invariant 0 <= i <= |x|
invariant total == Sum(x[..i])
{
assert x[..i + 1][..i] == x[..i];
total := total + x[i];
i := i + 1;
}
assert x[..|x|] == x;
m := total / (|x| as real);
}
// Every value at most hi: the sum is at most |x| * hi.
lemma SumAtMost(x: seq<real>, hi: real)
requires forall i :: 0 <= i < |x| ==> x[i] <= hi
ensures Sum(x) <= (|x| as real) * hi
{
if |x| > 0 { SumAtMost(x[..|x| - 1], hi); }
}
// Every value at least lo: the sum is at least |x| * lo.
lemma SumAtLeast(x: seq<real>, lo: real)
requires forall i :: 0 <= i < |x| ==> lo <= x[i]
ensures (|x| as real) * lo <= Sum(x)
{
if |x| > 0 { SumAtLeast(x[..|x| - 1], lo); }
}
// In exact arithmetic the mean lies between any lower and upper bound of the values.
lemma MeanBetween(x: seq<real>, lo: real, hi: real)
requires |x| > 0
requires forall i :: 0 <= i < |x| ==> lo <= x[i] <= hi
ensures lo <= Sum(x) / (|x| as real) <= hi
{
SumAtMost(x, hi);
SumAtLeast(x, lo);
}