expression

Numerically stable accumulation

Adding tiny increments to a large total can lose information at each step. A compensated sum retains a correction for some lost low-order digits; it is not exact in every case. Expected stdout (not executed): 0 2 Common mistake: Reordering arithmetic can change the result; compensation is not arbitrary precision.

Formal Syntax & Structure

rust syntaxrust
sum with explicit compensation

Working Example

Example Snippetrust
fn main() {    let items = [1e16_f64, 1.0, 1.0, -1e16];    let mut plain = 0.0_f64;    for x in items { plain += x; }    let (mut sum, mut correction) = (0.0_f64, 0.0_f64);    for x in items {        let y = x - correction;        let next = sum + y;        correction = (next - sum) - y;        sum = next;    }    println!("{} {}", plain, sum);}
Rust Reference