Fused Multiply-Add With mul_add

mul_add computes a*b+c with a single rounding; on huge factors the naive a*b+c loses the final unit that fused math keeps.

RustData Integrity

Code

rustsnippet
16 lines
fn main() {
    // fused multiply-add:mul_add 把 a*b+c 融合成一次舍入
    let a: f64 = 134217729.0; // 2^27 + 1
    let b: f64 = 134217729.0;
    let c: f64 = -18014398509481984.0; // -2^54

    // 精确的 a*b = 2^54 + 2^28 + 1,超出 53 位尾数:朴素写法先舍入乘积
    let fused = a.mul_add(b, c);
    let naive = a * b + c;
    println!("mul_add: {fused}"); // 268435457 = 2^28 + 1,一位不丢
    println!("a*b+c:   {naive}"); // 268435456,丢了 1

    // 常规量级下两者一致:折价 + 固定运费
    let total = 100.0_f64.mul_add(0.9, 5.0);
    println!("total: {total}");
}

How it works

Fused Multiply-Add With mul_add comes down to the function main.

Using it

The demo output is labeled (mul_add:, a*b+c:, total:), so every printed line maps back to its originating operation.

Key statements

let c: f64 = -18014398509481984.0; // -2^54
// 精确的 a*b = 2^54 + 2^28 + 1,超出 53 位尾数:朴素写法先舍入乘积
let fused = a.mul_add(b, c);
let total = 100.0_f64.mul_add(0.9, 5.0);
let a: f64 = 134217729.0; // 2^27 + 1
let b: f64 = 134217729.0;

Interactive Tools for This Topic

FAQ

What does Fused Multiply-Add With mul_add print when run?
Execute the whole file; each printed line is prefixed with a label like `mul_add:`, `a*b+c:`, `total:`.