This is an automated email from the ASF dual-hosted git repository.

garydgregory pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/commons-lang.git

commit 0bafe758aabfc5742e6fbc02a9c908de06013bc9
Author: Gary Gregory <[email protected]>
AuthorDate: Sun Nov 15 08:46:14 2026 -0500

    Fix premature overflow in Fraction double conversion
    
    Compute the signed numerator in long before narrowing, allowing
    representable Integer.MIN_VALUE numerators while rejecting true
    overflow.
    
    Add 100,000 boundary cases covering denominators 1 through 10,000,
    both double and decimal-string conversion, and preserved exception
    causes.
    Update Javadoc and release notes.
    
    Assisted-By: OpenAI Codex
---
 src/changes/changes.xml                            |  1 +
 .../org/apache/commons/lang3/math/Fraction.java    |  9 +++--
 .../apache/commons/lang3/math/FractionTest.java    | 45 ++++++++++++++++++++++
 3 files changed, 51 insertions(+), 4 deletions(-)

diff --git a/src/changes/changes.xml b/src/changes/changes.xml
index a58d94097..58e512187 100644
--- a/src/changes/changes.xml
+++ b/src/changes/changes.xml
@@ -61,6 +61,7 @@ The <action> type attribute can be add,update,fix,remove.
     <action                   type="fix" dev="ggregory" due-to="Gary 
Gregory">Expand Fraction.pow tests for negative bases, extreme exponents, and 
zero raised to zero.</action>
     <action                   type="fix" dev="ggregory" due-to="Gary 
Gregory">Parameterize Fraction factory and unary-operation tests while 
preserving expected representations, invalid inputs, and reduction identity 
checks.</action>
     <action                   type="fix" dev="ggregory" due-to="Gary 
Gregory">Improve Fraction double-conversion test diagnostics and verify 
preserved ArithmeticException causes for all six unrepresentable-string 
regression cases.</action>
+    <action                   type="fix" dev="ggregory" due-to="Gary 
Gregory">Fix premature overflow in Fraction.getFraction(double) and 
decimal-string parsing for representable Integer.MIN_VALUE numerators, with 
boundary tests for every denominator from 1 through 10,000.</action>
     <!-- ADD -->
     <!-- UPDATE -->
   </release>
