← 中文资源

简体中文版本

Math.fma 融合乘加单次舍入

Math.fma 以无限精度算 a*b+c 再只舍入一次,尾数可与两次舍入的 a*b+c 不同:0.1/0.2/-0.02 就是差异演示,符号零与 inf*0 组合按 IEEE 语义返回而非抛错。

阅读英文原文

实现说明

逻辑集中在类 FusedMath和函数 main里。

使用要点

  • 跑完文件,输出里会留下标记——fma:、a*b+c:、differ:。

常见问题

运行「Math.fma 融合乘加单次舍入」会打印什么?

不用做任何设置,直接把文件跑完——输出里的 fma:、a*b+c:、differ: 标签标明各步骤。

核心语句

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

代码示例

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));
    }
}