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 8ff7ad37f3979e9fcee07741f15a6abee2b9be3f Author: Gary Gregory <[email protected]> AuthorDate: Sun Nov 15 08:33:32 2026 -0500 Fix premature overflow in Fraction.pow for negative powers Reduce Integer.MIN_VALUE numerators before inversion so representable results succeed, preserving existing successful unreduced reciprocals. Add exhaustive tests for representable affected cases with exponents below -1, overflow boundaries, extreme exponents, and special powers. Clarify the Javadoc and update release notes. Assisted-By: OpenAI Codex --- .../org/apache/commons/lang3/math/Fraction.java | 13 ++- .../apache/commons/lang3/math/FractionTest.java | 112 +++++++++++++++++++++ 2 files changed, 121 insertions(+), 4 deletions(-) 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 30f3bfac1..b47522760 100644 --- a/src/main/java/org/apache/commons/lang3/math/Fraction.java +++ b/src/main/java/org/apache/commons/lang3/math/Fraction.java @@ -853,14 +853,17 @@ public Fraction negate() { /** * Gets a fraction that is raised to the passed in power. + * * <p> - * The returned fraction is in reduced form. + * For powers other than {@code 1} and {@code -1}, the returned fraction is in reduced form. A power of {@code 1} returns this instance unchanged. + * A power of {@code -1} returns the unreduced reciprocal unless reduction is necessary to avoid overflow. * </p> * * @param power The power to raise the fraction to * @return {@code this} if the power is one, {@link #ONE} if the power is zero (even if the fraction equals ZERO) or a new fraction instance raised to the * appropriate power - * @throws ArithmeticException Thrown if the resulting numerator or denominator exceeds {@code Integer.MAX_VALUE}. + * @throws ArithmeticException Thrown if this fraction is zero and the power is negative. + * @throws ArithmeticException Thrown if the resulting numerator or positive denominator cannot be represented as an {@code int}. */ public Fraction pow(final int power) { if (power == 1) { @@ -870,10 +873,12 @@ public Fraction pow(final int power) { return ONE; } if (power < 0) { + // Reduce a minimum-value numerator before inversion, while preserving other unreduced reciprocals. + final Fraction inverse = (numerator == Integer.MIN_VALUE ? reduce() : this).invert(); if (power == Integer.MIN_VALUE) { // MIN_VALUE can't be negated. - return invert().pow(2).pow(-(power / 2)); + return inverse.pow(2).pow(-(power / 2)); } - return invert().pow(-power); + return inverse.pow(-power); } final Fraction f = multiplyBy(this); if (power % 2 == 0) { // if even... 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 bc60db8fd..baeb5e0a4 100644 --- a/src/test/java/org/apache/commons/lang3/math/FractionTest.java +++ b/src/test/java/org/apache/commons/lang3/math/FractionTest.java @@ -31,6 +31,7 @@ import java.util.ArrayList; import java.util.List; import java.util.function.Supplier; +import java.util.stream.IntStream; import java.util.stream.Stream; import org.apache.commons.lang3.AbstractLangTest; @@ -65,6 +66,21 @@ private static Stream<Arguments> arithmeticBoundaryValues() { .flatMap(left -> fractions.stream().map(right -> Arguments.of(left, right))); } + private static void assertPowResult(final Fraction fraction, final int power) { + if (fraction.getNumerator() == 0 && power < 0) { + assertThrows(ArithmeticException.class, () -> fraction.pow(power)); + return; + } + // The providers bound these exponents to keep the exact expected values small. + final BigInteger numerator = BigInteger.valueOf(fraction.getNumerator()).pow(Math.abs(power)); + final BigInteger denominator = BigInteger.valueOf(fraction.getDenominator()).pow(Math.abs(power)); + if (power < 0) { + assertReducedResult(denominator.multiply(BigInteger.valueOf(numerator.signum())), numerator.abs(), () -> fraction.pow(power)); + } else { + assertReducedResult(numerator, denominator, () -> fraction.pow(power)); + } + } + private static void assertReducedResult(final BigInteger numerator, final BigInteger denominator, final Supplier<Fraction> operation) { // Use arbitrary-precision arithmetic as an independent oracle for the reduced result and its range. final BigInteger gcd = numerator.gcd(denominator); @@ -93,6 +109,39 @@ private static Stream<Arguments> factoryDoubleValues() { Arguments.of(1.0d / 10001d, 0, 1)); } + private static Stream<Fraction> powBaseValues() { + final int[] numerators = { + Integer.MIN_VALUE, Integer.MIN_VALUE + 1, -1073741824, -46341, -2, -1, 0, 1, 2, 46341, 1073741824, + Integer.MAX_VALUE - 1, Integer.MAX_VALUE + }; + final int[] denominators = {1, 2, 3, 4, 46341, 536870912, 1073741824, 1610612736, Integer.MAX_VALUE - 1, Integer.MAX_VALUE}; + return IntStream.of(numerators).boxed() + .flatMap(numerator -> IntStream.of(denominators).mapToObj(denominator -> Fraction.getFraction(numerator, denominator))); + } + + private static Stream<Arguments> powBoundaryValues() { + return powBaseValues().flatMap(fraction -> IntStream.rangeClosed(-32, 32) + .filter(power -> power < -1 || power > 1) + .mapToObj(power -> Arguments.of(fraction, power))); + } + + private static Stream<Arguments> powExtremeValues() { + return powBaseValues().flatMap(fraction -> IntStream.of(Integer.MIN_VALUE, Integer.MIN_VALUE + 1, Integer.MAX_VALUE - 1, Integer.MAX_VALUE) + .mapToObj(power -> Arguments.of(fraction, power))); + } + + private static Stream<Arguments> powIntegerMinValueValues() { + // After cancellation, the reciprocal denominator is 2^(31 - trailingZeros(denominator)). + // Raising it to a power of at least two fits a positive int only if the original denominator is a multiple of 2^16. + // The reciprocal numerator has smaller magnitude, so fitting the denominator is sufficient. + // Enumerate every such denominator and every representable power, plus the first overflowing power. + return IntStream.range(1, 1 << 15).boxed().flatMap(factor -> { + final int denominator = factor << 16; + final int maxPower = 30 / (31 - Integer.numberOfTrailingZeros(denominator)); + return IntStream.rangeClosed(2, maxPower + 1).mapToObj(power -> Arguments.of(denominator, -power)); + }); + } + @ParameterizedTest(name = "[{index}] abs({0}/{1})") @CsvSource({ "50, 75, 50, 75", @@ -1031,6 +1080,56 @@ void testPow() { assertThrows(ArithmeticException.class, () -> Fraction.getFraction(65536, 1).pow(2)); } + @ParameterizedTest(name = "[{index}] ({0})^{1}") + @MethodSource("powBoundaryValues") + void testPowBoundaryValues(final Fraction fraction, final int power) { + assertPowResult(fraction, power); + } + + @ParameterizedTest(name = "[{index}] ({0})^{1}") + @MethodSource("powExtremeValues") + void testPowExtremeValues(final Fraction fraction, final int power) { + if (fraction.getNumerator() == 0) { + if (power < 0) { + assertThrows(ArithmeticException.class, () -> fraction.pow(power)); + } else { + assertSame(Fraction.ZERO, fraction.pow(power)); + } + } else if (Math.abs((long) fraction.getNumerator()) == fraction.getDenominator()) { + final Fraction result = fraction.pow(power); + assertEquals(fraction.getNumerator() < 0 && (power & 1) != 0 ? -1 : 1, result.getNumerator()); + assertEquals(1, result.getDenominator()); + } else { + // In lowest terms, a numerator or denominator of magnitude at least two cannot fit at these exponents. + assertThrows(ArithmeticException.class, () -> fraction.pow(power)); + } + } + + @ParameterizedTest(name = "[{index}] (-2147483648/{0})^{1}") + @MethodSource("powIntegerMinValueValues") + void testPowIntegerMinValue(final int denominator, final int power) { + assertPowResult(Fraction.getFraction(Integer.MIN_VALUE, denominator), power); + } + + @ParameterizedTest(name = "[{index}] (-2147483648/{0})^{1}") + @CsvSource({ + "2, -1, -1, 1073741824", + "1073741824, -1, -1, 2", + "1610612736, -1, -3, 4", + "1073741824, -2, 1, 4", + "1073741824, -3, -1, 8", + "1073741824, -30, 1, 1073741824", + "1610612736, -2, 9, 16", + "1610612736, -3, -27, 64", + "65536, -2, 1, 1073741824", + "536870912, -15, -1, 1073741824" + }) + void testPowIntegerMinValueRegression(final int denominator, final int power, final int expectedNumerator, final int expectedDenominator) { + final Fraction result = Fraction.getFraction(Integer.MIN_VALUE, denominator).pow(power); + assertEquals(expectedNumerator, result.getNumerator()); + assertEquals(expectedDenominator, result.getDenominator()); + } + @ParameterizedTest(name = "[{index}] ({0}/{1})^{2}") @CsvSource({ "-2, 3, 2, 4, 9", @@ -1059,6 +1158,19 @@ void testPowNegativeOne(final int power, final int expectedNumerator) { assertEquals(1, result.getDenominator()); } + @ParameterizedTest(name = "[{index}] special powers of {0}") + @MethodSource("powBaseValues") + void testPowSpecialPowers(final Fraction fraction) { + assertSame(Fraction.ONE, fraction.pow(0)); + assertSame(fraction, fraction.pow(1)); + if (fraction.getNumerator() == Integer.MIN_VALUE || fraction.getNumerator() == 0) { + assertPowResult(fraction, -1); + } else { + // Preserve the existing unreduced reciprocal whenever inversion already fits. + assertEquals(fraction.invert(), fraction.pow(-1)); + } + } + @Test void testPowZeroToZero() { assertSame(Fraction.ONE, Fraction.ZERO.pow(0));
