From 355677f3a6c2899e6930e33f6e9a384911ffcc0f Mon Sep 17 00:00:00 2001 From: Lee Rhodes Date: Sun, 22 Nov 2026 12:07:52 -0800 Subject: [PATCH] Util.invPow2: limit exp to 0..1022, the range it computes exactly At exp = 1023 the exponent field is 0, so the method returned 0.0 instead of the subnormal 2^-1023. All callers use exp < 64. Co-Authored-By: Claude Opus 5.5 --- src/main/java/org/apache/datasketches/common/Util.java | 9 ++++++--- .../java/org/apache/datasketches/common/UtilTest.java | 7 +++++++ 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/src/main/java/org/apache/datasketches/common/Util.java b/src/main/java/org/apache/datasketches/common/Util.java index 0d867bc44..6551d2867 100644 --- a/src/main/java/org/apache/datasketches/common/Util.java +++ b/src/main/java/org/apache/datasketches/common/Util.java @@ -485,12 +485,15 @@ public static long ceilingMultiple2expK(final long n, final int k) { /** * Computes the inverse integer power of 2: 1/(2^exp) = 2^(-exp). - * @param exp a positive value between 0 and 1023 inclusive + * The result is built directly from its IEEE 754 bits, so it is exact. + * @param exp a value between 0 and 1022 inclusive. 2^(-1022) is the smallest normal double; + * 2^(-1023) is subnormal and cannot be built this way. * @return the inverse integer power of 2: 1/(2^exp) = 2^(-exp) + * @throws SketchesArgumentException if exp is negative or greater than 1022 */ public static double invPow2(final int exp) { - if ((exp | (1024 - exp - 1)) < 0) { - throw new SketchesArgumentException("exp cannot be negative or greater than 1023: " + exp); + if ((exp | (1022 - exp)) < 0) { + throw new SketchesArgumentException("exp cannot be negative or greater than 1022: " + exp); } return Double.longBitsToDouble((1023L - exp) << 52); } diff --git a/src/test/java/org/apache/datasketches/common/UtilTest.java b/src/test/java/org/apache/datasketches/common/UtilTest.java index 950ef7565..8499ce5d0 100644 --- a/src/test/java/org/apache/datasketches/common/UtilTest.java +++ b/src/test/java/org/apache/datasketches/common/UtilTest.java @@ -205,7 +205,14 @@ public void checkInvPow2() { Assert.assertEquals(invPow2(1), 0.5); Assert.assertEquals(invPow2(0), 1.0); try {invPow2(-1); failIAE(); } catch (final SketchesArgumentException e) {} + try {invPow2(1023); failIAE(); } catch (final SketchesArgumentException e) {} try {invPow2(1024); failIAE(); } catch (final SketchesArgumentException e) {} + try {invPow2(Integer.MAX_VALUE); failIAE(); } catch (final SketchesArgumentException e) {} + Assert.assertEquals(invPow2(1022), Double.MIN_NORMAL); + for (int exp = 0; exp <= 1022; exp++) { //exact over the whole range + Assert.assertEquals(Double.doubleToRawLongBits(invPow2(exp)), + Double.doubleToRawLongBits(Math.scalb(1.0, -exp)), "exp: " + exp); + } try {invPow2(Integer.MIN_VALUE); failIAE(); } catch (final SketchesArgumentException e) {} }