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.
Code
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
Date Add/Subtract CalculatorAdd or subtract days, weeks, months, or years from a date, clamping month ends such as January 31 plus one month.GCD & LCM CalculatorFind the greatest common divisor and least common multiple of two or more integers, computed exactly with BigInt.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.Vector Similarity CalculatorCompute Cosine Similarity, Dot Product, Euclidean L2, Manhattan L1, and Chebyshev distances between numeric vectors with dimension checks.
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:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.