diff --git a/src/main/java/org/apache/commons/lang3/math/Fraction.java 
b/src/main/java/org/apache/commons/lang3/math/Fraction.java
index b47522760..9b82b93fa 100644
--- a/src/main/java/org/apache/commons/lang3/math/Fraction.java
+++ b/src/main/java/org/apache/commons/lang3/math/Fraction.java
@@ -118,6 +118,7 @@ private static void checkDenominator(final int denominator) 
{
 
     /**
      * Gets a {@link Fraction} instance from a {@code double} value.
+     *
      * <p>
      * This method uses the <a 
href="https://web.archive.org/web/20210516065058/http%3A//archives.math.utk.edu/articles/atuyl/confrac/";>
 continued fraction
      * algorithm</a>, computing a maximum of 25 convergents and bounding the 
denominator by 10,000.
@@ -126,6 +127,7 @@ private static void checkDenominator(final int denominator) 
{
      * @param value The double value to convert
      * @return A new fraction instance that is close to the value
      * @throws ArithmeticException Thrown if {@code |value| &gt; 
Integer.MAX_VALUE} or {@code value = NaN}.
+     * @throws ArithmeticException Thrown if the calculated numerator cannot 
be represented as an {@code int}.
      * @throws ArithmeticException Thrown if the calculated denominator is 
{@code zero}.
      * @throws ArithmeticException Thrown if the algorithm does not converge.
      */
@@ -174,10 +176,9 @@ public static Fraction getFraction(double value) {
         if (i == 25) {
             throw new ArithmeticException("Unable to convert double to 
fraction");
         }
-        // wholeNumber can be up to Integer.MAX_VALUE while denom0 > 1 for any 
non-integer value,
-        // so the int product overflows for values near the limit; check it 
instead of wrapping silently.
-        final int numerator = Math.addExact(numer0, mulAndCheck(wholeNumber, 
denom0));
-        return getReducedFraction(numerator * sign, denom0);
+        // Use long arithmetic and apply the sign before narrowing so that 
Integer.MIN_VALUE remains representable.
+        final long numerator = (numer0 + (long) wholeNumber * denom0) * sign;
+        return getReducedFraction(Math.toIntExact(numerator), denom0);
     }
 
     /**
diff --git a/src/test/java/org/apache/commons/lang3/math/FractionTest.java 
b/src/test/java/org/apache/commons/lang3/math/FractionTest.java
index baeb5e0a4..22aa1ebba 100644
--- a/src/test/java/org/apache/commons/lang3/math/FractionTest.java
+++ b/src/test/java/org/apache/commons/lang3/math/FractionTest.java
@@ -32,6 +32,7 @@
 import java.util.List;
 import java.util.function.Supplier;
 import java.util.stream.IntStream;
+import java.util.stream.LongStream;
 import java.util.stream.Stream;
 
 import org.apache.commons.lang3.AbstractLangTest;
@@ -98,6 +99,16 @@ private static void assertReducedResult(final BigInteger 
numerator, final BigInt
         }
     }
 
+    private static Stream<Arguments> factoryDoubleBoundaryValues() {
+        final long[] numerators = {
+            (long) Integer.MIN_VALUE - 2, (long) Integer.MIN_VALUE - 1, 
Integer.MIN_VALUE, Integer.MIN_VALUE + 1, Integer.MIN_VALUE + 2,
+            Integer.MAX_VALUE - 2, Integer.MAX_VALUE - 1, Integer.MAX_VALUE, 
(long) Integer.MAX_VALUE + 1, (long) Integer.MAX_VALUE + 2
+        };
+        // Exercise every supported denominator, including all reduced 
minimum-value numerators and both neighboring range limits.
+        return LongStream.of(numerators).boxed()
+                .flatMap(numerator -> IntStream.rangeClosed(1, 
10000).mapToObj(denominator -> Arguments.of(numerator, denominator)));
+    }
+
     private static Stream<Arguments> factoryDoubleValues() {
         return Stream.of(
             Arguments.of(0.0d, 0, 1),
@@ -620,6 +631,32 @@ void testFactory_double(final double value, final int 
expectedNumerator, final i
         assertEquals(expectedDenominator, result.getDenominator());
     }
 
+    @ParameterizedTest(name = "[{index}] getFraction({0}/{1}) via double and 
string")
+    @MethodSource("factoryDoubleBoundaryValues")
+    void testFactory_doubleAndStringBoundaryValues(final long numerator, final 
int denominator) {
+        final double value = (double) numerator / denominator;
+        final String text = Double.toString(value);
+        final BigInteger bigNumerator = BigInteger.valueOf(numerator);
+        final BigInteger bigDenominator = BigInteger.valueOf(denominator);
+        final BigInteger gcd = bigNumerator.gcd(bigDenominator);
+        final BigInteger expectedNumerator = bigNumerator.divide(gcd);
+        final BigInteger expectedDenominator = bigDenominator.divide(gcd);
+        final BigInteger minValue = BigInteger.valueOf(Integer.MIN_VALUE);
+        final BigInteger maxValue = BigInteger.valueOf(Integer.MAX_VALUE);
+        // The double factory also imposes a documented magnitude limit on the 
input itself.
+        if (Math.abs(value) > Integer.MAX_VALUE || 
expectedNumerator.compareTo(minValue) < 0 || 
expectedNumerator.compareTo(maxValue) > 0) {
+            assertThrows(ArithmeticException.class, () -> 
Fraction.getFraction(value));
+            final NumberFormatException exception = 
assertThrows(NumberFormatException.class, () -> Fraction.getFraction(text));
+            assertInstanceOf(ArithmeticException.class, exception.getCause());
+        } else {
+            final Fraction result = Fraction.getFraction(value);
+            assertEquals(expectedNumerator.intValueExact(), 
result.getNumerator());
+            assertEquals(expectedDenominator.intValueExact(), 
result.getDenominator());
+            assertEquals(value, result.doubleValue());
+            assertEquals(result, Fraction.getFraction(text));
+        }
+    }
+
     @ParameterizedTest(name = "[{index}] getFraction({0}) throws")
     @ValueSource(doubles = {Double.NaN, Double.POSITIVE_INFINITY, 
Double.NEGATIVE_INFINITY, (double) Integer.MAX_VALUE + 1, 2147483646.5d, 
1073741824.5d})
     void testFactory_doubleInvalid(final double value) {
@@ -627,6 +664,14 @@ void testFactory_doubleInvalid(final double value) {
         assertThrows(ArithmeticException.class, () -> 
Fraction.getFraction(value));
     }
 
+    @ParameterizedTest(name = "[{index}] getFraction(-2147483648/{0})")
+    @ValueSource(ints = {3, 5, 7, 9, 11, 9999})
+    void testFactory_doubleIntegerMinValue(final int denominator) {
+        final Fraction result = Fraction.getFraction((double) 
Integer.MIN_VALUE / denominator);
+        assertEquals(Integer.MIN_VALUE, result.getNumerator());
+        assertEquals(denominator, result.getDenominator());
+    }
+
     @Test
     void testFactory_doubleRoundTrip() {
         Fraction f;

Reply via email to