expression

Reduce rounding loss with compensated summation

Kahan summation maintains a correction for rounding lost during addition. For the finite inputs here it recovers two unit increments lost by ordinary sequential summation. It is not universally exact; overflow, non-finite inputs, ordering and ill-conditioned data still matter. Expected result (NOT RUN): naive: 0, compensated: 2 Common mistake: Assuming compensation guarantees an exact sum for every input. Static Rust example; not a verified ByteMind executable assessment.

Formal Syntax & Structure

rust syntaxrust
y = x - correction; t = sum + y; correction = (t - sum) - y; sum = t

Working Example

Example Snippetrust
fn kahan(xs: &[f64]) -> f64 {    let (mut sum, mut correction) = (0.0, 0.0);    for &x in xs {        let y = x - correction;        let t = sum + y;        correction = (t - sum) - y;        sum = t;    }    sum}fn main() {    let xs = [1e16_f64, 1.0, 1.0, -1e16];    let naive = xs.iter().fold(0.0, |acc, &x| acc + x);    println!("naive: {naive}, compensated: {}", kahan(&xs));}
Rust Reference