Math fma Fused Multiply Add Single Rounding

Math.fma computes a*b+c with unlimited intermediate precision and rounds once, so it can differ from the two-rounding expression a*b+c in the last bits.

JavaData Integrity

Code

snippet
public class FusedMath {

    public static void main(String[] args) {
        // fma:精确乘积加 c 后只舍入一次(IEEE 754 fusedMultiplyAdd,JDK 9+)
        double f = Math.fma(0.1, 0.2, -0.02);
        // 常规表达式:乘一次舍入、加一次再舍入,两处误差都可能留下
        double t = 0.1 * 0.2 + (-0.02);
        System.out.println("fma:      " + f);
        System.out.println("a*b+c:    " + t);
        System.out.println("differ:   " + (f != t));

        // 符号零:fma(-0.0,+0.0,+0.0) 是 +0.0,而 (-0.0*+0.0) 是 -0.0
        System.out.println("fma sign: " + Math.signum(Math.fma(-0.0, 0.0, 0.0)));
        System.out.println("mul sign: " + Math.signum(-0.0 * 0.0));

        // 无效组合按 IEEE 语义得 NaN,不抛 ArithmeticException
        System.out.println("inf*0+c:  "
                + Math.fma(Double.POSITIVE_INFINITY, 0.0, 1.0));
    }
}

Inside the snippet

All of the logic lives in the class FusedMath and the function main.

What to watch for

  • Self-sufficient by design — there is no registry and no lockfile entry.

Using it

Signature: public static void main(String[] args)

Output lines are prefixed (fma:, a*b+c:, differ:), so every step’s effect is easy to pick out.

The key statements, annotated

double f = Math.fma(0.1, 0.2, -0.02);
double t = 0.1 * 0.2 + (-0.02);

Interactive Tools for This Topic

FAQ

What does Math fma Fused Multiply Add Single Rounding print when run?
The script runs standalone; its 6 labeled outputs include `fma:`, `a*b+c:`, `differ:`.