This is an automated email from the ASF dual-hosted git repository. aherbert pushed a commit to branch master in repository https://gitbox.apache.org/repos/asf/commons-numbers.git
commit 5474575dc44e5190278be58714bc6ce4e305f9da Author: Alex Herbert <[email protected]> AuthorDate: Wed Nov 18 20:15:13 2026 +0000 NUMBERS-220: Add use of hardware supported FMA in DD Use Math.fma to compute the round-off of a product x * y when the JVM reports hardware FMA support (HotSpot UseFMA flag) and Math.fma is accessible and checked to be fused. A single FMA replaces the Dekker two-product (splitting both factors, about 16 flops). This applies to DD, DDMath, ExtendedPrecision (Sum products) and Norm. Detection is performed once per JVM by the package-private FMASupport class. Java 8, non-HotSpot VMs and CPUs without FMA use the existing code. Results are identical to the software implementation within its documented range. Outside this range results may differ, e.g. FMA can compute a finite round-off where the Dekker split overflows to NaN. FMA use can be disabled with the system property org.apache.commons.numbers.core.DD.fma=false. This avoids the start-up cost of the hardware detection. An FMA Support section has been added to the user-guide. Without FMA the products and Dekker split round-off terms in DDMath computePowScaled and multiply3 are computed in the same order as version 1.3. Computing all the products before the round-off terms (the same arithmetic) was slower than 1.3 on x86-64 with the HotSpot C2 JIT compiler. Correct the rescale comment in the scaled power functions. Build: On Java 9+ the DDTest, ExtendedPrecisionTest and FMASupportTest are repeated with -XX:-UseFMA, -XX:+UseFMA, and the DD.fma property set to false and true. The Surefire argLine uses @{argLine} so the JaCoCo agent is kept on JDK 21+. The no-fma-support profile (Java 8, or -P on hardware without FMA) lowers the JaCoCo ratios as the FMA code paths are unreachable. The coverage workflow runs on Java 11 (was 8) to cover the FMA code paths. The method to detect hardware FMA support, the benchmark of the software Math.fma fallback, and the analysis of JIT regressions in the power functions (inlining; operation order on x86-64) were assisted by Claude Code. Generated-by: Claude Code (claude-opus-5-5) --- .github/workflows/coverage.yml | 3 +- commons-numbers-core/pom.xml | 102 +++++++ .../java/org/apache/commons/numbers/core/DD.java | 226 ++++++++++++---- .../org/apache/commons/numbers/core/DDMath.java | 170 ++++++++---- .../commons/numbers/core/ExtendedPrecision.java | 48 +++- .../apache/commons/numbers/core/FMASupport.java | 298 +++++++++++++++++++++ .../java/org/apache/commons/numbers/core/Norm.java | 16 +- .../org/apache/commons/numbers/core/DDExt.java | 105 +++++--- .../org/apache/commons/numbers/core/DDTest.java | 63 ++++- .../numbers/core/ExtendedPrecisionTest.java | 8 + .../commons/numbers/core/FMASupportTest.java | 185 +++++++++++++ .../apache/commons/numbers/core/UserGuideTest.java | 2 +- src/conf/checkstyle/checkstyle-suppressions.xml | 3 + src/site/apt/userguide/index.apt | 68 ++++- 14 files changed, 1138 insertions(+), 159 deletions(-) diff --git a/.github/workflows/coverage.yml b/.github/workflows/coverage.yml index 33d98cde..ab589d03 100644 --- a/.github/workflows/coverage.yml +++ b/.github/workflows/coverage.yml @@ -31,7 +31,8 @@ jobs: strategy: max-parallel: 20 matrix: - java: [ 8 ] + # Coverage of the DD FMA code paths requires Java 9+ (and hardware FMA) + java: [ 11 ] steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 diff --git a/commons-numbers-core/pom.xml b/commons-numbers-core/pom.xml index a498c254..957df77b 100644 --- a/commons-numbers-core/pom.xml +++ b/commons-numbers-core/pom.xml @@ -72,4 +72,106 @@ </plugins> </build> + <profiles> + <profile> + <!-- On Java 8 we cannot test FMA support. + Activate explicitly (-Pno-fma-support) when building on Java 9+ on + hardware without FMA support: the FMA code paths cannot be reached. --> + <id>no-fma-support</id> + <activation> + <jdk>(,9)</jdk> + </activation> + <properties> + <!-- No FMA code paths can be reached. Everything else should be tested. + These values should be raised as the codebase expands. --> + <commons.jacoco.instructionRatio>0.95</commons.jacoco.instructionRatio> + <commons.jacoco.methodRatio>0.96</commons.jacoco.methodRatio> + <commons.jacoco.branchRatio>0.96</commons.jacoco.branchRatio> + <commons.jacoco.lineRatio>0.96</commons.jacoco.lineRatio> + <commons.jacoco.complexityRatio>0.96</commons.jacoco.complexityRatio> + </properties> + </profile> + <profile> + <!-- On Java 9+ all code paths are tested on hardware with FMA support (default + JaCoCo coverage ratios). On hardware without FMA support use + -Pno-fma-support to apply the reduced coverage ratios. --> + <id>fma-support</id> + <activation> + <jdk>[9,)</jdk> + </activation> + <properties> + <!-- Tests repeated with each option to enable/disable FMA. + Comma-separated Surefire include patterns without spaces: + a pattern with a leading space is silently ignored. --> + <numbers.fma.tests>**/DDTest,**/ExtendedPrecisionTest,**/FMASupportTest</numbers.fma.tests> + </properties> + <!-- Test the methods that can enable/disable FMA. + argLine is set by jacoco so pass its settings through using the late + evaluation syntax @{argLine}: on Java 21+ the commons-parent java-21-up + profile defines argLine as a property, so ${argLine} would be resolved + before jacoco sets it and the jacoco agent would be dropped. --> + <build> + <plugins> + <plugin> + <artifactId>maven-surefire-plugin</artifactId> + <executions> + <execution> + <id>dd-no-use-fma</id> + <phase>test</phase> + <goals> + <goal>test</goal> + </goals> + <configuration> + <argLine>@{argLine} -XX:-UseFMA</argLine> + <includes> + <include>${numbers.fma.tests}</include> + </includes> + </configuration> + </execution> + <execution> + <id>dd-use-fma</id> + <phase>test</phase> + <goals> + <goal>test</goal> + </goals> + <configuration> + <argLine>@{argLine} -XX:+UseFMA</argLine> + <includes> + <include>${numbers.fma.tests}</include> + </includes> + </configuration> + </execution> + <execution> + <id>dd-property-disable</id> + <phase>test</phase> + <goals> + <goal>test</goal> + </goals> + <configuration> + <argLine>@{argLine} -Dorg.apache.commons.numbers.core.DD.fma=false</argLine> + <includes> + <include>${numbers.fma.tests}</include> + </includes> + </configuration> + </execution> + <execution> + <id>dd-property-enable</id> + <phase>test</phase> + <goals> + <goal>test</goal> + </goals> + <configuration> + <argLine>@{argLine} -Dorg.apache.commons.numbers.core.DD.fma=true</argLine> + <includes> + <include>${numbers.fma.tests}</include> + </includes> + </configuration> + </execution> + </executions> + </plugin> + </plugins> + </build> + </profile> + </profiles> + </project> diff --git a/commons-numbers-core/src/main/java/org/apache/commons/numbers/core/DD.java b/commons-numbers-core/src/main/java/org/apache/commons/numbers/core/DD.java index c5da397f..05234261 100644 --- a/commons-numbers-core/src/main/java/org/apache/commons/numbers/core/DD.java +++ b/commons-numbers-core/src/main/java/org/apache/commons/numbers/core/DD.java @@ -147,6 +147,64 @@ import java.util.function.DoubleUnaryOperator; * intermediate terms (see {@link #frexp(int[]) frexp} and {@link #scalb(int) scalb}) and * appropriate management of the current base 2 scale. * + * <p><b>Fused multiply-add (FMA) support</b> + * + * <p>The round-off part of the product of two {@code double} values is computed on all + * platforms using a software implementation (Dekker's split) of 16 floating-point + * operations (FLOPs). The same value can be computed using a fused multiply-add (FMA) + * operation in 2 FLOPs. FMA was added to Java 9 as + * <a href="https://docs.oracle.com/javase/9/docs/api/java/lang/Math.html#fma-double-double-double-"> + * {@code Math.fma}</a>. HotSpot-based Java Virtual Machines (VMs) detect hardware support + * for FMA and compile {@code Math.fma} to the FMA instruction. This is controlled by the + * HotSpot product flag {@code -XX:+UseFMA} ({@code -XX:-UseFMA} to disable); if not set + * explicitly the flag is {@code true} on processors that support FMA. + * + * <p>From version 1.4 this class detects hardware-enabled FMA once, on the first operation + * that computes the round-off of a product. FMA is used when all of the following conditions + * are met: + * <ul> + * <li>The system property {@code org.apache.commons.numbers.core.DD.fma} can be read and is + * either not set or set to {@code true} (case-insensitive); + * <li>The {@code Math.fma} method is found by a public look-up in the {@link Math} class + * using the {@link java.lang.invoke.MethodHandle MethodHandle} API; + * <li>The <a href="https://docs.oracle.com/javase/8/docs/jre/api/management/extension/com/sun/management/HotSpotDiagnosticMXBean.html"> + * HotSpotDiagnosticMXBean</a> reports the VM option "UseFMA" as {@code true}; + * <li>The method returns the correct finite result when the intermediate product + * {@code a * b} of {@code Math.fma(a, b, c)} overflows, i.e. the operation is fused. + * </ul> + * + * <p>Setting the system property {@code org.apache.commons.numbers.core.DD.fma} to + * {@code false} disables the use of FMA: no detection is performed and the software + * implementation is used. This avoids the one-off cost of the detection (which + * initialises the management API) for start-up cost sensitive applications, and provides + * the same results on all platforms outside the range supported by the software + * implementation. The property is read once, so it must be set when the JVM is started + * ({@code -Dorg.apache.commons.numbers.core.DD.fma=false}) or before the first product is + * computed. It applies to all classes in this package that compute the round-off of a + * product (e.g. {@link Sum} and {@link Norm}). + * + * <p>If FMA is not enabled, e.g. on Java 8 or VMs that are not based on HotSpot, the software + * implementation is used. When FMA is detected the round-off part of a product is computed as: + * <pre>{@code + * double x = a * b; + * double xx = Math.fma(a, b, -x); + * }</pre> + * + * <p>This is a performance-only change. Results are identical with and without FMA where + * the software implementation computes the exact product: the product is finite, the + * round-off part is not sub-normal, and the split arguments have a base 2 exponent below + * 996. Outside this range results may differ; for example FMA can compute a finite + * round-off where the software split overflows and creates NaN. When hardware FMA is not + * detected the performance is equivalent to version 1.3. When it is used, operators that + * compute the round-off of a product (multiply, square, divide, reciprocal, sqrt) are + * faster, and the integer power functions, which use repeated multiplication, run in + * approximately half the time on the platforms tested. + * + * <p>Users are recommended to keep the arguments and results of DD operations within the + * range supported by the software implementation (see <i>Overflow, underflow and + * non-finite support</i>). This ensures consistent results on all platforms, and increased + * performance where hardware FMA is available. + * * <p>References: * <ol> * <li> @@ -493,25 +551,40 @@ public final class DD /** * Returns a {@code DD} whose value is {@code (x * y)}. * + * <p>The result is the exact double-double representation of the product under the + * following conditions: + * + * <ul> + * <li>{@code x * y > 2^-969};</li> + * <li>neither argument multiplied by {@code 1 + 2^27} is infinite; and</li> + * <li>both arguments are finite normal numbers.</li> + * </ul> + * * <p>This method ignores special handling of non-normal numbers and intermediate - * overflow within the extended precision computation. - * This creates the following special cases: + * overflow within the extended precision computation. The low part will be computed + * using FMA if hardware support is available; otherwise splitting of 53-bit numbers by + * multiplication is used which can create intermediate overflow. + * + * <p>This creates the following special cases: * * <ul> - * <li>If either {@code |x|} or {@code |y|} multiplied by {@code 1 + 2^27} - * is infinite (intermediate overflow) then the low part is NaN.</li> - * <li>If {@code x * y} is infinite then the low part is NaN.</li> * <li>If {@code x} or {@code y} is infinite or NaN then the low part is NaN.</li> * <li>If {@code x * y} is sub-normal or zero then the low part is +/-0.0.</li> + * <li>If {@code x * y} is infinite then the low part is undefined.</li> + * <li>If {@code x * y} is finite and FMA support is available then the low part can be + * computed.</li> + * <li>If {@code x * y} is finite and FMA support is not available, and + * either {@code |x|} or {@code |y|} multiplied by {@code 1 + 2^27} + * is infinite (intermediate overflow) then the low part is NaN; + * otherwise the low part can be computed.</li> * </ul> * * <p>An invalid result can be identified using {@link #isFinite()}. * - * <p>Note: Ignoring special cases is a design choice for performance. The - * method is therefore not a drop-in replacement for - * {@code roundOff = Math.fma(x, y, -x * y)}. - * - * <p>The result is the exact double-double representation of the product. + * <p>Note: Ignoring special cases is a design choice for performance. Scaling of arguments + * by the caller to the supported range is recommended to avoid overflow and underflow + * cases if the low part is required to 53-bit precision. The result can be efficiently + * rescaled using {@link DD#scalb(int)}. * * @param x Factor. * @param y Factor. @@ -525,12 +598,11 @@ public final class DD * Returns a {@code DD} whose value is {@code (x * x)}. * * <p>This method is an optimisation of {@link #ofProduct(double, double) ofProduct(x, x)}. - * See that method for details of special cases. + * See that method for details of where the result is the exact double-double + * representation of the square and special cases. * * <p>An invalid result can be identified using {@link #isFinite()}. * - * <p>The result is the exact double-double representation of the square. - * * @param x Factor. * @return the square {@code x * x}. * @see #ofProduct(double, double) @@ -544,14 +616,17 @@ public final class DD * If {@code y = 0} the result is undefined. * * <p>This method ignores special handling of non-normal numbers and intermediate - * overflow within the extended precision computation. + * overflow within the extended precision computation. The low part will be computed + * using FMA if hardware support is available; otherwise splitting of 53-bit numbers by + * multiplication is used which can create intermediate overflow. * This creates the following special cases: * * <ul> - * <li>If either {@code |x / y|} or {@code |y|} multiplied by {@code 1 + 2^27} - * is infinite (intermediate overflow) then the low part is NaN.</li> - * <li>If {@code x / y} is infinite then the low part is NaN.</li> * <li>If {@code x} or {@code y} is infinite or NaN then the low part is NaN.</li> + * <li>If {@code x / y} is infinite then the low part is NaN.</li> + * <li>If FMA support is not available and either {@code |x / y|} or + * {@code |y|} multiplied by {@code 1 + 2^27} + * is infinite (intermediate overflow) then the low part is NaN.</li> * <li>If {@code x / y} is sub-normal or zero, excluding the previous cases, * then the low part is +/-0.0.</li> * </ul> @@ -570,7 +645,7 @@ public final class DD final double q0 = x / y; // remainder r = x - q0 * y final double p0 = q0 * y; - final double p1 = twoProductLow(q0, y, p0); + final double p1 = prodLow(q0, y, p0); final double r0 = x - p0; final double r1 = twoDiffLow(x, p0, r0) - p1; // correction term q1 = r0 / y @@ -950,19 +1025,7 @@ public final class DD * * <p>This method ignores special handling of non-normal numbers and intermediate * overflow within the extended precision computation. - * This creates the following special cases: - * - * <ul> - * <li>If {@code x * y} is sub-normal or zero then the low part is +/-0.0.</li> - * <li>If {@code x * y} is infinite then the low part is NaN.</li> - * <li>If {@code x} or {@code y} is infinite or NaN then the low part is NaN.</li> - * <li>If either {@code |x|} or {@code |y|} multiplied by {@code 1 + 2^27} - * is infinite (intermediate overflow) then the low part is NaN.</li> - * </ul> - * - * <p>Note: Ignoring special cases is a design choice for performance. The - * method is therefore not a drop-in replacement for - * {@code round_off = Math.fma(x, y, -x * y)}. + * See {@link DD#ofProduct(double, double)} for special cases. * * @param x First factor. * @param y Second factor. @@ -970,8 +1033,25 @@ public final class DD */ static DD twoProd(double x, double y) { final double xy = x * y; - // No checks for non-normal xy, or overflow during the split of the arguments - return new DD(xy, twoProductLow(x, y, xy)); + return new DD(xy, prodLow(x, y, xy)); + } + + /** + * Compute the low part of the double length number {@code (z,zz)} for the exact + * product of {@code x} and {@code y}. + * + * <p>The method will use FMA if hardware supported FMA has been detected; otherwise + * a software implementation using Dekker's mult12 algorithm. + * + * @param x First factor. + * @param y Second factor. + * @param xy Product of the factors (x * y). + * @return the low part of the square double length number + */ + private static double prodLow(double x, double y, double xy) { + return FMASupport.isHardwareFMA() ? + FMASupport.fma(x, y, -xy) : + twoProductLow(x, y, xy); } /** @@ -983,6 +1063,10 @@ public final class DD * <p>Warning: This method does not perform scaling in Dekker's split and large * finite numbers can create NaN results. * + * <p>Note: This method is a fallback for when hardware supported FMA has not + * been detected. It is exposed for use in {@link ExtendedPrecision} for the + * software implementation of a scaled two-product. + * * @param x First factor. * @param y Second factor. * @param xy Product of the factors (x * y). @@ -998,6 +1082,30 @@ public final class DD return twoProductLow(hx, lx, hy, ly, xy); } + /** + * Compute the low part of the double length number {@code (z,zz)} for the exact + * product of {@code x} and {@code y}. + * + * <p>The method will use FMA if hardware supported FMA has been detected; otherwise + * a software implementation using Dekker's mult12 algorithm. + * + * <p>This is a specialised method used in the power function where repeated + * multiplication by the same term is required. This term can be split once + * and reused. + * + * @param x First factor. + * @param y Second factor. + * @param hy High-part of second factor. + * @param ly Low-part of second factor. + * @param xy Product of the factors (x * y). + * @return the low part of the square double length number + */ + private static double prodLow(double x, double y, double hy, double ly, double xy) { + return FMASupport.isHardwareFMA() ? + FMASupport.fma(x, y, -xy) : + twoProductLow(x, hy, ly, xy); + } + /** * Compute the low part of the double length number {@code (z,zz)} for the exact * product of {@code x} and {@code y} using Dekker's mult12 algorithm. The standard @@ -1008,6 +1116,9 @@ public final class DD * multiplication by the same term is required. This term can be split once * and reused. * + * <p>Note: This method is a fallback for when hardware supported FMA has not + * been detected. + * * @param x First factor. * @param hy High-part of second factor. * @param ly Low-part of second factor. @@ -1063,8 +1174,26 @@ public final class DD */ static DD twoSquare(double x) { final double xx = x * x; - // No checks for non-normal xy, or overflow during the split of the arguments - return new DD(xx, twoSquareLow(x, xx)); + return new DD(xx, squareLow(x, xx)); + } + + /** + * Compute the low part of the double length number {@code (z,zz)} for the exact + * square of {@code x}. + * + * <p>The method will use FMA if hardware supported FMA has been detected; otherwise + * a software implementation using Dekker's mult12 algorithm. + * + * <p>Note: This method is exposed for use in the {@link Norm} class. + * + * @param x Factor. + * @param x2 Square of the factor (x * x). + * @return the low part of the square double length number + */ + static double squareLow(double x, double x2) { + return FMASupport.isHardwareFMA() ? + FMASupport.fma(x, x, -x2) : + twoSquareLow(x, x2); } /** @@ -1082,8 +1211,7 @@ public final class DD * @see #highPart(double) * @see #twoProductLow(double, double, double) */ - static double twoSquareLow(double x, double x2) { - // See productLowUnscaled + private static double twoSquareLow(double x, double x2) { final double hx = highPart(x); final double lx = x - hx; return twoSquareLow(hx, lx, x2); @@ -1476,7 +1604,7 @@ public final class DD // Dekker mul2 with yy=0 // (Alternative: Scale expansion (Schewchuk Fig 13)) final double hi = x * y; - final double lo = twoProductLow(x, y, hi); + final double lo = prodLow(x, y, hi); // Save 2 FLOPS compared to multiply(x, xx, y, 0). // This is reused in divide to save more FLOPS so worth the optimisation. return fastTwoSum(hi, lo + xx * y); @@ -1510,7 +1638,7 @@ public final class DD // Dekker mul2 // (Alternative: Scale expansion (Schewchuk Fig 13)) final double hi = x * y; - final double lo = twoProductLow(x, y, hi); + final double lo = prodLow(x, y, hi); return fastTwoSum(hi, lo + (x * yy + xx * y)); } @@ -1538,7 +1666,7 @@ public final class DD private static DD square(double x, double xx) { // Dekker mul2 final double hi = x * x; - final double lo = twoSquareLow(x, hi); + final double lo = squareLow(x, hi); return fastTwoSum(hi, lo + (2 * x * xx)); } @@ -1714,7 +1842,7 @@ public final class DD // Dekker's double precision sqrt2 algorithm. // See Dekker, 1971, pp 242. final double u = c * c; - final double uu = twoSquareLow(c, u); + final double uu = squareLow(c, u); final double cc = (x - u - uu + xx) * 0.5 / c; // Extended precision result: @@ -2033,7 +2161,8 @@ public final class DD // - if the current bit is 1 then multiply by x // In this scheme the factors to multiply by x can be pre-computed. - // Split b + // Split x even with FMA support. + // This cost is 4 FLOPs and reduces byte-size to achieve thresholds for inlining. final double xh = highPart(x); final double xl = x - xh; @@ -2055,7 +2184,7 @@ public final class DD for (int i = 32 - shift; i != 0; i--, bits <<= 1) { // Square the result: square(f0) -> (u, v) u = f0 * f0; - v = twoSquareLow(f0, u); + v = squareLow(f0, u); // Inline fastTwoSum(u, v + (2 * f0 * f1)) -> (f0, f1) v += 2 * f0 * f1; f0 = u + v; @@ -2063,7 +2192,7 @@ public final class DD if (bits < 0) { // Inline multiply(f0, x) -> (u, v) u = f0 * x; - v = twoProductLow(f0, xh, xl, u); + v = prodLow(f0, x, xh, xl, u); // Inline fastTwoSum(u, v + (f0 * xx + f1 * x)) -> (f0, f1) v += f0 * xx + f1 * x; f0 = u + v; @@ -2178,7 +2307,8 @@ public final class DD final long be = b - 1; final double b0 = x * 2; final double b1 = xx * 2; - // Split b + // Split b even with FMA support. + // This cost is 4 FLOPs and reduces byte-size to achieve thresholds for inlining. final double b0h = highPart(b0); final double b0l = b0 - b0h; @@ -2202,7 +2332,7 @@ public final class DD // Square the result: square(f0) -> (u, v) fe <<= 1; u = f0 * f0; - v = twoSquareLow(f0, u); + v = squareLow(f0, u); // Inline fastTwoSum(u, v + (2 * f0 * f1)) -> (f0, f1) v += 2 * f0 * f1; f0 = u + v; @@ -2222,12 +2352,12 @@ public final class DD fe += be; // Inline multiply(f0, b0) -> (u, v) u = f0 * b0; - v = twoProductLow(f0, b0h, b0l, u); + v = prodLow(f0, b0, b0h, b0l, u); // Inline fastTwoSum(u, v + (f0 * b1 + f1 * b0)) -> (f0, f1) v += f0 * b1 + f1 * b0; f0 = u + v; f1 = fastTwoSumLow(u, v, f0); - // Avoid rescale as x2 is in [1, 2) + // Avoid rescale as (b0, b1) is in [1, 2) } } diff --git a/commons-numbers-core/src/main/java/org/apache/commons/numbers/core/DDMath.java b/commons-numbers-core/src/main/java/org/apache/commons/numbers/core/DDMath.java index 3d0425d1..50ac4281 100644 --- a/commons-numbers-core/src/main/java/org/apache/commons/numbers/core/DDMath.java +++ b/commons-numbers-core/src/main/java/org/apache/commons/numbers/core/DDMath.java @@ -164,10 +164,21 @@ public final class DDMath { final double b0 = x * 2; final double b1 = xx * 2; // Split b - final double b0h = DD.highPart(b0); - final double b0l = b0 - b0h; - final double b1h = DD.highPart(b1); - final double b1l = b1 - b1h; + final double b0h; + final double b0l; + final double b1h; + final double b1l; + if (FMASupport.isHardwareFMA()) { + b0h = 0; + b0l = 0; + b1h = 0; + b1l = 0; + } else { + b0h = DD.highPart(b0); + b0l = b0 - b0h; + b1h = DD.highPart(b1); + b1l = b1 - b1h; + } // Initialise the result as x^1. Represented as 2^fe * f. long fe = be; @@ -188,21 +199,49 @@ public final class DDMath { for (int i = 32 - shift; i != 0; i--, bits <<= 1) { // Square the result fe <<= 1; - double a0h = DD.highPart(f0); - double a0l = f0 - a0h; - double a1h = DD.highPart(f1); - double a1l = f1 - a1h; - double a2h = DD.highPart(f2); - double a2l = f2 - a2h; - double p00 = f0 * f0; - double q00 = DD.twoSquareLow(a0h, a0l, p00); - double p01 = f0 * f1; - double q01 = DD.twoProductLow(a0h, a0l, a1h, a1l, p01); - final double p02 = f0 * f2; - final double q02 = DD.twoProductLow(a0h, a0l, a2h, a2l, p02); - double p11 = f1 * f1; - double q11 = DD.twoSquareLow(a1h, a1l, p11); - final double p12 = f1 * f2; + double p00; + double p01; + final double p02; + double p11; + final double p12; + double q00; + double q01; + final double q02; + double q11; + // The products are computed in each branch. Without FMA each product is + // followed by its round-off term so the split and two-product low part + // are close to the product they use. With the HotSpot optimizing + // JIT compiler (C2), benchmarks on x86 measured that computing common + // products before the branch was slower. Code order inside the non-FMA + // branch matches version 1.3. + // Note: C2 removes the branch not taken (due to the static final FMA flag). + if (FMASupport.isHardwareFMA()) { + p00 = f0 * f0; + p01 = f0 * f1; + p02 = f0 * f2; + p11 = f1 * f1; + p12 = f1 * f2; + q00 = FMASupport.fma(f0, f0, -p00); + q01 = FMASupport.fma(f0, f1, -p01); + q02 = FMASupport.fma(f0, f2, -p02); + q11 = FMASupport.fma(f1, f1, -p11); + } else { + final double a0h = DD.highPart(f0); + final double a0l = f0 - a0h; + final double a1h = DD.highPart(f1); + final double a1l = f1 - a1h; + final double a2h = DD.highPart(f2); + final double a2l = f2 - a2h; + p00 = f0 * f0; + q00 = DD.twoSquareLow(a0h, a0l, p00); + p01 = f0 * f1; + q01 = DD.twoProductLow(a0h, a0l, a1h, a1l, p01); + p02 = f0 * f2; + q02 = DD.twoProductLow(a0h, a0l, a2h, a2l, p02); + p11 = f1 * f1; + q11 = DD.twoSquareLow(a1h, a1l, p11); + p12 = f1 * f2; + } double s0 = p00; // Sum (2 * p01, q00) -> (s1, r2) Order(eps) double s1 = 2 * p01 + q00; @@ -236,23 +275,43 @@ public final class DDMath { if (bits < 0) { // Multiply by b fe += be; - a0h = DD.highPart(f0); - a0l = f0 - a0h; - a1h = DD.highPart(f1); - a1l = f1 - a1h; - a2h = DD.highPart(f2); - a2l = f2 - a2h; - p00 = f0 * b0; - q00 = DD.twoProductLow(a0h, a0l, b0h, b0l, p00); - p01 = f0 * b1; - q01 = DD.twoProductLow(a0h, a0l, b1h, b1l, p01); - final double p10 = f1 * b0; - final double q10 = DD.twoProductLow(a1h, a1l, b0h, b0l, p10); - p11 = f1 * b1; - q11 = DD.twoProductLow(a1h, a1l, b1h, b1l, p11); - final double p20 = f2 * b0; - final double q20 = DD.twoProductLow(a2h, a2l, b0h, b0l, p20); - final double p21 = f2 * b1; + final double p10; + final double p20; + final double p21; + final double q10; + final double q20; + // Products computed in each branch: see the square above. + if (FMASupport.isHardwareFMA()) { + p00 = f0 * b0; + p01 = f0 * b1; + p10 = f1 * b0; + p11 = f1 * b1; + p20 = f2 * b0; + p21 = f2 * b1; + q00 = FMASupport.fma(f0, b0, -p00); + q01 = FMASupport.fma(f0, b1, -p01); + q10 = FMASupport.fma(f1, b0, -p10); + q11 = FMASupport.fma(f1, b1, -p11); + q20 = FMASupport.fma(f2, b0, -p20); + } else { + final double a0h = DD.highPart(f0); + final double a0l = f0 - a0h; + final double a1h = DD.highPart(f1); + final double a1l = f1 - a1h; + final double a2h = DD.highPart(f2); + final double a2l = f2 - a2h; + p00 = f0 * b0; + q00 = DD.twoProductLow(a0h, a0l, b0h, b0l, p00); + p01 = f0 * b1; + q01 = DD.twoProductLow(a0h, a0l, b1h, b1l, p01); + p10 = f1 * b0; + q10 = DD.twoProductLow(a1h, a1l, b0h, b0l, p10); + p11 = f1 * b1; + q11 = DD.twoProductLow(a1h, a1l, b1h, b1l, p11); + p20 = f2 * b0; + q20 = DD.twoProductLow(a2h, a2l, b0h, b0l, p20); + p21 = f2 * b1; + } s0 = p00; // Sum (p01, p10, q00) -> (s1, r2, r3a) Order(eps) u = p01 + p10; @@ -274,7 +333,7 @@ public final class DDMath { f0 = norm3(s0, s1, s2, s3, m); f1 = m.x; f2 = m.xx; - // Avoid rescale as x2 is in [1, 2) + // Avoid rescale as (b0, b1) is in [1, 2) } } @@ -400,17 +459,32 @@ public final class DDMath { // s0 = p00 Order(1) // Sum (p10, q00) -> (s1, r1) Order(eps) // Sum (p20, q10, r1) -> (s2, s3) Order(eps^2) - final double a0h = DD.highPart(a0); - final double a0l = a0 - a0h; - final double a1h = DD.highPart(a1); - final double a1l = a1 - a1h; - final double b0h = DD.highPart(b); - final double b0l = b - b0h; - final double p00 = a0 * b; - final double q00 = DD.twoProductLow(a0h, a0l, b0h, b0l, p00); - final double p10 = a1 * b; - final double q10 = DD.twoProductLow(a1h, a1l, b0h, b0l, p10); - final double p20 = a2 * b; + final double p00; + final double p10; + final double p20; + final double q00; + final double q10; + // Products computed in each branch. Without FMA each product is followed by + // its round-off term (see computePowScaled). + if (FMASupport.isHardwareFMA()) { + p00 = a0 * b; + p10 = a1 * b; + p20 = a2 * b; + q00 = FMASupport.fma(a0, b, -p00); + q10 = FMASupport.fma(a1, b, -p10); + } else { + final double a0h = DD.highPart(a0); + final double a0l = a0 - a0h; + final double a1h = DD.highPart(a1); + final double a1l = a1 - a1h; + final double b0h = DD.highPart(b); + final double b0l = b - b0h; + p00 = a0 * b; + q00 = DD.twoProductLow(a0h, a0l, b0h, b0l, p00); + p10 = a1 * b; + q10 = DD.twoProductLow(a1h, a1l, b0h, b0l, p10); + p20 = a2 * b; + } // Sum (p10, q00) -> (s1, r1) Order(eps) final double s1 = p10 + q00; final double r1 = DD.twoSumLow(p10, q00, s1); diff --git a/commons-numbers-core/src/main/java/org/apache/commons/numbers/core/ExtendedPrecision.java b/commons-numbers-core/src/main/java/org/apache/commons/numbers/core/ExtendedPrecision.java index 4c47cd9d..621ff6ae 100644 --- a/commons-numbers-core/src/main/java/org/apache/commons/numbers/core/ExtendedPrecision.java +++ b/commons-numbers-core/src/main/java/org/apache/commons/numbers/core/ExtendedPrecision.java @@ -59,7 +59,7 @@ final class ExtendedPrecision { * containing the magnitude of the rounding error when converting the exact 106-bit * significand of the multiplication result to a 53-bit significand. * - * <p>The method is written to be functionally similar to using a fused multiply add (FMA) + * <p>The method is written to be functionally <em>similar</em> to using a fused multiply add (FMA) * operation to compute the low part, for example JDK 9's Math.fma function (note the sign * change in the input argument for the product): * <pre> @@ -73,12 +73,25 @@ final class ExtendedPrecision { * <p>Special cases: * * <ul> - * <li>If {@code x * y} is sub-normal or zero then the result is 0.0.</li> - * <li>If {@code x * y} is infinite or NaN then the result is NaN.</li> + * <li>If {@code x * y} is sub-normal or zero then the result is 0.0 + * (no low part in double precision).</li> + * <li>If {@code x * y} is infinite or NaN then the result is NaN (no usable low part). + * This case may be different from using Math.fma(x, y, -xy).</li> * </ul> * - * <p>This method delegates to {@link DD#twoProductLow(double, double, double)} but uses - * scaling to avoid intermediate overflow. + * <p>Note: Math.fma will represent the infinite product {@code x * y} as representable. + * When the argument {@code xy} is infinite FMA can compute a round-off different from + * this method, e.g. fma(2, MAX_VALUE, -2 * MAX_VALUE) is -infinity. This difference will + * occur only when the standard product is not finite. Attempts to extend precision for such + * cases are not supported. The caller is responsible for the product {@code x * y} and + * must ensure that use of the NaN round-off returned from this method is acceptable. + * + * <p>This method will use FMA if hardware supported FMA has been detected. Use of FMA + * occurs when the product {@code xy} has been validated as a finite normal number. + * + * <p>In the absence of FMA support, this method delegates to + * {@link DD#twoProductLow(double, double, double)} but uses scaling to avoid + * intermediate overflow. * * @param x First factor. * @param y Second factor. @@ -96,6 +109,31 @@ final class ExtendedPrecision { return xy - xy; } + // The result xy is finite and normal. + // Use FMA when available. + // This call is performed after the check for infinite numbers to + // ensure a consistent result with or without FMA. + if (FMASupport.isHardwareFMA()) { + return FMASupport.fma(x, y, -xy); + } + return scaledProductLow(x, y, xy); + } + + /** + * Compute the low part of the double length number {@code (z,zz)} for the exact + * product of {@code x} and {@code y}. + * + * <p>This method delegates to {@link DD#twoProductLow(double, double, double)} but uses + * scaling to avoid intermediate overflow. + * + * @param x First factor. + * @param y Second factor. + * @param xy Product of the factors (x * y). + * @return the low part of the product double length number + * @see DD#twoProductLow(double, double, double) + */ + // Visible for testing + static double scaledProductLow(double x, double y, double xy) { // The result xy is finite and normal. // Use Dekker's mul12 algorithm that splits the values into high and low parts. // Dekker's split using multiplication will overflow if the value is within 2^27 diff --git a/commons-numbers-core/src/main/java/org/apache/commons/numbers/core/FMASupport.java b/commons-numbers-core/src/main/java/org/apache/commons/numbers/core/FMASupport.java new file mode 100644 index 00000000..f80ef41c --- /dev/null +++ b/commons-numbers-core/src/main/java/org/apache/commons/numbers/core/FMASupport.java @@ -0,0 +1,298 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.numbers.core; + +import java.lang.invoke.MethodHandle; +import java.lang.invoke.MethodHandles; +import java.lang.invoke.MethodHandles.Lookup; +import java.lang.invoke.MethodType; +import java.lang.management.ManagementFactory; +import java.lang.management.PlatformManagedObject; + +/** + * Allows access to a hardward-supported Fused-Multiply-Add (FMA) operator. + * + * <p>This class is intentionally not part of the public API. + * + * <p>The class allows round-off components from the exact 106-bit product of two + * 53-bit {@code double} factors to be computed using FMA: + * + * <pre>{@code + * roundoff = Math.fma(x, y, -x * y) + * }</pre> + * + * <p>This method allows the roundoff to be computed in 2 FLOPs compared to + * the 16 FLOPs required when using Dekker's split method on the arguments. + * + * <p>All callers of this class must check if hardware FMA has been detected + * using the method {@link #isHardwareFMA()}. If {@code true} then callers + * can assume that the method {@link #fma(double, double, double)} will + * function as a FMA operator with support for infinite precision in the + * initial product {@code a * b} before addition of {@code c}. + * + * <p>Best efforts are made to detect and test FMA. Detection returns + * false if the Java HotSpot VM flag argument {@code UseFMA} is disabled + * with {@code -XX:-UseFMA}. This disables FMA application + * wide and is not limited to this class. + * + * <p>To disable FMA usage only within this class (not application wide) the + * system property {@code org.apache.commons.numbers.core.DD.fma} can be + * set to false before this class is loaded. + * + * @since 1.4 + */ +final class FMASupport { + /** Name of the Commons Numbers system property to enable/disable use of FMA in DD. */ + private static final String PROPERTY_DD_FMA_KEY = "org.apache.commons.numbers.core.DD.fma"; + /** Default for the Commons Numbers system property if it does not exist. */ + private static final boolean PROPERTY_DD_FMA_DEFAULT_VALUE = true; + /** + * Name of the HotSpotDiagnosticMXBean. + * See: https://docs.oracle.com/en/java/javase/17/docs/api/jdk.management/com/sun/management/HotSpotDiagnosticMXBean.html + */ + private static final String COM_SUN_MANAGEMENT_HOT_SPOT_DIAGNOSTIC_MX_BEAN = + "com.sun.management.HotSpotDiagnosticMXBean"; + /** + * Set to true if {@code java.lang.Math.fma} uses hardware FMA instructions, + * and can be invoked to generate results that avoid intermediate overflow + * in the product {@code a * b} before addition of {@code c}. + * + * <p>This flag is set once when the class is loaded. It is set to {@code true} + * only when the system property {@code org.apache.commons.numbers.core.DD.fma} + * is unset, or is set to true; the HotSpot VM option {@code UseFMA} is {@code true}; + * and the method {@code Math.fma} can be invoked and returns a fused-multiply-add + * result. + */ + private static final boolean HARDWARE_FMA; + /** + * Method to compute fused-multiply-add. + * <ul> + * <li>{@code java.lang.Math.fma} if Java 9, and use of hardware FMA is enabled; + * <li>otherwise a default implementation that raises an exception. + * </ul> + */ + private static final MethodHandle FUN; + + static { + // The checks are performed in order of speed to reduce the one-off + // initialisation cost for start-up cost sensitive users. + // The FMA feature can be disabled using a system property, otherwise + // an attempt is made to find and test Math.fma. + // Note: + // This uses the public lookup mechanism for static methods to find methods + // added to java.lang.Math since java 8 to make them available in java 8. + // For simplicity the lookup is always attempted rather than checking the + // java version from System.getProperty("java.version") which is prone + // to implementation specific property parsing errors. + final MethodHandle op = + isSystemPropertyEnabled(PROPERTY_DD_FMA_KEY, PROPERTY_DD_FMA_DEFAULT_VALUE) ? + lookupFMA(true, Math.class, "fma") : + null; + + // Check if the JVM flag for hardware FMA is enabled; then test the function. + // If the function is null (Math.fma cannot be found); no flag is set; or the + // method cannot be invoked to demonstrate a functional FMA method, this flag + // is false. If false then register a method that raises an exception. + // This exception will only be generated if this library attempts to use + // FMA before checking if it is available. It indicates an internal error + // that should be reported. + HARDWARE_FMA = op != null && + testFMA(op, readUseFMA(COM_SUN_MANAGEMENT_HOT_SPOT_DIAGNOSTIC_MX_BEAN)); + FUN = HARDWARE_FMA ? op : null; + } + + /** Private constructor. */ + private FMASupport() { + // intentionally empty. + } + + /** + * Test if the system property is enabled. Cases: + * <ul> + * <li>If the system property cannot be read (unknown status), return false + * <li>If the system property is null (no explicit property), return the default value + * <li>If the system property is not null, return the boolean value of the property + * </ul> + * + * @param name name of the system property + * @param defaultValue the value to use when the property is not set + * @return true if the property is enabled, or does not exist and the default value is true + */ + // package-private for testing + static boolean isSystemPropertyEnabled(String name, boolean defaultValue) { + final String property; + try { + property = System.getProperty(name); + } catch (RuntimeException ignored) { + // Either: SecurityException | NullPointerException | IllegalArgumentException + // The property cannot be read. + // It cannot be known if the property was set to true or false. + return false; + } + if (property == null) { + // Property was not set so use the default + return defaultValue; + } + return Boolean.parseBoolean(property); + } + + /** + * Lookup the fused-multiply-add (FMA) operator {@code a * b + c} from the specified class. + * + * @param publicLookup true for a public look, else a lookup with full bytecode support for the caller. + * @param cls class containing the method + * @param name name of the FMA method + * @return the method, or null + */ + // package-private for testing + static MethodHandle lookupFMA(boolean publicLookup, Class<?> cls, String name) { + try { + // The public lookup can find public methods in java.lang.Math. + // The full bytecode support lookup can find the fall back method in this class. + final Lookup lookup = publicLookup ? + MethodHandles.publicLookup() : + MethodHandles.lookup(); + return lookup.findStatic(cls, + name, + MethodType.methodType(double.class, double.class, double.class, double.class)); + } catch (NoSuchMethodException | IllegalAccessException ignored) { + return null; + } + } + + /** + * Test if the JVM uses hardware FMA instructions for {@code java.lang.Math.fma}. + * + * <p>Reads the HotSpot product flag {@code UseFMA} using the JDK management API + * {@code com.sun.management.HotSpotDiagnosticMXBean}. The flag is documented in + * the {@code java} tool reference: it enables hardware-based FMA intrinsics for + * {@code java.lang.Math.fma} and is on by default if the hardware supports FMA. + * Reflection is used to avoid a dependency on the {@code jdk.management} module. + * + * <p>Any failure (e.g. Java 8, a non-HotSpot JVM, or an unknown flag) returns false. + * + * @param className the name of the PlatformManagedObject + * @return true if {@code UseFMA} is set to true + */ + // package-private for testing + static boolean readUseFMA(String className) { + try { + // Equivalent to: + // import com.sun.management.HotSpotDiagnosticMXBean; + // + // HotSpotDiagnosticMXBean mxBean = + // ManagementFactory.getPlatformMXBean(HotSpotDiagnosticMXBean.class); + // String value = mxBean.getVMOption("UseFMA").getValue(); + final Class<? extends PlatformManagedObject> c = + Class.forName(className) + .asSubclass(PlatformManagedObject.class); + final Object mxBean = ManagementFactory.getPlatformMXBean(c); + final Object option = c.getMethod("getVMOption", String.class).invoke(mxBean, "UseFMA"); + final Object value = option.getClass().getMethod("getValue").invoke(option); + // Check the VM option UseFMA was true or false, e.g -XX:+UseFMA or -XX:-UseFMA. + // This allows FMA to be disabled in Commons Numbers core; it would also + // disable it throughout the JVM for any use of java.lang.Math.fma(a, b, c). + return Boolean.parseBoolean(String.valueOf(value)); + } catch (ReflectiveOperationException | RuntimeException | LinkageError ignored) { + return false; + } + } + + /** + * Test the implementation of fused-multiply-add {@code a * b + c}. + * + * <p>If the method is null (e.g. Java 8), or the use FMA flag is false, this will + * return false. + * + * <p>Otherwise the method is tested with arguments that would have intermediate + * overflow if computed without infinite precision support for the result + * {@code a * b} before addition of {@code c}. + * + * <p>It is assumed the invocation of the method may raise an + * {@link IllegalStateException} if it cannot be invoked. + * + * @param op Method implementation (or null). + * @param useFMA Flag to indicate hardware FMA has been detected + * @return True if the method can be called to generate the expected result + * @see #lookupFMA(boolean, Class, String) + * @see #readUseFMA(String) + */ + // package-private for testing + static boolean testFMA(MethodHandle op, boolean useFMA) { + if (!useFMA) { + return false; + } + try { + // Test a result that will overflow without FMA support + // Arguments must be exact: double,double,double -> double + return (double) op.invokeExact(Double.MAX_VALUE, 2.0, -Double.MAX_VALUE) == Double.MAX_VALUE; + } catch (Throwable e) { + // Method cannot be invoked + return false; + } + } + + /** + * Check if the the method {@link #fma(double, double, double)} has been detected to + * use hardware FMA instructions for {@code java.lang.Math.fma}. + * + * <p><strong>Warning</strong> + * + * <p>If this method returns {@code false} then the method {@link #fma(double, double, double)} + * is non-functional and will raise an exception. + * + * @return true if hardware FMA has been detected + */ + static boolean isHardwareFMA() { + return HARDWARE_FMA; + } + + /** + * Compute {@code a * b + c}. + * + * <p>This method uses a {@link MethodHandle} to call Java functions added since + * Java 8 to the {@link Math} class: + * <ul> + * <li>{@code java.lang.Math.fma} if Java 9 and hardware FMA has been detected; + * <li>otherwise raise an exception. + * </ul> + * + * <p>This method should not be called if {@link #isHardwareFMA()} returns {@code false}. + * + * @param a Argument. + * @param b Argument. + * @param c Argument. + * @return the result + * @throws IllegalStateException if hardware FMA is not in use (internal error) + * @see #isHardwareFMA() + */ + static double fma(double a, double b, double c) { + // FUN is a static final MethodHandle (or null). This should be inlined by the JIT + // at the first successful call to the underlying method. + try { + return (double) FUN.invokeExact(a, b, c); + } catch (Throwable cause) { + throw new IllegalStateException( + "Commons Numbers attempted to use FMA when hardware supported FMA is either " + + "not available; has been disabled using the HotSpot VM argument -XX:-UseFMA; " + + "or disabled before first use of DD using system property " + + PROPERTY_DD_FMA_KEY + + "=false. This is an internal error and should be reported as a bug.", cause + ); + } + } +} diff --git a/commons-numbers-core/src/main/java/org/apache/commons/numbers/core/Norm.java b/commons-numbers-core/src/main/java/org/apache/commons/numbers/core/Norm.java index 055d0bb4..7ec54c95 100644 --- a/commons-numbers-core/src/main/java/org/apache/commons/numbers/core/Norm.java +++ b/commons-numbers-core/src/main/java/org/apache/commons/numbers/core/Norm.java @@ -305,12 +305,12 @@ public enum Norm { // initialise sum and compensation using scaled x final double sx = xabs * scale; double sum = sx * sx; - double comp = DD.twoSquareLow(sx, sum); + double comp = DD.squareLow(sx, sum); // add scaled y final double sy = yabs * scale; final double py = sy * sy; - comp += DD.twoSquareLow(sy, py); + comp += DD.squareLow(sy, py); final double sumPy = sum + py; comp += DD.twoSumLow(sum, py, sumPy); sum = sumPy; @@ -365,12 +365,12 @@ public enum Norm { // initialise sum and compensation using scaled x final double sx = xabs * scale; double sum = sx * sx; - double comp = DD.twoSquareLow(sx, sum); + double comp = DD.squareLow(sx, sum); // add scaled y final double sy = yabs * scale; final double py = sy * sy; - comp += DD.twoSquareLow(sy, py); + comp += DD.squareLow(sy, py); final double sumPy = sum + py; comp += DD.twoSumLow(sum, py, sumPy); sum = sumPy; @@ -378,7 +378,7 @@ public enum Norm { // add scaled z final double sz = zabs * scale; final double pz = sz * sz; - comp += DD.twoSquareLow(sz, pz); + comp += DD.squareLow(sz, pz); final double sumPz = sum + pz; comp += DD.twoSumLow(sum, pz, sumPz); sum = sumPz; @@ -418,7 +418,7 @@ public enum Norm { // compute the product and product compensation final double p = sx * sx; - final double cp = DD.twoSquareLow(sx, p); + final double cp = DD.squareLow(sx, p); // compute the running sum and sum compensation final double s = s1 + p; @@ -433,7 +433,7 @@ public enum Norm { // compute the product and product compensation final double p = sx * sx; - final double cp = DD.twoSquareLow(sx, p); + final double cp = DD.squareLow(sx, p); // compute the running sum and sum compensation final double s = s3 + p; @@ -446,7 +446,7 @@ public enum Norm { // no scaling // compute the product and product compensation final double p = x * x; - final double cp = DD.twoSquareLow(x, p); + final double cp = DD.squareLow(x, p); // compute the running sum and sum compensation final double s = s2 + p; diff --git a/commons-numbers-core/src/test/java/org/apache/commons/numbers/core/DDExt.java b/commons-numbers-core/src/test/java/org/apache/commons/numbers/core/DDExt.java index 8c7205d2..0734ccb8 100644 --- a/commons-numbers-core/src/test/java/org/apache/commons/numbers/core/DDExt.java +++ b/commons-numbers-core/src/test/java/org/apache/commons/numbers/core/DDExt.java @@ -163,17 +163,25 @@ public final class DDExt { private static DD accurateMultiply(double x, double xx, double y) { // For working see accurateMultiply(double x, double xx, double y, double yy) - final double xh = DD.highPart(x); - final double xl = x - xh; - final double xxh = DD.highPart(xx); - final double xxl = xx - xxh; - final double yh = DD.highPart(y); - final double yl = y - yh; - final double p00 = x * y; - final double q00 = DD.twoProductLow(xh, xl, yh, yl, p00); final double p10 = xx * y; - final double q10 = DD.twoProductLow(xxh, xxl, yh, yl, p10); + double q00; + double q10; + if (FMASupport.isHardwareFMA()) { + // Direct use of fma: 4 FLOPs + q00 = FMASupport.fma(x, y, -p00); + q10 = FMASupport.fma(xx, y, -p10); + } else { + // FLOPs = 3*4 + 2*8 = 28 + final double xh = DD.highPart(x); + final double xl = x - xh; + final double xxh = DD.highPart(xx); + final double xxl = xx - xxh; + final double yh = DD.highPart(y); + final double yl = y - yh; + q00 = DD.twoProductLow(xh, xl, yh, yl, p00); + q10 = DD.twoProductLow(xxh, xxl, yh, yl, p10); + } // The code below collates the O(eps) terms with a round-off // so O(eps^2) terms can be added to it. @@ -234,21 +242,39 @@ public final class DDExt { // Sum (p01, p10, q00) -> (s1, r2) Order(eps) // Sum (p11, q01, q10, r2) -> s2 Order(eps^2) - final double xh = DD.highPart(x); - final double xl = x - xh; - final double xxh = DD.highPart(xx); - final double xxl = xx - xxh; - final double yh = DD.highPart(y); - final double yl = y - yh; - final double yyh = DD.highPart(yy); - final double yyl = yy - yyh; - - final double p00 = x * y; - final double q00 = DD.twoProductLow(xh, xl, yh, yl, p00); - final double p01 = x * yy; - final double q01 = DD.twoProductLow(xh, xl, yyh, yyl, p01); - final double p10 = xx * y; - final double q10 = DD.twoProductLow(xxh, xxl, yh, yl, p10); + final double p00; + final double p01; + final double p10; + double q00; + double q10; + double q01; + + if (FMASupport.isHardwareFMA()) { + // Direct use of FMA + p00 = x * y; + p01 = x * yy; + p10 = xx * y; + q00 = FMASupport.fma(x, y, -p00); + q01 = FMASupport.fma(x, yy, -p01); + q10 = FMASupport.fma(xx, y, -p10); + } else { + // Operation order from version 1.3 + final double xh = DD.highPart(x); + final double xl = x - xh; + final double xxh = DD.highPart(xx); + final double xxl = xx - xxh; + final double yh = DD.highPart(y); + final double yl = y - yh; + final double yyh = DD.highPart(yy); + final double yyl = yy - yyh; + + p00 = x * y; + q00 = DD.twoProductLow(xh, xl, yh, yl, p00); + p01 = x * yy; + q01 = DD.twoProductLow(xh, xl, yyh, yyl, p01); + p10 = xx * y; + q10 = DD.twoProductLow(xxh, xxl, yh, yl, p10); + } final double p11 = xx * yy; // Note: Directly adding same order terms (error = 2 eps^2): @@ -299,15 +325,28 @@ public final class DDExt { private static DD accurateSquare(double x, double xx) { // For working see accurateMultiply(double x, double xx, double y, double yy) - final double xh = DD.highPart(x); - final double xl = x - xh; - final double xxh = DD.highPart(xx); - final double xxl = xx - xxh; - - final double p00 = x * x; - final double q00 = DD.twoSquareLow(xh, xl, p00); - final double p01 = x * xx; - final double q01 = DD.twoProductLow(xh, xl, xxh, xxl, p01); + final double p00; + final double p01; + double q00; + double q01; + if (FMASupport.isHardwareFMA()) { + // Direct use of FMA + p00 = x * x; + p01 = x * xx; + q00 = FMASupport.fma(x, x, -p00); + q01 = FMASupport.fma(x, xx, -p01); + } else { + // Operation order from version 1.3 + final double xh = DD.highPart(x); + final double xl = x - xh; + final double xxh = DD.highPart(xx); + final double xxl = xx - xxh; + + p00 = x * x; + q00 = DD.twoSquareLow(xh, xl, p00); + p01 = x * xx; + q01 = DD.twoProductLow(xh, xl, xxh, xxl, p01); + } final double p11 = xx * xx; // The code below collates the O(eps) terms with a round-off diff --git a/commons-numbers-core/src/test/java/org/apache/commons/numbers/core/DDTest.java b/commons-numbers-core/src/test/java/org/apache/commons/numbers/core/DDTest.java index c2cd5d33..5110946c 100644 --- a/commons-numbers-core/src/test/java/org/apache/commons/numbers/core/DDTest.java +++ b/commons-numbers-core/src/test/java/org/apache/commons/numbers/core/DDTest.java @@ -739,11 +739,39 @@ class DDTest { assertProduct(Double.NaN, 1.0, Double.POSITIVE_INFINITY); assertProduct(Double.NaN, 1.0, Double.NEGATIVE_INFINITY); assertProduct(Double.NaN, 1.0, Double.NaN); - // x * y is infinite - assertProduct(Double.NaN, 0x1.0p511, 0x1.0p513); - // |x| or |y| > ~2^997 - assertProduct(Double.NaN, 0.5, 0x1.0p997); - assertProduct(Double.NaN, 0.5, Double.MAX_VALUE); + assertProduct(Double.NaN, Double.POSITIVE_INFINITY, -1.0); + assertProduct(Double.NaN, Double.NEGATIVE_INFINITY, -1.0); + assertProduct(Double.NaN, Double.NaN, -1.0); + // Here FMA creates a behavioural change when the product is infinite; + // or the product of either argument would overflow when multiplied by 1 + 2^27. + // Note: product low part is documented as undefined when the high part is not finite. + final double half = 0.5; + final double big = 0x1.0p997; + final double max = Double.MAX_VALUE; + if (FMASupport.isHardwareFMA()) { + // x * y is infinite + // FMA: [finite unrepresentable value above MAX_VALUE] - Infinity = -Infinity + assertProduct(Double.NEGATIVE_INFINITY, 0x1.0p511, 0x1.0p513); + assertProduct(Double.POSITIVE_INFINITY, -0x1.0p511, 0x1.0p513); + assertProduct(Double.POSITIVE_INFINITY, 0x1.0p511, -0x1.0p513); + assertProduct(Double.NEGATIVE_INFINITY, -0x1.0p511, -0x1.0p513); + // |x| or |y| > ~2^997 + // FMA can be used as there is no splitting by multiplication + assertProduct(0.0, half, big); + assertProduct(0.0, half, max); + // Compare to scaledProductLow (which uses scaling to prevent overflow during the split) + Assertions.assertEquals(0.0, ExtendedPrecision.scaledProductLow(half, big, half * big)); + // This creates a sign change not observed for FMA. + // The precision of the double-double is not affected. + Assertions.assertEquals(-0.0, ExtendedPrecision.scaledProductLow(half, max, half * max)); + } else { + // x * y is infinite + assertProduct(Double.NaN, 0x1.0p511, 0x1.0p513); + // |x| or |y| > ~2^997 + // Splitting the arguments creates infinite intermediate terms and generates NaN + assertProduct(Double.NaN, half, big); + assertProduct(Double.NaN, half, max); + } } private static void assertProduct(double expectedLo, double x, double y) { @@ -789,10 +817,15 @@ class DDTest { assertSquare(Double.NaN, Double.POSITIVE_INFINITY); assertSquare(Double.NaN, Double.NaN); // x * x is infinite - assertSquare(Double.NaN, 0x1.0p512); + // FMA has unlimited precision for the intermediate x*x + // FMA: [finite unrepresentable value above MAX_VALUE] - Infinity = -Infinity + // Std: Infinity - Infinity = NaN + // Note: product low part is documented as undefined when the high part is not finite. + final double expected = FMASupport.isHardwareFMA() ? Double.NEGATIVE_INFINITY : Double.NaN; + assertSquare(expected, 0x1.0p512); // |x| > ~2^997 - assertSquare(Double.NaN, 0x1.0p997); - assertSquare(Double.NaN, Double.MAX_VALUE); + assertSquare(expected, 0x1.0p997); + assertSquare(expected, Double.MAX_VALUE); } private static void assertSquare(double expectedLo, double x) { @@ -859,15 +892,17 @@ class DDTest { // x / y is infinite assertQuotient(Double.NaN, 0x1.0p511, 0x1.0p-513); assertQuotient(Double.NaN, 1, Double.MIN_VALUE); + // Here FMA creates a behavioural change when Dekker's split will overflow on |y| + final double expected = FMASupport.isHardwareFMA() ? 0.0 : Double.NaN; // |x / y| > ~2^997 - assertQuotient(Double.NaN, 0x1.0p997, 0.5); - assertQuotient(Double.NaN, Double.MAX_VALUE, 2); + assertQuotient(expected, 0x1.0p997, 0.5); + assertQuotient(expected, Double.MAX_VALUE, 2); // |y| > ~2^997 - assertQuotient(Double.NaN, 0.5, 0x1.0p997); - assertQuotient(Double.NaN, 2, Double.MAX_VALUE); + assertQuotient(expected, 0.5, 0x1.0p997); + assertQuotient(expected, 2, Double.MAX_VALUE); // x / y is sub-normal or zero with intermediate overflow - assertQuotient(Double.NaN, 0.5, Double.MAX_VALUE); - assertQuotient(Double.NaN, Double.MIN_NORMAL, 0x1.0p997); + assertQuotient(expected, 0.5, Double.MAX_VALUE); + assertQuotient(expected, Double.MIN_NORMAL, 0x1.0p997); } private static void assertQuotient(double expectedLo, double x, double y) { diff --git a/commons-numbers-core/src/test/java/org/apache/commons/numbers/core/ExtendedPrecisionTest.java b/commons-numbers-core/src/test/java/org/apache/commons/numbers/core/ExtendedPrecisionTest.java index 1c19e3bf..03a276eb 100644 --- a/commons-numbers-core/src/test/java/org/apache/commons/numbers/core/ExtendedPrecisionTest.java +++ b/commons-numbers-core/src/test/java/org/apache/commons/numbers/core/ExtendedPrecisionTest.java @@ -167,5 +167,13 @@ class ExtendedPrecisionTest { // Allowed ULP=0. This allows -0.0 and 0.0 to be equal. TestUtils.assertEquals(expected, ExtendedPrecision.productLow(x, y, x * y), 0, () -> TestUtils.prefix(msg) + "low(" + x + " * " + y + ")"); + + // Check the scaling method matches true FMA for finite products. + // This is done to ensure the behaviour is not effected if the method + // switches to FMA. On platforms without FMA the fallback computes the same result. + if (FMASupport.isHardwareFMA() && Double.isFinite(expected)) { + TestUtils.assertEquals(expected, ExtendedPrecision.scaledProductLow(x, y, x * y), 0, + () -> TestUtils.prefix(msg) + "FMA low(" + x + " * " + y + ")"); + } } } diff --git a/commons-numbers-core/src/test/java/org/apache/commons/numbers/core/FMASupportTest.java b/commons-numbers-core/src/test/java/org/apache/commons/numbers/core/FMASupportTest.java new file mode 100644 index 00000000..b9902282 --- /dev/null +++ b/commons-numbers-core/src/test/java/org/apache/commons/numbers/core/FMASupportTest.java @@ -0,0 +1,185 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.numbers.core; + +import java.lang.invoke.MethodHandle; +import java.math.BigDecimal; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +/** + * Test cases for the {@link FMASupport} class. + */ +class FMASupportTest { + /** Counter incremented when MethodHandles to methods in this class are invoked. */ + private static int methodInvoked; + + /** + * Test the FMA support can read system properties. + * This method exercises the logic paths during FMA detection. + */ + @Test + void testIsSystemPropertyEnabled() { + // Note: The SecurityManager is deprecated for removal from JDK 17. + // An explicit test for a SecurityException raised by System.getProperty + // due to a SecurityManager is not performed here. We test the same + // catch block using a null or empty property name. + // If any exception occurs reading the system properties the default value is ignored. + Assertions.assertFalse(FMASupport.isSystemPropertyEnabled(null, false)); + Assertions.assertFalse(FMASupport.isSystemPropertyEnabled(null, true)); + Assertions.assertFalse(FMASupport.isSystemPropertyEnabled("", false)); + Assertions.assertFalse(FMASupport.isSystemPropertyEnabled("", true)); + + final String key = "org.apache.commons.numbers.core.FMASupportTest"; + Assertions.assertNull(System.getProperty(key), + () -> "System property is set for test key: " + key); + + try { + // Any property that is missing uses the default + Assertions.assertFalse(FMASupport.isSystemPropertyEnabled(key, false)); + Assertions.assertTrue(FMASupport.isSystemPropertyEnabled(key, true)); + // Set the property and test the boolean value + System.setProperty(key, "something not case-insensitive true"); + Assertions.assertFalse(FMASupport.isSystemPropertyEnabled(key, false)); + Assertions.assertFalse(FMASupport.isSystemPropertyEnabled(key, true)); + // Empty + System.setProperty(key, ""); + Assertions.assertFalse(FMASupport.isSystemPropertyEnabled(key, false)); + Assertions.assertFalse(FMASupport.isSystemPropertyEnabled(key, true)); + // Explicit false + System.setProperty(key, "false"); + Assertions.assertFalse(FMASupport.isSystemPropertyEnabled(key, false)); + Assertions.assertFalse(FMASupport.isSystemPropertyEnabled(key, true)); + // true is case-insensitive + System.setProperty(key, "true"); + Assertions.assertTrue(FMASupport.isSystemPropertyEnabled(key, false)); + Assertions.assertTrue(FMASupport.isSystemPropertyEnabled(key, true)); + System.setProperty(key, "TrUe"); + Assertions.assertTrue(FMASupport.isSystemPropertyEnabled(key, false)); + Assertions.assertTrue(FMASupport.isSystemPropertyEnabled(key, true)); + } finally { + // Clean up + System.clearProperty(key); + } + } + + /** + * Test the FMA support can detect a functional FMA method. + * This method exercises the logic paths during FMA detection. + */ + @Test + void testTestFMA() { + // Test lookup is safe on methods that do not exist, e.g. Math.fma on Java 8 + Assertions.assertNull(lookupFMA("noSuchMethod")); + + // Test the check for the HotSpotDiagnosticMXBean is safe when exceptions are raised + Assertions.assertFalse(FMASupport.readUseFMA("MissingPlatformManagedObject")); + + // Null operators return false + Assertions.assertFalse(FMASupport.testFMA(null, false)); + Assertions.assertFalse(FMASupport.testFMA(null, true)); + + // Note: + // Methods should only be invoked if the UseFMA flag is true. + // Checking the invocations will only fail on race conditions with the static + // methodInvoked count if multiple instances of this test method are + // executed in the same JVM. + int count = methodInvoked; + + // An operator that raises an exception returns false even if the UseFMA flag is true + final MethodHandle bad = lookupFMA("badFMA"); + Assertions.assertFalse(FMASupport.testFMA(bad, false)); + Assertions.assertEquals(count, methodInvoked, "Method handle was invoked when useFMA is false"); + Assertions.assertFalse(FMASupport.testFMA(bad, true)); + Assertions.assertEquals(++count, methodInvoked, "Method handle was not invoked"); + + // An operator that cannot compute FMA returns false even if the UseFMA flag is true + final MethodHandle noFMA = lookupFMA("noFMA"); + Assertions.assertFalse(FMASupport.testFMA(noFMA, false)); + Assertions.assertEquals(count, methodInvoked, "Method handle was invoked when useFMA is false"); + Assertions.assertFalse(FMASupport.testFMA(noFMA, true)); + Assertions.assertEquals(++count, methodInvoked, "Method handle was not invoked"); + + // Provide an operator that will pass with finite arguments + final MethodHandle good = lookupFMA("goodFMA"); + Assertions.assertFalse(FMASupport.testFMA(good, false)); + Assertions.assertEquals(count, methodInvoked, "Method handle was invoked when useFMA is false"); + Assertions.assertTrue(FMASupport.testFMA(good, true)); + Assertions.assertEquals(++count, methodInvoked, "Method handle was not invoked with UseFMA"); + } + + /** + * Lookup the fused-multiply-add (FMA) operator {@code a * b + c} from this class. + * This allows methods with different behaviour to be passed to + * {@link FMASupport#testFMA(MethodHandle, java.util.function.BooleanSupplier)}. + * + * <p>This uses the lookup performed by FMASupport but requires a lookup with + * full bytecode support. This allows FMASupport to see the package-private methods + * in this class as they exist in the same package. + * + * @param name name of the FMA method + * @return the method, or null + */ + private static MethodHandle lookupFMA(String name) { + return FMASupport.lookupFMA(false, FMASupportTest.class, name); + } + + // Methods must be package-private for the FMASupport to look-up the method + + static double badFMA(double a, double b, double c) { + methodInvoked++; + throw new IllegalStateException(); + } + + static double noFMA(double a, double b, double c) { + methodInvoked++; + return a * b + c; + } + + static double goodFMA(double a, double b, double c) { + methodInvoked++; + return new BigDecimal(a).multiply(new BigDecimal(b)).add(new BigDecimal(c)).doubleValue(); + } + + /** + * Test the detected FMA method if it is available; otherwise check an exception is raised + * for trying to use the method when it has been marked an unavailable. + */ + @Test + void testHardwareFMA() { + final boolean hardware = FMASupport.isHardwareFMA(); + if (hardware) { + // Note: + // This result exploits round-to-even double arithmetic for the + // unrepresentable points between 0, MIN_VALUE, and 2 * MIN_VALUE: + // 1.5 * MIN_VALUE = 2 * MIN_VALUE after rounding + // 0.5 * MIN_VALUE underflows to zero; add another MIN_VALUE = 1.5 MIN_VALUE + final double a = Double.MIN_VALUE; + final double b = 0.5; + final double c = Double.MIN_VALUE; + Assertions.assertEquals(0, a * b, "Expected underflow"); + Assertions.assertEquals(2 * a, 1.5 * a, "Expected rounding"); + Assertions.assertEquals(c, a * b + c, "Expected 0 + c due to intermediate underflow"); + final double abc = FMASupport.fma(a, b, c); + Assertions.assertNotEquals(a * b + c, abc, "FMA should not match standard multiply-add"); + Assertions.assertEquals(2 * Double.MIN_VALUE, abc, "FMA=1.5*MIN_VALUE should round to 2*MIN_VALUE"); + } else { + // Should raise an exception if used when no hardware FMA was detected + Assertions.assertThrows(IllegalStateException.class, () -> FMASupport.fma(1, 2, 3)); + } + } +} diff --git a/commons-numbers-core/src/test/java/org/apache/commons/numbers/core/UserGuideTest.java b/commons-numbers-core/src/test/java/org/apache/commons/numbers/core/UserGuideTest.java index e072e2b8..9e664a1e 100644 --- a/commons-numbers-core/src/test/java/org/apache/commons/numbers/core/UserGuideTest.java +++ b/commons-numbers-core/src/test/java/org/apache/commons/numbers/core/UserGuideTest.java @@ -228,7 +228,7 @@ class UserGuideTest { double b = 4 * Math.pow(2, -1022); DD x = DD.of(a); DD y = DD.of(b); - Assertions.assertFalse(x.multiply(y).isFinite()); + Assertions.assertEquals(FMASupport.isHardwareFMA(), x.multiply(y).isFinite()); // Create fractional representation as [0.5, 1) * 2^b int[] xb = {0}; diff --git a/src/conf/checkstyle/checkstyle-suppressions.xml b/src/conf/checkstyle/checkstyle-suppressions.xml index a10817c4..6a3dbc89 100644 --- a/src/conf/checkstyle/checkstyle-suppressions.xml +++ b/src/conf/checkstyle/checkstyle-suppressions.xml @@ -46,6 +46,9 @@ <suppress checks="SummaryJavadoc" files=".*[/\\]combinatorics[/\\]FactorialDouble.java" /> <suppress checks="SummaryJavadoc" files="[\\/]examples[\\/].*" /> + <!-- Catch all documented throwables when using the public API to find and test FMA. --> + <suppress checks="IllegalCatch" files=".*[/\\]core[/\\]FMASupport\.java" /> + <!-- Selection --> <suppress checks="ParameterNumber" files=".*[/\\]arrays[/\\]QuickSelect.java" /> <suppress checks="ParameterNumber" files=".*[/\\]jmh[/\\]arrays[/\\]Partition.java" /> diff --git a/src/site/apt/userguide/index.apt b/src/site/apt/userguide/index.apt index b7738418..3f0b155e 100644 --- a/src/site/apt/userguide/index.apt +++ b/src/site/apt/userguide/index.apt @@ -37,6 +37,8 @@ The Apache Commons Numbers User Guide * {{{DD:_double-double}DD: double-double}} + * {{{FMA_Support}FMA Support}} + * {{{Field}Field}} * {{{Fraction}Fraction}} @@ -797,7 +799,7 @@ DD x = DD.of(a); DD y = DD.of(b); // Values too extreme for DD arithmetic! -x.multiply(y).isFinite() // false +x.multiply(y).isFinite() // false (without FMA support - see below) // Create fractional representation as [0.5, 1) * 2^b int[] xb = {0}; @@ -855,6 +857,10 @@ z.lo() // = Math.fma(x, y, -x * y) the round-off component. Splitting and computation of the round-off takes 16 FLOPS which is far slower than a hardware supported FMA operation. + From version 1.4 <<<Commons Numbers>>> can detect and use hardware-supported FMA + (see {{{FMA_Support}FMA Support}}). This can provide speed-ups for all operations + that use the product round-off. + ** Comparison to IEEE 754 quadruple A <<<DD>>> class has a 106-bit significand, 11-bit exponent and a sign bit. It is not an @@ -881,6 +887,66 @@ z.lo() // = Math.fma(x, y, -x * y) <<<double>>> arithmetic, or even to enable computations that have catastrophic error using <<<double>>> arithmetic. +* FMA Support + + The Java HotSpot Virtual Machine (VM) provides a public API to look-up VM options. From + Java 9 an option is provided to enable FMA intrinsic instructions + to be generated for calls to the method <<<Math.fma>>> on supported CPUs. + + On start-up the VM will set the VM option <<<UseFMA>>> to <<<true>>> if FMA is supported. + On platforms where hardware support is not available, or the VM argument <<<-XX:-UseFMA>>> is + explicitly used then a software implementation is used for <<<Math.fma>>>. + + From version 1.4, <<<Commons Numbers>>> core provides support for FMA. A check is performed + on first use of classes that use the round-off part of multiplications to increase precision. + This applies to the <<<DD>>>, <<<DDMath>>>, <<<Norm>>> and <<<Sum>>> classes; + <<<Sum>>> uses extended precision for the sum of products. + The check will attempt to find the <<<Math.fma>>> method (Java 9+). + If found, the option <<<UseFMA>>> is read, and if <<<true>>> the method is tested + to check it returns a fused multiply-add result. If successful then FMA + can provide a speed-up for classes computing extended precision products. If the + <<<Math.fma>>> method cannot be found (Java 8), the VM option cannot be read (not a HotSpot VM), + or is set to <<<false>>>, then the software implementation is used which matches the + behaviour of version 1.3. + + For performance reasons the look-up is only performed once, and cannot be + changed after the <<<Commons Numbers>>> classes using this feature have been loaded. + Look-up of hardware supported FMA has a small one-time start-up cost. The look-up + can be disabled by setting the system property <<<org.apache.commons.numbers.core.DD.fma>>> + to <<<false>>>. <<<Commons Numbers>>> will not attempt to detect FMA support and will use + the software implementation to compute product round-off. The property must be set before + first use, e.g. <<<-Dorg.apache.commons.numbers.core.DD.fma=false>>> on the command line. + + Explicit use of <<<-XX:-UseFMA>>> is not recommended as it will disable FMA application wide, + and will not remove the one-time start-up cost made by <<<Commons Numbers>>> to check the + FMA support. Use the system property <<<org.apache.commons.numbers.core.DD.fma>>>. + +** Behaviour using FMA + + The <<<Norm>>> and <<<Sum>>> classes use appropriate scaling of arguments to avoid overflow + or underflow when computing extended precision products. Behaviour + with FMA is a performance-only change. + + The <<<DD>>> class is an API for extended precision <<<double>>> arithmetic where the result + and intermediates do not approach over or underflow. For performance reasons no validation of + arguments is performed; arguments and results should be validated by the caller. + + Operations that involve splitting a double (multiply, divide) to compute + extended precision products are safe when the base 2 exponent is below 996 using the default + software implementation. Larger arguments and intermediate terms can generate overflow + and the result <<<DD>>> is not finite, even if the standard double product is finite, for + example \( 2^\{1022\} \times 2^\{-1022\} \). + + Use of FMA can extend the supported range of arguments for <<<DD>>> operations that compute + the double-double product of multiplications. When using FMA any product that is finite and + not sub-normal can have the round-off computed using FMA, expanding the supported domain. + Note that when the product is below \( 2^\{-969\} \) the round-off is sub-normal and accuracy + is lost, with or without FMA. + Applications should not rely on FMA support and should use scaling where appropriate to ensure + consistent behaviour when FMA is enabled or disabled. Explicitly setting the system property + <<<org.apache.commons.numbers.core.DD.fma>>> to <<<false>>> will ensure consistent behaviour + across all JVMs and hardware platforms. + Field The {{{../commons-numbers-field/index.html}commons-numbers-field}} module
