27 lines
593 B
Plaintext
27 lines
593 B
Plaintext
function Sum(x: seq<real>): real
|
|
{
|
|
if |x| == 0 then 0.0 else Sum(x[..|x| - 1]) + x[|x| - 1]
|
|
}
|
|
|
|
// In exact arithmetic Kahan summation is the plain sum, and its compensation is always 0.
|
|
method KahanSum(x: seq<real>) returns (total: real)
|
|
ensures total == Sum(x)
|
|
{
|
|
total := 0.0;
|
|
var c := 0.0;
|
|
var i := 0;
|
|
while i < |x|
|
|
invariant 0 <= i <= |x|
|
|
invariant total == Sum(x[..i])
|
|
invariant c == 0.0
|
|
{
|
|
assert x[..i + 1][..i] == x[..i];
|
|
var y := x[i] - c;
|
|
var t := total + y;
|
|
c := (t - total) - y;
|
|
total := t;
|
|
i := i + 1;
|
|
}
|
|
assert x[..|x|] == x;
|
|
}
|