You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@commons.apache.org by ah...@apache.org on 2020/04/07 12:43:32 UTC

[commons-numbers] branch master updated (01a6c77 -> 2332235)

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

aherbert pushed a change to branch master
in repository https://gitbox.apache.org/repos/asf/commons-numbers.git.


    from 01a6c77  updating README files to refer to latest release
     new db98ddf  BigFraction: Removed validation of arguments in internal function
     new 077baed  BigFraction/Fraction: clean-up javadoc
     new 7a94e4a  Fraction/BigFraction to use same method order:
     new 4e596fc  Fraction/BigFraction to validate input double in factory constructors
     new 8b6ba20  Fraction/BigFraction to use consistent javadoc.
     new d7b2895  ContinuedFraction: reverse names of coefficients a and b
     new 0963555  Fraction/BigFraction: Increase consistency using isZero().
     new 071aa58  Avoid reassigning parameters.
     new 2332235  PMD: Allow certain violations in Fraction/BigFraction

The 9 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails.  The revisions
listed as "add" were already present in the repository and have only
been added to this reference.


Summary of changes:
 .../commons/numbers/fraction/BigFraction.java      | 1405 +++++++++-----------
 .../numbers/fraction/ContinuedFraction.java        |   24 +-
 .../apache/commons/numbers/fraction/Fraction.java  |  653 +++++----
 .../numbers/fraction/FractionException.java        |    2 +
 .../commons/numbers/fraction/BigFractionTest.java  |   14 +-
 .../numbers/fraction/ContinuedFractionTest.java    |   21 +-
 .../commons/numbers/fraction/FractionTest.java     |   12 +
 .../commons/numbers/gamma/RegularizedBeta.java     |    4 +-
 .../commons/numbers/gamma/RegularizedGamma.java    |    4 +-
 src/main/resources/pmd/pmd-ruleset.xml             |   10 +-
 10 files changed, 1085 insertions(+), 1064 deletions(-)


[commons-numbers] 07/09: Fraction/BigFraction: Increase consistency using isZero().

Posted by ah...@apache.org.
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 0963555f3791a90c953ec916dde82bd7a74399f7
Author: aherbert <ah...@apache.org>
AuthorDate: Tue Apr 7 13:24:08 2020 +0100

    Fraction/BigFraction: Increase consistency using isZero().
    
    Use internal method isZero() for increase consistency.
    
    Consistent divide by zero error message.
    
    Consistent formatting in identical methods.
---
 .../commons/numbers/fraction/BigFraction.java      | 64 +++++++++++++---------
 .../apache/commons/numbers/fraction/Fraction.java  | 50 ++++++++++-------
 .../numbers/fraction/FractionException.java        |  2 +
 .../commons/numbers/fraction/BigFractionTest.java  |  2 +-
 4 files changed, 69 insertions(+), 49 deletions(-)

diff --git a/commons-numbers-fraction/src/main/java/org/apache/commons/numbers/fraction/BigFraction.java b/commons-numbers-fraction/src/main/java/org/apache/commons/numbers/fraction/BigFraction.java
index 617f386..9cbc43d 100644
--- a/commons-numbers-fraction/src/main/java/org/apache/commons/numbers/fraction/BigFraction.java
+++ b/commons-numbers-fraction/src/main/java/org/apache/commons/numbers/fraction/BigFraction.java
@@ -638,12 +638,12 @@ public final class BigFraction
      * @return {@code this + value}.
      */
     public BigFraction add(final BigInteger value) {
-        if (numerator.signum() == 0) {
-            return of(value);
-        }
         if (value.signum() == 0) {
             return this;
         }
+        if (isZero()) {
+            return of(value);
+        }
 
         return new BigFraction(numerator.add(denominator.multiply(value)), denominator);
     }
@@ -657,10 +657,10 @@ public final class BigFraction
      */
     @Override
     public BigFraction add(final BigFraction value) {
-        if (value.numerator.signum() == 0) {
+        if (value.isZero()) {
             return this;
         }
-        if (numerator.signum() == 0) {
+        if (isZero()) {
             return value;
         }
 
@@ -715,7 +715,7 @@ public final class BigFraction
         if (value.signum() == 0) {
             return this;
         }
-        if (numerator.signum() == 0) {
+        if (isZero()) {
             return of(value.negate());
         }
 
@@ -731,10 +731,10 @@ public final class BigFraction
      */
     @Override
     public BigFraction subtract(final BigFraction value) {
-        if (value.numerator.signum() == 0) {
+        if (value.isZero()) {
             return this;
         }
-        if (numerator.signum() == 0) {
+        if (isZero()) {
             return value.negate();
         }
 
@@ -759,7 +759,7 @@ public final class BigFraction
      */
     @Override
     public BigFraction multiply(final int value) {
-        if (value == 0 || numerator.signum() == 0) {
+        if (value == 0 || isZero()) {
             return ZERO;
         }
 
@@ -774,7 +774,7 @@ public final class BigFraction
      * @return {@code this * value}.
      */
     public BigFraction multiply(final long value) {
-        if (value == 0 || numerator.signum() == 0) {
+        if (value == 0 || isZero()) {
             return ZERO;
         }
 
@@ -789,7 +789,7 @@ public final class BigFraction
      * @return {@code this * value}.
      */
     public BigFraction multiply(final BigInteger value) {
-        if (numerator.signum() == 0 || value.signum() == 0) {
+        if (value.signum() == 0 || isZero()) {
             return ZERO;
         }
         return new BigFraction(value.multiply(numerator), denominator);
@@ -804,8 +804,7 @@ public final class BigFraction
      */
     @Override
     public BigFraction multiply(final BigFraction value) {
-        if (numerator.signum() == 0 ||
-            value.numerator.signum() == 0) {
+        if (value.isZero() || isZero()) {
             return ZERO;
         }
         return new BigFraction(numerator.multiply(value.numerator),
@@ -846,10 +845,10 @@ public final class BigFraction
      */
     public BigFraction divide(final BigInteger value) {
         if (value.signum() == 0) {
-            throw new FractionException(FractionException.ERROR_ZERO_DENOMINATOR);
+            throw new FractionException(FractionException.ERROR_DIVIDE_BY_ZERO);
         }
-        if (numerator.signum() == 0) {
-            return ZERO;
+        if (isZero()) {
+            return this;
         }
         return new BigFraction(numerator, denominator.multiply(value));
     }
@@ -864,11 +863,11 @@ public final class BigFraction
      */
     @Override
     public BigFraction divide(final BigFraction value) {
-        if (value.numerator.signum() == 0) {
-            throw new FractionException(FractionException.ERROR_ZERO_DENOMINATOR);
+        if (value.isZero()) {
+            throw new FractionException(FractionException.ERROR_DIVIDE_BY_ZERO);
         }
-        if (numerator.signum() == 0) {
-            return ZERO;
+        if (isZero()) {
+            return this;
         }
         return multiply(value.reciprocal());
     }
@@ -885,14 +884,16 @@ public final class BigFraction
         if (exponent == 0) {
             return ONE;
         }
-        if (numerator.signum() == 0) {
+        if (isZero()) {
             return this;
         }
 
         if (exponent < 0) {
-            return new BigFraction(denominator.pow(-exponent), numerator.pow(-exponent));
+            return new BigFraction(denominator.pow(-exponent),
+                                   numerator.pow(-exponent));
         }
-        return new BigFraction(numerator.pow(exponent), denominator.pow(exponent));
+        return new BigFraction(numerator.pow(exponent),
+                               denominator.pow(exponent));
     }
 
     /**
@@ -906,7 +907,7 @@ public final class BigFraction
         if (exponent == 0) {
             return ONE;
         }
-        if (numerator.signum() == 0) {
+        if (isZero()) {
             return this;
         }
 
@@ -929,7 +930,7 @@ public final class BigFraction
         if (exponent.signum() == 0) {
             return ONE;
         }
-        if (numerator.signum() == 0) {
+        if (isZero()) {
             return this;
         }
 
@@ -970,7 +971,7 @@ public final class BigFraction
         final String str;
         if (BigInteger.ONE.equals(denominator)) {
             str = numerator.toString();
-        } else if (BigInteger.ZERO.equals(numerator)) {
+        } else if (isZero()) {
             str = "0";
         } else {
             str = numerator + " / " + denominator;
@@ -1062,7 +1063,7 @@ public final class BigFraction
         //assert significandLength >= 1;
         //assert significandLength <= 63 - exponentLength;
 
-        if (numerator.signum() == 0) {
+        if (isZero()) {
             return 0L;
         }
 
@@ -1225,4 +1226,13 @@ public final class BigFraction
 
         return result;
     }
+
+    /**
+     * Returns true if this fraction is zero.
+     *
+     * @return true if zero
+     */
+    private boolean isZero() {
+        return numerator.signum() == 0;
+    }
 }
diff --git a/commons-numbers-fraction/src/main/java/org/apache/commons/numbers/fraction/Fraction.java b/commons-numbers-fraction/src/main/java/org/apache/commons/numbers/fraction/Fraction.java
index 389dabe..f8fa171 100644
--- a/commons-numbers-fraction/src/main/java/org/apache/commons/numbers/fraction/Fraction.java
+++ b/commons-numbers-fraction/src/main/java/org/apache/commons/numbers/fraction/Fraction.java
@@ -56,7 +56,6 @@ public final class Fraction
     /** The denominator of this fraction reduced to lowest terms. */
     private final int denominator;
 
-
     /**
      * Private constructor: Instances are created using factory methods.
      *
@@ -67,7 +66,7 @@ public final class Fraction
      */
     private Fraction(int num, int den) {
         if (den == 0) {
-            throw new ArithmeticException("division by zero");
+            throw new FractionException(FractionException.ERROR_ZERO_DENOMINATOR);
         }
 
         if (num == den) {
@@ -371,7 +370,7 @@ public final class Fraction
         if ((numerator > 0 && denominator > 0) ||
             (numerator < 0 && denominator < 0)) {
             return 1;
-        } else if (numerator == 0) {
+        } else if (isZero()) {
             return 0;
         } else {
             return -1;
@@ -507,15 +506,14 @@ public final class Fraction
      * cannot be represented in an {@code int}.
      */
     private Fraction addSub(Fraction value, boolean isAdd) {
+        if (value.isZero()) {
+            return this;
+        }
         // Zero is identity for addition.
-        if (numerator == 0) {
+        if (isZero()) {
             return isAdd ? value : value.negate();
         }
 
-        if (value.numerator == 0) {
-            return this;
-        }
-
         /*
          * Let the two fractions be u/u' and v/v', and d1 = gcd(u', v').
          * First, compute t, defined as:
@@ -560,6 +558,9 @@ public final class Fraction
      */
     @Override
     public Fraction multiply(final int value) {
+        if (value == 0 || isZero()) {
+            return ZERO;
+        }
         return multiply(of(value));
     }
 
@@ -574,8 +575,7 @@ public final class Fraction
      */
     @Override
     public Fraction multiply(Fraction value) {
-        if (numerator == 0 ||
-            value.numerator == 0) {
+        if (value.isZero() || isZero()) {
             return ZERO;
         }
 
@@ -613,11 +613,9 @@ public final class Fraction
      */
     @Override
     public Fraction divide(Fraction value) {
-        if (value.numerator == 0) {
-            throw new FractionException("the fraction to divide by must not be zero: {0}/{1}",
-                                        value.numerator, value.denominator);
+        if (value.isZero()) {
+            throw new FractionException(FractionException.ERROR_DIVIDE_BY_ZERO);
         }
-
         return multiply(value.reciprocal());
     }
 
@@ -633,15 +631,16 @@ public final class Fraction
         if (exponent == 0) {
             return ONE;
         }
-        if (numerator == 0) {
+        if (isZero()) {
             return this;
         }
 
-        return exponent < 0 ?
-            new Fraction(ArithmeticUtils.pow(denominator, -exponent),
-                         ArithmeticUtils.pow(numerator, -exponent)) :
-            new Fraction(ArithmeticUtils.pow(numerator, exponent),
-                         ArithmeticUtils.pow(denominator, exponent));
+        if (exponent < 0) {
+            return new Fraction(ArithmeticUtils.pow(denominator, -exponent),
+                                ArithmeticUtils.pow(numerator,   -exponent));
+        }
+        return new Fraction(ArithmeticUtils.pow(numerator,   exponent),
+                            ArithmeticUtils.pow(denominator, exponent));
     }
 
     /**
@@ -660,7 +659,7 @@ public final class Fraction
         final String str;
         if (denominator == 1) {
             str = Integer.toString(numerator);
-        } else if (numerator == 0) {
+        } else if (isZero()) {
             str = "0";
         } else {
             str = numerator + " / " + denominator;
@@ -710,4 +709,13 @@ public final class Fraction
     public int hashCode() {
         return 37 * (37 * 17 + numerator) + denominator;
     }
+
+    /**
+     * Returns true if this fraction is zero.
+     *
+     * @return true if zero
+     */
+    private boolean isZero() {
+        return numerator == 0;
+    }
 }
diff --git a/commons-numbers-fraction/src/main/java/org/apache/commons/numbers/fraction/FractionException.java b/commons-numbers-fraction/src/main/java/org/apache/commons/numbers/fraction/FractionException.java
index 4ce0a69..39c1a8b 100644
--- a/commons-numbers-fraction/src/main/java/org/apache/commons/numbers/fraction/FractionException.java
+++ b/commons-numbers-fraction/src/main/java/org/apache/commons/numbers/fraction/FractionException.java
@@ -31,6 +31,8 @@ class FractionException extends ArithmeticException {
     static final String ERROR_NEGATION_OVERFLOW = "Overflow in fraction {0}/{1}, cannot negate";
     /** Error message for zero-valued denominator. */
     static final String ERROR_ZERO_DENOMINATOR = "Denominator must be different from 0";
+    /** Error message for divide by zero. */
+    static final String ERROR_DIVIDE_BY_ZERO = "The value to divide by must not be zero";
 
     /** Serializable version identifier. */
     private static final long serialVersionUID = 201701191744L;
diff --git a/commons-numbers-fraction/src/test/java/org/apache/commons/numbers/fraction/BigFractionTest.java b/commons-numbers-fraction/src/test/java/org/apache/commons/numbers/fraction/BigFractionTest.java
index d2da883..8bbcc14 100644
--- a/commons-numbers-fraction/src/test/java/org/apache/commons/numbers/fraction/BigFractionTest.java
+++ b/commons-numbers-fraction/src/test/java/org/apache/commons/numbers/fraction/BigFractionTest.java
@@ -513,7 +513,7 @@ public class BigFractionTest {
         f1 = BigFraction.of(0, 5);
         f2 = BigFraction.of(2, 7);
         BigFraction f = f1.divide(f2);
-        Assertions.assertSame(BigFraction.ZERO, f);
+        Assertions.assertEquals(BigFraction.ZERO, f);
 
         final BigFraction f3 = BigFraction.of(Integer.MIN_VALUE, 1);
         Assertions.assertThrows(NullPointerException.class,


[commons-numbers] 06/09: ContinuedFraction: reverse names of coefficients a and b

Posted by ah...@apache.org.
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 d7b2895dc48b6804ef010188906209346edb6a1b
Author: aherbert <ah...@apache.org>
AuthorDate: Tue Apr 7 12:43:50 2020 +0100

    ContinuedFraction: reverse names of coefficients a and b
    
    a = numerator
    b = denominator
    
    This matches the original reference paper for the implemented method
    (Thompson & Barnett, 1986).
---
 .../numbers/fraction/ContinuedFraction.java        | 24 ++++++++++++----------
 .../numbers/fraction/ContinuedFractionTest.java    | 21 +++++++++----------
 .../commons/numbers/gamma/RegularizedBeta.java     |  4 ++--
 .../commons/numbers/gamma/RegularizedGamma.java    |  4 ++--
 4 files changed, 27 insertions(+), 26 deletions(-)

diff --git a/commons-numbers-fraction/src/main/java/org/apache/commons/numbers/fraction/ContinuedFraction.java b/commons-numbers-fraction/src/main/java/org/apache/commons/numbers/fraction/ContinuedFraction.java
index 4801318..a01fee8 100644
--- a/commons-numbers-fraction/src/main/java/org/apache/commons/numbers/fraction/ContinuedFraction.java
+++ b/commons-numbers-fraction/src/main/java/org/apache/commons/numbers/fraction/ContinuedFraction.java
@@ -21,19 +21,21 @@ import org.apache.commons.numbers.core.Precision;
 /**
  * Provides a generic means to evaluate
  * <a href="https://mathworld.wolfram.com/ContinuedFraction.html">continued fractions</a>.
- * Subclasses must provide the {@link #getA(int,double) a} and {@link #getB(int,double) b}
- * coefficients to evaluate the continued fraction.
  *
- * <p>The fraction uses the following form for the {@code a} and {@code b} coefficients:
+ * <p>The continued fraction uses the following form for the numerator ({@code a}) and
+ * denominator ({@code b}) coefficients:
  * <pre>
- *              b1
- * a0 + ------------------
- *      a1 +      b2
+ *              a1
+ * b0 + ------------------
+ *      b1 +      a2
  *           -------------
- *           a2 +    b3
+ *           b2 +    a3
  *                --------
- *                a3 + ...
+ *                b3 + ...
  * </pre>
+ *
+ * <p>Subclasses must provide the {@link #getA(int,double) a} and {@link #getB(int,double) b}
+ * coefficients to evaluate the continued fraction.
  */
 public abstract class ContinuedFraction {
     /**
@@ -106,7 +108,7 @@ public abstract class ContinuedFraction {
      * before the expected convergence is achieved.
      */
     public double evaluate(double x, double epsilon, int maxIterations) {
-        double hPrev = updateIfCloseToZero(getA(0, x));
+        double hPrev = updateIfCloseToZero(getB(0, x));
 
         int n = 1;
         double dPrev = 0.0;
@@ -117,8 +119,8 @@ public abstract class ContinuedFraction {
             final double a = getA(n, x);
             final double b = getB(n, x);
 
-            double dN = updateIfCloseToZero(a + b * dPrev);
-            final double cN = updateIfCloseToZero(a + b / cPrev);
+            double dN = updateIfCloseToZero(b + a * dPrev);
+            final double cN = updateIfCloseToZero(b + a / cPrev);
 
             dN = 1 / dN;
             final double deltaN = cN * dN;
diff --git a/commons-numbers-fraction/src/test/java/org/apache/commons/numbers/fraction/ContinuedFractionTest.java b/commons-numbers-fraction/src/test/java/org/apache/commons/numbers/fraction/ContinuedFractionTest.java
index ebb03ae..6760894 100644
--- a/commons-numbers-fraction/src/test/java/org/apache/commons/numbers/fraction/ContinuedFractionTest.java
+++ b/commons-numbers-fraction/src/test/java/org/apache/commons/numbers/fraction/ContinuedFractionTest.java
@@ -20,7 +20,6 @@ import java.util.Locale;
 import org.junit.jupiter.api.Assertions;
 import org.junit.jupiter.api.Test;
 
-
 /**
  * Tests for {@link ContinuedFraction}.
  */
@@ -60,6 +59,11 @@ public class ContinuedFractionTest {
         ContinuedFraction cf = new ContinuedFraction() {
             @Override
             public double getA(int n, double x) {
+                return n <= 3 ? 1 : 0;
+            }
+
+            @Override
+            public double getB(int n, double x) {
                 switch (n) {
                     case 0: return 4;
                     case 1: return 2;
@@ -68,11 +72,6 @@ public class ContinuedFractionTest {
                     default: return 1;
                 }
             }
-
-            @Override
-            public double getB(int n, double x) {
-                return n <= 3 ? 1 : 0;
-            }
         };
 
         final double eps = 1e-8;
@@ -107,12 +106,12 @@ public class ContinuedFractionTest {
         ContinuedFraction cf = new ContinuedFraction() {
             @Override
             public double getA(int n, double x) {
-                return n == 0 ? 1 : Double.NaN;
+                return 1;
             }
 
             @Override
             public double getB(int n, double x) {
-                return 1;
+                return n == 0 ? 1 : Double.NaN;
             }
         };
 
@@ -125,16 +124,16 @@ public class ContinuedFractionTest {
     @Test
     public void testInfThrows() throws Exception {
         // Create an infinity during the iteration:
-        // b / cPrev  => b_1 / a_0 => Double.MAX_VALUE / 0.5
+        // a / cPrev  => a_1 / b_0 => Double.MAX_VALUE / 0.5
         ContinuedFraction cf = new ContinuedFraction() {
             @Override
             public double getA(int n, double x) {
-                return 0.5;
+                return n == 0 ? 1 : Double.MAX_VALUE;
             }
 
             @Override
             public double getB(int n, double x) {
-                return n == 0 ? 1 : Double.MAX_VALUE;
+                return 0.5;
             }
         };
 
diff --git a/commons-numbers-gamma/src/main/java/org/apache/commons/numbers/gamma/RegularizedBeta.java b/commons-numbers-gamma/src/main/java/org/apache/commons/numbers/gamma/RegularizedBeta.java
index 2a4d4fa..d4c1c59 100644
--- a/commons-numbers-gamma/src/main/java/org/apache/commons/numbers/gamma/RegularizedBeta.java
+++ b/commons-numbers-gamma/src/main/java/org/apache/commons/numbers/gamma/RegularizedBeta.java
@@ -99,7 +99,7 @@ public final class RegularizedBeta {
             final ContinuedFraction fraction = new ContinuedFraction() {
                 /** {@inheritDoc} */
                 @Override
-                protected double getB(int n, double x) {
+                protected double getA(int n, double x) {
                     if (n % 2 == 0) { // even
                         final double m = n / 2d;
                         return (m * (b - m) * x) /
@@ -113,7 +113,7 @@ public final class RegularizedBeta {
 
                 /** {@inheritDoc} */
                 @Override
-                protected double getA(int n, double x) {
+                protected double getB(int n, double x) {
                     return 1;
                 }
             };
diff --git a/commons-numbers-gamma/src/main/java/org/apache/commons/numbers/gamma/RegularizedGamma.java b/commons-numbers-gamma/src/main/java/org/apache/commons/numbers/gamma/RegularizedGamma.java
index 448c8ea..f607fb9 100644
--- a/commons-numbers-gamma/src/main/java/org/apache/commons/numbers/gamma/RegularizedGamma.java
+++ b/commons-numbers-gamma/src/main/java/org/apache/commons/numbers/gamma/RegularizedGamma.java
@@ -192,13 +192,13 @@ public final class RegularizedGamma {
                         /** {@inheritDoc} */
                         @Override
                         protected double getA(int n, double x) {
-                            return ((2 * n) + 1) - a + x;
+                            return n * (a - n);
                         }
 
                         /** {@inheritDoc} */
                         @Override
                         protected double getB(int n, double x) {
-                            return n * (a - n);
+                            return ((2 * n) + 1) - a + x;
                         }
                     };
 


[commons-numbers] 08/09: Avoid reassigning parameters.

Posted by ah...@apache.org.
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 071aa588ba37907241ae684a0e34c014789450ec
Author: aherbert <ah...@apache.org>
AuthorDate: Tue Apr 7 13:33:23 2020 +0100

    Avoid reassigning parameters.
---
 .../commons/numbers/fraction/BigFraction.java      | 11 +++++------
 .../apache/commons/numbers/fraction/Fraction.java  | 22 ++++++++++++++--------
 2 files changed, 19 insertions(+), 14 deletions(-)

diff --git a/commons-numbers-fraction/src/main/java/org/apache/commons/numbers/fraction/BigFraction.java b/commons-numbers-fraction/src/main/java/org/apache/commons/numbers/fraction/BigFraction.java
index 9cbc43d..60f2c06 100644
--- a/commons-numbers-fraction/src/main/java/org/apache/commons/numbers/fraction/BigFraction.java
+++ b/commons-numbers-fraction/src/main/java/org/apache/commons/numbers/fraction/BigFraction.java
@@ -71,13 +71,12 @@ public final class BigFraction
         // reduce numerator and denominator by greatest common denominator
         final BigInteger gcd = num.gcd(den);
         if (BigInteger.ONE.compareTo(gcd) < 0) {
-            num = num.divide(gcd);
-            den = den.divide(gcd);
+            numerator = num.divide(gcd);
+            denominator = den.divide(gcd);
+        } else {
+            numerator = num;
+            denominator = den;
         }
-
-        // store the values in the final fields
-        numerator = num;
-        denominator = den;
     }
 
     /**
diff --git a/commons-numbers-fraction/src/main/java/org/apache/commons/numbers/fraction/Fraction.java b/commons-numbers-fraction/src/main/java/org/apache/commons/numbers/fraction/Fraction.java
index f8fa171..a2acc21 100644
--- a/commons-numbers-fraction/src/main/java/org/apache/commons/numbers/fraction/Fraction.java
+++ b/commons-numbers-fraction/src/main/java/org/apache/commons/numbers/fraction/Fraction.java
@@ -73,23 +73,29 @@ public final class Fraction
             numerator = 1;
             denominator = 1;
         } else {
+            // Reduce numerator (p) and denominator (q) by greatest common divisor.
+            int p;
+            int q;
+
             // If num and den are both 2^-31, or if one is 0 and the other is 2^-31,
             // the calculation of the gcd below will fail. Ensure that this does not
             // happen by dividing both by 2 in case both are even.
             if (((num | den) & 1) == 0) {
-                num >>= 1;
-                den >>= 1;
+                p = num >> 1;
+                q = den >> 1;
+            } else {
+                p = num;
+                q = den;
             }
 
-            // Reduce numerator and denominator by greatest common divisor.
-            final int d = ArithmeticUtils.gcd(num, den);
+            final int d = ArithmeticUtils.gcd(p, q);
             if (d > 1) {
-                num /= d;
-                den /= d;
+                p /= d;
+                q /= d;
             }
 
-            numerator = num;
-            denominator = den;
+            numerator = p;
+            denominator = q;
         }
     }
 


[commons-numbers] 02/09: BigFraction/Fraction: clean-up javadoc

Posted by ah...@apache.org.
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 077baedf1203d26ff34592c60fc2e44ca1d58ee6
Author: aherbert <ah...@apache.org>
AuthorDate: Tue Apr 7 10:08:43 2020 +0100

    BigFraction/Fraction: clean-up javadoc
    
    Remove <p> tags from first paragraph.
    
    Change <code> tags to {@code ...}
    
    Consistent javadoc between BigFraction and Fraction.
---
 .../commons/numbers/fraction/BigFraction.java      | 261 +++++++--------------
 .../apache/commons/numbers/fraction/Fraction.java  |  45 ++--
 2 files changed, 117 insertions(+), 189 deletions(-)

diff --git a/commons-numbers-fraction/src/main/java/org/apache/commons/numbers/fraction/BigFraction.java b/commons-numbers-fraction/src/main/java/org/apache/commons/numbers/fraction/BigFraction.java
index a3c3242..a62e0d7 100644
--- a/commons-numbers-fraction/src/main/java/org/apache/commons/numbers/fraction/BigFraction.java
+++ b/commons-numbers-fraction/src/main/java/org/apache/commons/numbers/fraction/BigFraction.java
@@ -24,8 +24,14 @@ import org.apache.commons.numbers.core.ArithmeticUtils;
 import org.apache.commons.numbers.core.NativeOperators;
 
 /**
- * Representation of a rational number without any overflow. This class is
- * immutable.
+ * Representation of a rational number using arbitrary precision.
+ *
+ * <p>The number is expressed as the quotient {@code p/q} of two {@link BigInteger}s,
+ * a numerator {@code p} and a non-zero denominator {@code q}.
+ *
+ * <p>This class is immutable.
+ *
+ * <a href="https://en.wikipedia.org/wiki/Rational_number">Rational number</a>
  */
 public final class BigFraction
     extends Number
@@ -76,22 +82,26 @@ public final class BigFraction
      * error allowed or the maximum number of denominator digits.
      *
      * <p>
-     * NOTE: This method is called with
-     *  - EITHER a valid epsilon value and the maxDenominator set to
-     *    Integer.MAX_VALUE (that way the maxDenominator has no effect)
-     *  - OR a valid maxDenominator value and the epsilon value set to
-     *    zero (that way epsilon only has effect if there is an exact
-     *    match before the maxDenominator value is reached).
+     * NOTE: This method is called with:
      * </p>
+     * <ul>
+     *  <li>EITHER a valid epsilon value and the maxDenominator set to
+     *      Integer.MAX_VALUE (that way the maxDenominator has no effect)
+     *  <li>OR a valid maxDenominator value and the epsilon value set to
+     *      zero (that way epsilon only has effect if there is an exact
+     *      match before the maxDenominator value is reached).
+     * </ul>
      * <p>
      * It has been done this way so that the same code can be reused for
-     * both scenarios.  However this could be confusing to users if it
+     * both scenarios. However this could be confusing to users if it
      * were part of the public API and this method should therefore remain
      * PRIVATE.
      * </p>
      *
+     * <p>
      * See JIRA issue ticket MATH-181 for more details:
-     *   https://issues.apache.org/jira/browse/MATH-181
+     *     https://issues.apache.org/jira/browse/MATH-181
+     * </p>
      *
      * @param value Value to convert to a fraction.
      * @param epsilon Maximum error allowed.
@@ -175,32 +185,6 @@ public final class BigFraction
     }
 
     /**
-     * <p>
-     * Create a {@link BigFraction} equivalent to the passed {@code BigInteger}, ie
-     * "num / 1".
-     * </p>
-     *
-     * @param num the numerator.
-     * @return a new instance.
-     */
-    public static BigFraction of(final BigInteger num) {
-        return new BigFraction(num, BigInteger.ONE);
-    }
-
-    /**
-     * Create a {@link BigFraction} given the numerator and denominator as
-     * {@code BigInteger}. The {@link BigFraction} is reduced to lowest terms.
-     *
-     * @param num the numerator, must not be {@code null}.
-     * @param den the denominator, must not be {@code null}.
-     * @throws ArithmeticException if the denominator is zero.
-     * @return a new instance.
-     */
-    public static BigFraction of(BigInteger num, BigInteger den) {
-        return new BigFraction(num, den);
-    }
-
-    /**
      * Create a fraction given the double value.
      * <p>
      * This factory method behaves <em>differently</em> from
@@ -315,10 +299,7 @@ public final class BigFraction
     }
 
     /**
-     * <p>
-     * Create a {@link BigFraction} equivalent to the passed {@code int}, ie
-     * "num / 1".
-     * </p>
+     * Create a fraction given the numerator. The denominator is {@code 1}.
      *
      * @param num
      *            the numerator.
@@ -329,10 +310,8 @@ public final class BigFraction
     }
 
     /**
-     * <p>
-     * Create a {@link BigFraction} given the numerator and denominator as simple
-     * {@code int}. The {@link BigFraction} is reduced to lowest terms.
-     * </p>
+     * Create a fraction given the numerator and denominator.
+     * The fraction is reduced to lowest terms.
      *
      * @param num the numerator.
      * @param den the denominator.
@@ -344,9 +323,7 @@ public final class BigFraction
     }
 
     /**
-     * <p>
-     * Create a {@link BigFraction} equivalent to the passed long, ie "num / 1".
-     * </p>
+     * Create a fraction given the numerator. The denominator is {@code 1}.
      *
      * @param num the numerator.
      * @return a new instance.
@@ -356,10 +333,8 @@ public final class BigFraction
     }
 
     /**
-     * <p>
-     * Create a {@link BigFraction} given the numerator and denominator as simple
-     * {@code long}. The {@link BigFraction} is reduced to lowest terms.
-     * </p>
+     * Create a fraction given the numerator and denominator.
+     * The fraction is reduced to lowest terms.
      *
      * @param num the numerator.
      * @param den the denominator.
@@ -371,11 +346,34 @@ public final class BigFraction
     }
 
     /**
-     * <p>
-     * Returns the absolute value of this {@link BigFraction}.
-     * </p>
+     * Create a fraction given the numerator. The denominator is {@code 1}.
      *
-     * @return the absolute value as a {@link BigFraction}.
+     * @param num the numerator.
+     * @return a new instance.
+     * @throws NullPointerException if numerator is null.
+     */
+    public static BigFraction of(final BigInteger num) {
+        return new BigFraction(num, BigInteger.ONE);
+    }
+
+    /**
+     * Create a fraction given the numerator and denominator.
+     * The fraction is reduced to lowest terms.
+     *
+     * @param num the numerator.
+     * @param den the denominator.
+     * @return a new instance.
+     * @throws ArithmeticException if the denominator is zero.
+     * @throws NullPointerException if numerator or denominator are null.
+     */
+    public static BigFraction of(BigInteger num, BigInteger den) {
+        return new BigFraction(num, den);
+    }
+
+    /**
+     * Returns the absolute value of this fraction.
+     *
+     * @return the absolute value.
      */
     public BigFraction abs() {
         return signum() >= 0 ?
@@ -384,14 +382,12 @@ public final class BigFraction
     }
 
     /**
-     * <p>
      * Adds the value of this fraction to the passed {@link BigInteger},
      * returning the result in reduced form.
-     * </p>
      *
      * @param bg
-     *            the {@link BigInteger} to add, must'nt be <code>null</code>.
-     * @return a <code>BigFraction</code> instance with the resulting values.
+     *            the {@link BigInteger} to add, must'nt be {@code null}.
+     * @return a {@code BigFraction} instance with the resulting values.
      */
     public BigFraction add(final BigInteger bg) {
         if (numerator.signum() == 0) {
@@ -405,41 +401,35 @@ public final class BigFraction
     }
 
     /**
-     * <p>
      * Adds the value of this fraction to the passed {@code integer}, returning
      * the result in reduced form.
-     * </p>
      *
      * @param i
      *            the {@code integer} to add.
-     * @return a <code>BigFraction</code> instance with the resulting values.
+     * @return a {@code BigFraction} instance with the resulting values.
      */
     public BigFraction add(final int i) {
         return add(BigInteger.valueOf(i));
     }
 
     /**
-     * <p>
      * Adds the value of this fraction to the passed {@code long}, returning
      * the result in reduced form.
-     * </p>
      *
      * @param l
      *            the {@code long} to add.
-     * @return a <code>BigFraction</code> instance with the resulting values.
+     * @return a {@code BigFraction} instance with the resulting values.
      */
     public BigFraction add(final long l) {
         return add(BigInteger.valueOf(l));
     }
 
     /**
-     * <p>
      * Adds the value of this fraction to another, returning the result in
      * reduced form.
-     * </p>
      *
      * @param fraction
-     *            the {@link BigFraction} to add, must not be <code>null</code>.
+     *            the {@link BigFraction} to add, must not be {@code null}.
      * @return a {@link BigFraction} instance with the resulting values.
      */
     @Override
@@ -471,12 +461,10 @@ public final class BigFraction
     }
 
     /**
-     * <p>
-     * Gets the fraction as a <code>BigDecimal</code>. This calculates the
+     * Gets the fraction as a {@code BigDecimal}. This calculates the
      * fraction as the numerator divided by denominator.
-     * </p>
      *
-     * @return the fraction as a <code>BigDecimal</code>.
+     * @return the fraction as a {@code BigDecimal}.
      * @throws ArithmeticException
      *             if the exact quotient does not have a terminating decimal
      *             expansion.
@@ -487,14 +475,12 @@ public final class BigFraction
     }
 
     /**
-     * <p>
-     * Gets the fraction as a <code>BigDecimal</code> following the passed
+     * Gets the fraction as a {@code BigDecimal} following the passed
      * rounding mode. This calculates the fraction as the numerator divided by
      * denominator.
-     * </p>
      *
      * @param roundingMode Rounding mode to apply.
-     * @return the fraction as a <code>BigDecimal</code>.
+     * @return the fraction as a {@code BigDecimal}.
      * @see BigDecimal
      */
     public BigDecimal bigDecimalValue(RoundingMode roundingMode) {
@@ -502,17 +488,15 @@ public final class BigFraction
     }
 
     /**
-     * <p>
-     * Gets the fraction as a <code>BigDecimal</code> following the passed scale
+     * Gets the fraction as a {@code BigDecimal} following the passed scale
      * and rounding mode. This calculates the fraction as the numerator divided
      * by denominator.
-     * </p>
      *
      * @param scale
-     *            scale of the <code>BigDecimal</code> quotient to be returned.
+     *            scale of the {@code BigDecimal} quotient to be returned.
      *            see {@link BigDecimal} for more information.
      * @param roundingMode Rounding mode to apply.
-     * @return the fraction as a <code>BigDecimal</code>.
+     * @return the fraction as a {@code BigDecimal}.
      * @throws ArithmeticException if {@code roundingMode} == {@link RoundingMode#UNNECESSARY} and
      *      the specified scale is insufficient to represent the result of the division exactly.
      * @see BigDecimal
@@ -522,9 +506,7 @@ public final class BigFraction
     }
 
     /**
-     * <p>
      * Compares this object to another based on size.
-     * </p>
      *
      * @param other Object to compare to, must not be {@code null}.
      * @return -1 if this is less than {@code object}, +1 if this is greater
@@ -550,10 +532,8 @@ public final class BigFraction
     }
 
     /**
-     * <p>
      * Divide the value of this fraction by the passed {@code BigInteger},
      * ie {@code this * 1 / bg}, returning the result in reduced form.
-     * </p>
      *
      * @param bg the {@code BigInteger} to divide by, must not be {@code null}
      * @return a {@link BigFraction} instance with the resulting values
@@ -570,10 +550,8 @@ public final class BigFraction
     }
 
     /**
-     * <p>
      * Divide the value of this fraction by the passed {@code int}, ie
      * {@code this * 1 / i}, returning the result in reduced form.
-     * </p>
      *
      * @param i the {@code int} to divide by
      * @return a {@link BigFraction} instance with the resulting values
@@ -584,10 +562,8 @@ public final class BigFraction
     }
 
     /**
-     * <p>
      * Divide the value of this fraction by the passed {@code long}, ie
      * {@code this * 1 / l}, returning the result in reduced form.
-     * </p>
      *
      * @param l the {@code long} to divide by
      * @return a {@link BigFraction} instance with the resulting values
@@ -598,10 +574,8 @@ public final class BigFraction
     }
 
     /**
-     * <p>
      * Divide the value of this fraction by another, returning the result in
      * reduced form.
-     * </p>
      *
      * @param fraction Fraction to divide by, must not be {@code null}.
      * @return a {@link BigFraction} instance with the resulting values.
@@ -783,10 +757,8 @@ public final class BigFraction
     }
 
     /**
-     * <p>
      * Gets the fraction as a {@code double}. This calculates the fraction as
      * the numerator divided by denominator.
-     * </p>
      *
      * @return the fraction as a {@code double}
      * @see java.lang.Number#doubleValue()
@@ -828,17 +800,15 @@ public final class BigFraction
     }
 
     /**
-     * <p>
      * Test for the equality of two fractions. If the lowest term numerator and
      * denominators are the same for both fractions, the two fractions are
      * considered to be equal.
-     * </p>
      *
      * @param other
      *            fraction to test for equality to this fraction, can be
-     *            <code>null</code>.
+     *            {@code null}.
      * @return true if two fractions are equal, false if object is
-     *         <code>null</code>, not an instance of {@link BigFraction}, or not
+     *         {@code null}, not an instance of {@link BigFraction}, or not
      *         equal to this fraction instance.
      * @see java.lang.Object#equals(java.lang.Object)
      */
@@ -861,10 +831,8 @@ public final class BigFraction
     }
 
     /**
-     * <p>
-     * Gets the fraction as a {@code float}. This calculates the fraction as
-     * the numerator divided by denominator.
-     * </p>
+     * Retrieves the {@code float} value closest to this fraction.
+     * This calculates the fraction as numerator divided by denominator.
      *
      * @return the fraction as a {@code float}.
      * @see java.lang.Number#floatValue()
@@ -875,31 +843,25 @@ public final class BigFraction
     }
 
     /**
-     * <p>
-     * Access the denominator as a <code>BigInteger</code>.
-     * </p>
+     * Access the denominator as a {@code BigInteger}.
      *
-     * @return the denominator as a <code>BigInteger</code>.
+     * @return the denominator as a {@code BigInteger}.
      */
     public BigInteger getDenominator() {
         return denominator;
     }
 
     /**
-     * <p>
-     * Access the denominator as a {@code int}.
-     * </p>
+     * Access the denominator as an {@code int}.
      *
-     * @return the denominator as a {@code int}.
+     * @return the denominator as an {@code int}.
      */
     public int getDenominatorAsInt() {
         return denominator.intValue();
     }
 
     /**
-     * <p>
      * Access the denominator as a {@code long}.
-     * </p>
      *
      * @return the denominator as a {@code long}.
      */
@@ -908,31 +870,25 @@ public final class BigFraction
     }
 
     /**
-     * <p>
-     * Access the numerator as a <code>BigInteger</code>.
-     * </p>
+     * Access the numerator as a {@code BigInteger}.
      *
-     * @return the numerator as a <code>BigInteger</code>.
+     * @return the numerator as a {@code BigInteger}.
      */
     public BigInteger getNumerator() {
         return numerator;
     }
 
     /**
-     * <p>
-     * Access the numerator as a {@code int}.
-     * </p>
+     * Access the numerator as an {@code int}.
      *
-     * @return the numerator as a {@code int}.
+     * @return the numerator as an {@code int}.
      */
     public int getNumeratorAsInt() {
         return numerator.intValue();
     }
 
     /**
-     * <p>
      * Access the numerator as a {@code long}.
-     * </p>
      *
      * @return the numerator as a {@code long}.
      */
@@ -940,24 +896,15 @@ public final class BigFraction
         return numerator.longValue();
     }
 
-    /**
-     * <p>
-     * Gets a hashCode for the fraction.
-     * </p>
-     *
-     * @return a hash code value for this object.
-     * @see java.lang.Object#hashCode()
-     */
+    /** {@inheritDoc} */
     @Override
     public int hashCode() {
         return 37 * (37 * 17 + numerator.hashCode()) + denominator.hashCode();
     }
 
     /**
-     * <p>
      * Gets the fraction as an {@code int}. This returns the whole number part
      * of the fraction.
-     * </p>
      *
      * @return the whole number fraction part.
      * @see java.lang.Number#intValue()
@@ -968,10 +915,8 @@ public final class BigFraction
     }
 
     /**
-     * <p>
      * Gets the fraction as a {@code long}. This returns the whole number part
      * of the fraction.
-     * </p>
      *
      * @return the whole number fraction part.
      * @see java.lang.Number#longValue()
@@ -982,10 +927,8 @@ public final class BigFraction
     }
 
     /**
-     * <p>
      * Multiplies the value of this fraction by the passed
-     * <code>BigInteger</code>, returning the result in reduced form.
-     * </p>
+     * {@code BigInteger}, returning the result in reduced form.
      *
      * @param bg the {@code BigInteger} to multiply by.
      * @return a {@code BigFraction} instance with the resulting values.
@@ -998,10 +941,8 @@ public final class BigFraction
     }
 
     /**
-     * <p>
      * Multiply the value of this fraction by the passed {@code int}, returning
      * the result in reduced form.
-     * </p>
      *
      * @param i
      *            the {@code int} to multiply by.
@@ -1017,10 +958,8 @@ public final class BigFraction
     }
 
     /**
-     * <p>
      * Multiply the value of this fraction by the passed {@code long},
      * returning the result in reduced form.
-     * </p>
      *
      * @param l
      *            the {@code long} to multiply by.
@@ -1035,10 +974,8 @@ public final class BigFraction
     }
 
     /**
-     * <p>
      * Multiplies the value of this fraction by another, returning the result in
      * reduced form.
-     * </p>
      *
      * @param fraction Fraction to multiply by, must not be {@code null}.
      * @return a {@link BigFraction} instance with the resulting values.
@@ -1074,10 +1011,8 @@ public final class BigFraction
     }
 
     /**
-     * <p>
      * Return the additive inverse of this fraction, returning the result in
      * reduced form.
-     * </p>
      *
      * @return the negation of this fraction.
      */
@@ -1087,10 +1022,8 @@ public final class BigFraction
     }
 
     /**
-     * <p>
      * Returns a {@code BigFraction} whose value is
      * {@code (this<sup>exponent</sup>)}, returning the result in reduced form.
-     * </p>
      *
      * @param exponent
      *            exponent to which this {@code BigFraction} is to be
@@ -1113,14 +1046,12 @@ public final class BigFraction
     }
 
     /**
-     * <p>
-     * Returns a <code>BigFraction</code> whose value is
+     * Returns a {@code BigFraction} whose value is
      * \(\mathit{this}^{\mathit{exponent}}\), returning the result in reduced form.
-     * </p>
      *
      * @param exponent
-     *            exponent to which this <code>BigFraction</code> is to be raised.
-     * @return \(\mathit{this}^{\mathit{exponent}}\) as a <code>BigFraction</code>.
+     *            exponent to which this {@code BigFraction} is to be raised.
+     * @return \(\mathit{this}^{\mathit{exponent}}\) as a {@code BigFraction}.
      */
     public BigFraction pow(final long exponent) {
         if (exponent == 0) {
@@ -1139,14 +1070,12 @@ public final class BigFraction
     }
 
     /**
-     * <p>
-     * Returns a <code>BigFraction</code> whose value is
+     * Returns a {@code BigFraction} whose value is
      * \(\mathit{this}^{\mathit{exponent}}\), returning the result in reduced form.
-     * </p>
      *
      * @param exponent
-     *            exponent to which this <code>BigFraction</code> is to be raised.
-     * @return \(\mathit{this}^{\mathit{exponent}}\) as a <code>BigFraction</code>.
+     *            exponent to which this {@code BigFraction} is to be raised.
+     * @return \(\mathit{this}^{\mathit{exponent}}\) as a {@code BigFraction}.
      */
     public BigFraction pow(final BigInteger exponent) {
         if (exponent.signum() == 0) {
@@ -1166,13 +1095,11 @@ public final class BigFraction
     }
 
     /**
-     * <p>
-     * Returns a <code>double</code> whose value is
+     * Returns a {@code double} whose value is
      * \(\mathit{this}^{\mathit{exponent}}\), returning the result in reduced form.
-     * </p>
      *
      * @param exponent
-     *            exponent to which this <code>BigFraction</code> is to be raised.
+     *            exponent to which this {@code BigFraction} is to be raised.
      * @return \(\mathit{this}^{\mathit{exponent}}\).
      */
     public double pow(final double exponent) {
@@ -1181,9 +1108,7 @@ public final class BigFraction
     }
 
     /**
-     * <p>
      * Return the multiplicative inverse of this fraction.
-     * </p>
      *
      * @return the reciprocal fraction.
      */
@@ -1193,10 +1118,8 @@ public final class BigFraction
     }
 
     /**
-     * <p>
      * Subtracts the value of an {@link BigInteger} from the value of this
      * {@code BigFraction}, returning the result in reduced form.
-     * </p>
      *
      * @param bg the {@link BigInteger} to subtract, cannot be {@code null}.
      * @return a {@code BigFraction} instance with the resulting values.
@@ -1213,10 +1136,8 @@ public final class BigFraction
     }
 
     /**
-     * <p>
      * Subtracts the value of an {@code integer} from the value of this
      * {@code BigFraction}, returning the result in reduced form.
-     * </p>
      *
      * @param i the {@code integer} to subtract.
      * @return a {@code BigFraction} instance with the resulting values.
@@ -1226,10 +1147,8 @@ public final class BigFraction
     }
 
     /**
-     * <p>
      * Subtracts the value of a {@code long} from the value of this
      * {@code BigFraction}, returning the result in reduced form.
-     * </p>
      *
      * @param l the {@code long} to subtract.
      * @return a {@code BigFraction} instance with the resulting values.
@@ -1239,10 +1158,8 @@ public final class BigFraction
     }
 
     /**
-     * <p>
      * Subtracts the value of another fraction from the value of this one,
      * returning the result in reduced form.
-     * </p>
      *
      * @param fraction {@link BigFraction} to subtract, must not be {@code null}.
      * @return a {@link BigFraction} instance with the resulting values
@@ -1269,10 +1186,8 @@ public final class BigFraction
     }
 
     /**
-     * <p>
-     * Returns the <code>String</code> representing this fraction, ie
+     * Returns the {@code String} representing this fraction, ie
      * "num / dem" or just "num" if the denominator is one.
-     * </p>
      *
      * @return a string representation of the fraction.
      * @see java.lang.Object#toString()
diff --git a/commons-numbers-fraction/src/main/java/org/apache/commons/numbers/fraction/Fraction.java b/commons-numbers-fraction/src/main/java/org/apache/commons/numbers/fraction/Fraction.java
index bdc39f5..00dd80e 100644
--- a/commons-numbers-fraction/src/main/java/org/apache/commons/numbers/fraction/Fraction.java
+++ b/commons-numbers-fraction/src/main/java/org/apache/commons/numbers/fraction/Fraction.java
@@ -22,6 +22,13 @@ import org.apache.commons.numbers.core.NativeOperators;
 
 /**
  * Representation of a rational number.
+ *
+ * <p>The number is expressed as the quotient {@code p/q} of two 32-bit integers,
+ * a numerator {@code p} and a non-zero denominator {@code q}.
+ *
+ * <p>This class is immutable.
+ *
+ * <a href="https://en.wikipedia.org/wiki/Rational_number">Rational number</a>
  */
 public final class Fraction
     extends Number
@@ -30,38 +37,45 @@ public final class Fraction
                Serializable {
     /** A fraction representing "1". */
     public static final Fraction ONE = new Fraction(1, 1);
+
     /** A fraction representing "0". */
     public static final Fraction ZERO = new Fraction(0, 1);
+
     /** Serializable version identifier. */
     private static final long serialVersionUID = 20190701L;
+
     /** The default epsilon used for convergence. */
     private static final double DEFAULT_EPSILON = 1e-5;
+
     /** The denominator of this fraction reduced to lowest terms. */
     private final int denominator;
+
     /** The numerator of this fraction reduced to lowest terms. */
     private final int numerator;
 
     /**
      * Create a fraction given the double value and either the maximum error
      * allowed or the maximum number of denominator digits.
-     * <p>
-     *
-     * NOTE: This constructor is called with EITHER
-     *   - a valid epsilon value and the maxDenominator set to Integer.MAX_VALUE
-     *     (that way the maxDenominator has no effect).
-     * OR
-     *   - a valid maxDenominator value and the epsilon value set to zero
-     *     (that way epsilon only has effect if there is an exact match before
-     *     the maxDenominator value is reached).
-     * </p><p>
      *
+     * <p>
+     * NOTE: This constructor is called with:
+     * <ul>
+     *  <li>EITHER a valid epsilon value and the maxDenominator set to Integer.MAX_VALUE
+     *      (that way the maxDenominator has no effect).
+     *  <li>OR a valid maxDenominator value and the epsilon value set to zero
+     *      (that way epsilon only has effect if there is an exact match before
+     *      the maxDenominator value is reached).
+     * </ul>
+     * <p>
      * It has been done this way so that the same code can be (re)used for both
      * scenarios. However this could be confusing to users if it were part of
      * the public API and this constructor should therefore remain PRIVATE.
      * </p>
      *
+     * <p>
      * See JIRA issue ticket MATH-181 for more details:
      *     https://issues.apache.org/jira/browse/MATH-181
+     * </p>
      *
      * @param value the double value to convert to a fraction.
      * @param epsilon maximum error allowed.  The resulting fraction is
@@ -146,7 +160,7 @@ public final class Fraction
      * Constructs an instance.
      *
      * @param num Numerator.
-     * @param den Nenominator.
+     * @param den Denominator.
      * @throws ArithmeticException if the denominator is {@code zero}
      * or if integer overflow occurs.
      */
@@ -180,7 +194,7 @@ public final class Fraction
     }
 
     /**
-     * Creates an instance.
+     * Create a fraction given the double value.
      *
      * @param value Value to convert to a fraction.
      * @throws ArithmeticException if the continued fraction failed to
@@ -214,7 +228,7 @@ public final class Fraction
     }
 
     /**
-     * Creates an instance.
+     * Create a fraction given the double value and maximum denominator.
      *
      * <p>
      * References:
@@ -234,8 +248,7 @@ public final class Fraction
     }
 
     /**
-     * Creates an instance.
-     * The fraction is {@code num / 1}.
+     * Create a fraction given the numerator. The denominator is {@code 1}.
      *
      * @param num Numerator.
      * @return a new instance.
@@ -245,7 +258,7 @@ public final class Fraction
     }
 
     /**
-     * Return a fraction given the numerator and denominator.
+     * Create a fraction given the numerator and denominator.
      * The fraction is reduced to lowest terms.
      *
      * @param num Numerator.


[commons-numbers] 04/09: Fraction/BigFraction to validate input double in factory constructors

Posted by ah...@apache.org.
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 4e596fc5c9203f898e49806d6f3b46388e26be1f
Author: aherbert <ah...@apache.org>
AuthorDate: Tue Apr 7 11:41:05 2020 +0100

    Fraction/BigFraction to validate input double in factory constructors
    
    The double must not be nan or infinite.
---
 .../commons/numbers/fraction/BigFraction.java      | 18 ++++++---
 .../apache/commons/numbers/fraction/Fraction.java  | 44 ++++++++++++++--------
 .../commons/numbers/fraction/BigFractionTest.java  | 12 ++++++
 .../commons/numbers/fraction/FractionTest.java     | 12 ++++++
 4 files changed, 64 insertions(+), 22 deletions(-)

diff --git a/commons-numbers-fraction/src/main/java/org/apache/commons/numbers/fraction/BigFraction.java b/commons-numbers-fraction/src/main/java/org/apache/commons/numbers/fraction/BigFraction.java
index 9a969c9..152a33e 100644
--- a/commons-numbers-fraction/src/main/java/org/apache/commons/numbers/fraction/BigFraction.java
+++ b/commons-numbers-fraction/src/main/java/org/apache/commons/numbers/fraction/BigFraction.java
@@ -47,6 +47,9 @@ public final class BigFraction
     /** Serializable version identifier. */
     private static final long serialVersionUID = 20190701L;
 
+    /** Message for non-finite input double argument to factory constructors. */
+    private static final String NOT_FINITE = "Not finite: ";
+
     /** The numerator of this fraction reduced to lowest terms. */
     private final BigInteger numerator;
 
@@ -110,12 +113,17 @@ public final class BigFraction
      * @param maxDenominator Maximum denominator value allowed.
      * @param maxIterations Maximum number of convergents.
      * @return a new instance.
+     * @throws IllegalArgumentException if the given {@code value} is NaN or infinite.
      * @throws ArithmeticException if the continued fraction failed to converge.
      */
     private static BigFraction from(final double value,
                                     final double epsilon,
                                     final int maxDenominator,
                                     final int maxIterations) {
+        if (!Double.isFinite(value)) {
+            throw new IllegalArgumentException(NOT_FINITE + value);
+        }
+
         final long overflow = Integer.MAX_VALUE;
         double r0 = value;
         long a0 = (long) Math.floor(r0);
@@ -187,7 +195,7 @@ public final class BigFraction
     /**
      * Create a fraction given the double value.
      * <p>
-     * This factory method behaves <em>differently</em> from
+     * This factory method behaves <em>differently</em> to the method
      * {@link #from(double, double, int)}. It converts the double value
      * exactly, considering its internal bits representation. This works for all
      * values except NaN and infinities and does not requires any loop or
@@ -209,11 +217,8 @@ public final class BigFraction
      * @see #from(double,double,int)
      */
     public static BigFraction from(final double value) {
-        if (Double.isNaN(value)) {
-            throw new IllegalArgumentException("Cannot convert NaN value");
-        }
-        if (Double.isInfinite(value)) {
-            throw new IllegalArgumentException("Cannot convert infinite value");
+        if (!Double.isFinite(value)) {
+            throw new IllegalArgumentException(NOT_FINITE + value);
         }
 
         final long bits = Double.doubleToLongBits(value);
@@ -266,6 +271,7 @@ public final class BigFraction
      * @param epsilon Maximum error allowed. The resulting fraction is within
      * {@code epsilon} of {@code value}, in absolute terms.
      * @param maxIterations Maximum number of convergents.
+     * @throws IllegalArgumentException if the given {@code value} is NaN or infinite.
      * @throws ArithmeticException if the continued fraction failed to converge.
      * @return a new instance.
      *
diff --git a/commons-numbers-fraction/src/main/java/org/apache/commons/numbers/fraction/Fraction.java b/commons-numbers-fraction/src/main/java/org/apache/commons/numbers/fraction/Fraction.java
index 8135438..0ec2009 100644
--- a/commons-numbers-fraction/src/main/java/org/apache/commons/numbers/fraction/Fraction.java
+++ b/commons-numbers-fraction/src/main/java/org/apache/commons/numbers/fraction/Fraction.java
@@ -47,6 +47,9 @@ public final class Fraction
     /** The default epsilon used for convergence. */
     private static final double DEFAULT_EPSILON = 1e-5;
 
+    /** Message for non-finite input double argument to factory constructors. */
+    private static final String NOT_FINITE = "Not finite: ";
+
     /** The numerator of this fraction reduced to lowest terms. */
     private final int numerator;
 
@@ -55,7 +58,7 @@ public final class Fraction
 
 
     /**
-     * Constructs an instance.
+     * Private constructor: Instances are created using factory methods.
      *
      * @param num Numerator.
      * @param den Denominator.
@@ -98,16 +101,17 @@ public final class Fraction
      * <p>
      * NOTE: This constructor is called with:
      * <ul>
-     *  <li>EITHER a valid epsilon value and the maxDenominator set to Integer.MAX_VALUE
-     *      (that way the maxDenominator has no effect).
-     *  <li>OR a valid maxDenominator value and the epsilon value set to zero
-     *      (that way epsilon only has effect if there is an exact match before
-     *      the maxDenominator value is reached).
+     *  <li>EITHER a valid epsilon value and the maxDenominator set to
+     *      Integer.MAX_VALUE (that way the maxDenominator has no effect)
+     *  <li>OR a valid maxDenominator value and the epsilon value set to
+     *      zero (that way epsilon only has effect if there is an exact
+     *      match before the maxDenominator value is reached).
      * </ul>
      * <p>
-     * It has been done this way so that the same code can be (re)used for both
-     * scenarios. However this could be confusing to users if it were part of
-     * the public API and this constructor should therefore remain PRIVATE.
+     * It has been done this way so that the same code can be reused for
+     * both scenarios. However this could be confusing to users if it
+     * were part of the public API and this method should therefore remain
+     * PRIVATE.
      * </p>
      *
      * <p>
@@ -115,18 +119,23 @@ public final class Fraction
      *     https://issues.apache.org/jira/browse/MATH-181
      * </p>
      *
-     * @param value the double value to convert to a fraction.
-     * @param epsilon maximum error allowed.  The resulting fraction is
-     * within {@code epsilon} of {@code value}, in absolute terms.
-     * @param maxDenominator maximum denominator value allowed.
-     * @param maxIterations maximum number of convergents
-     * @throws ArithmeticException if the continued fraction failed
-     * to converge.
+     * @param value Value to convert to a fraction.
+     * @param epsilon Maximum error allowed.
+     * The resulting fraction is within {@code epsilon} of {@code value},
+     * in absolute terms.
+     * @param maxDenominator Maximum denominator value allowed.
+     * @param maxIterations Maximum number of convergents.
+     * @throws IllegalArgumentException if the given {@code value} is NaN or infinite.
+     * @throws ArithmeticException if the continued fraction failed to converge.
      */
     private Fraction(final double value,
                      final double epsilon,
                      final int maxDenominator,
                      final int maxIterations) {
+        if (!Double.isFinite(value)) {
+            throw new IllegalArgumentException(NOT_FINITE + value);
+        }
+
         final long overflow = Integer.MAX_VALUE;
         double r0 = value;
         long a0 = (long)Math.floor(r0);
@@ -201,6 +210,7 @@ public final class Fraction
      * Create a fraction given the double value.
      *
      * @param value Value to convert to a fraction.
+     * @throws IllegalArgumentException if the given {@code value} is NaN or infinite.
      * @throws ArithmeticException if the continued fraction failed to
      * converge.
      * @return a new instance.
@@ -223,6 +233,7 @@ public final class Fraction
      * @param epsilon maximum error allowed.  The resulting fraction is within
      * {@code epsilon} of {@code value}, in absolute terms.
      * @param maxIterations maximum number of convergents
+     * @throws IllegalArgumentException if the given {@code value} is NaN or infinite.
      * @throws ArithmeticException if the continued fraction failed to
      * converge.
      * @return a new instance.
@@ -245,6 +256,7 @@ public final class Fraction
      *
      * @param value the double value to convert to a fraction.
      * @param maxDenominator The maximum allowed value for denominator
+     * @throws IllegalArgumentException if the given {@code value} is NaN or infinite.
      * @throws ArithmeticException if the continued fraction failed to
      * converge.
      * @return a new instance.
diff --git a/commons-numbers-fraction/src/test/java/org/apache/commons/numbers/fraction/BigFractionTest.java b/commons-numbers-fraction/src/test/java/org/apache/commons/numbers/fraction/BigFractionTest.java
index 62057a2..d2da883 100644
--- a/commons-numbers-fraction/src/test/java/org/apache/commons/numbers/fraction/BigFractionTest.java
+++ b/commons-numbers-fraction/src/test/java/org/apache/commons/numbers/fraction/BigFractionTest.java
@@ -128,6 +128,18 @@ public class BigFractionTest {
         assertFraction(1, 2, BigFraction.from(0.5000000001, 10));
     }
 
+    @Test
+    public void testDoubleConstructorThrowsWithNonFinite() {
+        final double eps = 1e-5;
+        final int maxIterations = Integer.MAX_VALUE;
+        final int maxDenominator = Integer.MAX_VALUE;
+        for (final double value : new double[] {Double.NaN, Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY}) {
+            Assertions.assertThrows(IllegalArgumentException.class, () -> BigFraction.from(value));
+            Assertions.assertThrows(IllegalArgumentException.class, () -> BigFraction.from(value, eps, maxIterations));
+            Assertions.assertThrows(IllegalArgumentException.class, () -> BigFraction.from(value, maxDenominator));
+        }
+    }
+
     // MATH-1029
     @Test
     public void testPositiveValueOverflow() {
diff --git a/commons-numbers-fraction/src/test/java/org/apache/commons/numbers/fraction/FractionTest.java b/commons-numbers-fraction/src/test/java/org/apache/commons/numbers/fraction/FractionTest.java
index 9d19663..5534d2e 100644
--- a/commons-numbers-fraction/src/test/java/org/apache/commons/numbers/fraction/FractionTest.java
+++ b/commons-numbers-fraction/src/test/java/org/apache/commons/numbers/fraction/FractionTest.java
@@ -67,6 +67,18 @@ public class FractionTest {
         }
     }
 
+    @Test
+    public void testDoubleConstructorThrowsWithNonFinite() {
+        final double eps = 1e-5;
+        final int maxIterations = Integer.MAX_VALUE;
+        final int maxDenominator = Integer.MAX_VALUE;
+        for (final double value : new double[] {Double.NaN, Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY}) {
+            Assertions.assertThrows(IllegalArgumentException.class, () -> Fraction.from(value));
+            Assertions.assertThrows(IllegalArgumentException.class, () -> Fraction.from(value, eps, maxIterations));
+            Assertions.assertThrows(IllegalArgumentException.class, () -> Fraction.from(value, maxDenominator));
+        }
+    }
+
     // MATH-181
     @Test
     public void testDigitLimitConstructor() throws Exception  {


[commons-numbers] 01/09: BigFraction: Removed validation of arguments in internal function

Posted by ah...@apache.org.
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 db98ddf465f685a2ae0ec265feb6de8fe62f3f67
Author: aherbert <ah...@apache.org>
AuthorDate: Tue Apr 7 09:21:50 2020 +0100

    BigFraction: Removed validation of arguments in internal function
    
    This method is only called internally and the arguments are always
    valid.
---
 .../apache/commons/numbers/fraction/BigFraction.java    | 17 +++++++++--------
 1 file changed, 9 insertions(+), 8 deletions(-)

diff --git a/commons-numbers-fraction/src/main/java/org/apache/commons/numbers/fraction/BigFraction.java b/commons-numbers-fraction/src/main/java/org/apache/commons/numbers/fraction/BigFraction.java
index 2f9c1d0..a3c3242 100644
--- a/commons-numbers-fraction/src/main/java/org/apache/commons/numbers/fraction/BigFraction.java
+++ b/commons-numbers-fraction/src/main/java/org/apache/commons/numbers/fraction/BigFraction.java
@@ -628,6 +628,9 @@ public final class BigFraction
      * least significant bits used for the significand, the next more
      * significant bits for the exponent, and next more significant bit for the
      * sign.
+     *
+     * <p>Warning: The arguments are not validated.
+     *
      * @param exponentLength the number of bits allowed for the exponent; must be
      *                       between 1 and 32 (inclusive), and must not be greater
      *                       than {@code 63 - significandLength}
@@ -638,16 +641,14 @@ public final class BigFraction
      *                          {@code 63 - exponentLength} (inclusive)
      * @return the bits of an IEEE 754 binary floating-point representation of
      * this fraction encoded in a {@code long}, as described above.
-     * @throws IllegalArgumentException if the arguments do not meet the
-     *         criteria described above
      */
     private long toFloatingPointBits(int exponentLength, int significandLength) {
-        if (exponentLength < 1 ||
-            significandLength < 1 ||
-            exponentLength > Math.min(32, 63 - significandLength)) {
-            throw new IllegalArgumentException("exponent length: " + exponentLength +
-                                               "; significand length: " + significandLength);
-        }
+        // Assume the following conditions:
+        //assert exponentLength >= 1;
+        //assert exponentLength <= 32;
+        //assert significandLength >= 1;
+        //assert significandLength <= 63 - exponentLength;
+
         if (numerator.signum() == 0) {
             return 0L;
         }


[commons-numbers] 03/09: Fraction/BigFraction to use same method order:

Posted by ah...@apache.org.
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 7a94e4afb853c4e32b19a6ef0053937bf4bd7c2e
Author: aherbert <ah...@apache.org>
AuthorDate: Tue Apr 7 11:00:22 2020 +0100

    Fraction/BigFraction to use same method order:
    
    private constructors
    
    factory constructors, including parse(String)
    
    Properties:
    zero(), one()
    numerator(), denominator()
    
    Computed properties:
    signum
    
    Conversions:
    abs, negate, reciprocal
    primitive values (double/float/int/longValue,etc)
    
    Math:
    
    Arithmetic
    add,subtract,multiply,divide
    
    Power functions
    
    Standard object stuff:
    toString(), compareTo, equals(), hashCode()
---
 .../commons/numbers/fraction/BigFraction.java      | 1153 ++++++++++----------
 .../apache/commons/numbers/fraction/Fraction.java  |  414 +++----
 2 files changed, 786 insertions(+), 781 deletions(-)

diff --git a/commons-numbers-fraction/src/main/java/org/apache/commons/numbers/fraction/BigFraction.java b/commons-numbers-fraction/src/main/java/org/apache/commons/numbers/fraction/BigFraction.java
index a62e0d7..9a969c9 100644
--- a/commons-numbers-fraction/src/main/java/org/apache/commons/numbers/fraction/BigFraction.java
+++ b/commons-numbers-fraction/src/main/java/org/apache/commons/numbers/fraction/BigFraction.java
@@ -310,16 +310,13 @@ public final class BigFraction
     }
 
     /**
-     * Create a fraction given the numerator and denominator.
-     * The fraction is reduced to lowest terms.
+     * Create a fraction given the numerator. The denominator is {@code 1}.
      *
      * @param num the numerator.
-     * @param den the denominator.
      * @return a new instance.
-     * @throws ArithmeticException if {@code den} is zero.
      */
-    public static BigFraction of(final int num, final int den) {
-        return new BigFraction(BigInteger.valueOf(num), BigInteger.valueOf(den));
+    public static BigFraction of(final long num) {
+        return new BigFraction(BigInteger.valueOf(num), BigInteger.ONE);
     }
 
     /**
@@ -327,9 +324,10 @@ public final class BigFraction
      *
      * @param num the numerator.
      * @return a new instance.
+     * @throws NullPointerException if numerator is null.
      */
-    public static BigFraction of(final long num) {
-        return new BigFraction(BigInteger.valueOf(num), BigInteger.ONE);
+    public static BigFraction of(final BigInteger num) {
+        return new BigFraction(num, BigInteger.ONE);
     }
 
     /**
@@ -341,19 +339,21 @@ public final class BigFraction
      * @return a new instance.
      * @throws ArithmeticException if {@code den} is zero.
      */
-    public static BigFraction of(final long num, final long den) {
+    public static BigFraction of(final int num, final int den) {
         return new BigFraction(BigInteger.valueOf(num), BigInteger.valueOf(den));
     }
 
     /**
-     * Create a fraction given the numerator. The denominator is {@code 1}.
+     * Create a fraction given the numerator and denominator.
+     * The fraction is reduced to lowest terms.
      *
      * @param num the numerator.
+     * @param den the denominator.
      * @return a new instance.
-     * @throws NullPointerException if numerator is null.
+     * @throws ArithmeticException if {@code den} is zero.
      */
-    public static BigFraction of(final BigInteger num) {
-        return new BigFraction(num, BigInteger.ONE);
+    public static BigFraction of(final long num, final long den) {
+        return new BigFraction(BigInteger.valueOf(num), BigInteger.valueOf(den));
     }
 
     /**
@@ -366,10 +366,117 @@ public final class BigFraction
      * @throws ArithmeticException if the denominator is zero.
      * @throws NullPointerException if numerator or denominator are null.
      */
-    public static BigFraction of(BigInteger num, BigInteger den) {
+    public static BigFraction of(final BigInteger num, final BigInteger den) {
         return new BigFraction(num, den);
     }
 
+
+    /**
+     * Parses a string that would be produced by {@link #toString()}
+     * and instantiates the corresponding object.
+     *
+     * @param s String representation.
+     * @return an instance.
+     * @throws NumberFormatException if the string does not conform
+     * to the specification.
+     */
+    public static BigFraction parse(String s) {
+        s = s.replace(",", "");
+        final int slashLoc = s.indexOf('/');
+        // if no slash, parse as single number
+        if (slashLoc == -1) {
+            return BigFraction.of(new BigInteger(s.trim()));
+        }
+        final BigInteger num = new BigInteger(
+                s.substring(0, slashLoc).trim());
+        final BigInteger denom = new BigInteger(s.substring(slashLoc + 1).trim());
+        return of(num, denom);
+    }
+
+    @Override
+    public BigFraction zero() {
+        return ZERO;
+    }
+
+    @Override
+    public BigFraction one() {
+        return ONE;
+    }
+
+    /**
+     * Access the numerator as a {@code BigInteger}.
+     *
+     * @return the numerator as a {@code BigInteger}.
+     */
+    public BigInteger getNumerator() {
+        return numerator;
+    }
+
+    /**
+     * Access the numerator as an {@code int}.
+     *
+     * @return the numerator as an {@code int}.
+     */
+    public int getNumeratorAsInt() {
+        return numerator.intValue();
+    }
+
+    /**
+     * Access the numerator as a {@code long}.
+     *
+     * @return the numerator as a {@code long}.
+     */
+    public long getNumeratorAsLong() {
+        return numerator.longValue();
+    }
+
+    /**
+     * Access the denominator as a {@code BigInteger}.
+     *
+     * @return the denominator as a {@code BigInteger}.
+     */
+    public BigInteger getDenominator() {
+        return denominator;
+    }
+
+    /**
+     * Access the denominator as an {@code int}.
+     *
+     * @return the denominator as an {@code int}.
+     */
+    public int getDenominatorAsInt() {
+        return denominator.intValue();
+    }
+
+    /**
+     * Access the denominator as a {@code long}.
+     *
+     * @return the denominator as a {@code long}.
+     */
+    public long getDenominatorAsLong() {
+        return denominator.longValue();
+    }
+
+    /**
+     * Retrieves the sign of this fraction.
+     *
+     * @return -1 if the value is strictly negative, 1 if it is strictly
+     * positive, 0 if it is 0.
+     */
+    public int signum() {
+        final int numS = numerator.signum();
+        final int denS = denominator.signum();
+
+        if ((numS > 0 && denS > 0) ||
+            (numS < 0 && denS < 0)) {
+            return 1;
+        } else if (numS == 0) {
+            return 0;
+        } else {
+            return -1;
+        }
+    }
+
     /**
      * Returns the absolute value of this fraction.
      *
@@ -382,82 +489,72 @@ public final class BigFraction
     }
 
     /**
-     * Adds the value of this fraction to the passed {@link BigInteger},
-     * returning the result in reduced form.
+     * Return the additive inverse of this fraction, returning the result in
+     * reduced form.
      *
-     * @param bg
-     *            the {@link BigInteger} to add, must'nt be {@code null}.
-     * @return a {@code BigFraction} instance with the resulting values.
+     * @return the negation of this fraction.
      */
-    public BigFraction add(final BigInteger bg) {
-        if (numerator.signum() == 0) {
-            return of(bg);
-        }
-        if (bg.signum() == 0) {
-            return this;
-        }
-
-        return new BigFraction(numerator.add(denominator.multiply(bg)), denominator);
+    @Override
+    public BigFraction negate() {
+        return new BigFraction(numerator.negate(), denominator);
     }
 
     /**
-     * Adds the value of this fraction to the passed {@code integer}, returning
-     * the result in reduced form.
+     * Return the multiplicative inverse of this fraction.
      *
-     * @param i
-     *            the {@code integer} to add.
-     * @return a {@code BigFraction} instance with the resulting values.
+     * @return the reciprocal fraction.
      */
-    public BigFraction add(final int i) {
-        return add(BigInteger.valueOf(i));
+    @Override
+    public BigFraction reciprocal() {
+        return new BigFraction(denominator, numerator);
     }
 
     /**
-     * Adds the value of this fraction to the passed {@code long}, returning
-     * the result in reduced form.
+     * Gets the fraction as a {@code double}. This calculates the fraction as
+     * the numerator divided by denominator.
      *
-     * @param l
-     *            the {@code long} to add.
-     * @return a {@code BigFraction} instance with the resulting values.
+     * @return the fraction as a {@code double}
+     * @see java.lang.Number#doubleValue()
      */
-    public BigFraction add(final long l) {
-        return add(BigInteger.valueOf(l));
+    @Override
+    public double doubleValue() {
+        return Double.longBitsToDouble(toFloatingPointBits(11, 52));
     }
 
     /**
-     * Adds the value of this fraction to another, returning the result in
-     * reduced form.
+     * Retrieves the {@code float} value closest to this fraction.
+     * This calculates the fraction as numerator divided by denominator.
      *
-     * @param fraction
-     *            the {@link BigFraction} to add, must not be {@code null}.
-     * @return a {@link BigFraction} instance with the resulting values.
+     * @return the fraction as a {@code float}.
+     * @see java.lang.Number#floatValue()
      */
     @Override
-    public BigFraction add(final BigFraction fraction) {
-        if (fraction.numerator.signum() == 0) {
-            return this;
-        }
-        if (numerator.signum() == 0) {
-            return fraction;
-        }
-
-        final BigInteger num;
-        final BigInteger den;
-
-        if (denominator.equals(fraction.denominator)) {
-            num = numerator.add(fraction.numerator);
-            den = denominator;
-        } else {
-            num = (numerator.multiply(fraction.denominator)).add((fraction.numerator).multiply(denominator));
-            den = denominator.multiply(fraction.denominator);
-        }
-
-        if (num.signum() == 0) {
-            return ZERO;
-        }
+    public float floatValue() {
+        return Float.intBitsToFloat((int) toFloatingPointBits(8, 23));
+    }
 
-        return new BigFraction(num, den);
+    /**
+     * Gets the fraction as an {@code int}. This returns the whole number part
+     * of the fraction.
+     *
+     * @return the whole number fraction part.
+     * @see java.lang.Number#intValue()
+     */
+    @Override
+    public int intValue() {
+        return numerator.divide(denominator).intValue();
+    }
 
+    /**
+     * Gets the fraction as a {@code long}. This returns the whole number part
+     * of the fraction.
+     *
+     * @return the whole number fraction part.
+     * @see java.lang.Number#longValue()
+     */
+    @Override
+    public long longValue() {
+        return numerator.divide(denominator).longValue();
     }
 
     /**
@@ -506,47 +603,213 @@ public final class BigFraction
     }
 
     /**
-     * Compares this object to another based on size.
-     *
-     * @param other Object to compare to, must not be {@code null}.
-     * @return -1 if this is less than {@code object}, +1 if this is greater
-     * than {@code object}, 0 if they are equal.
+     * Adds the value of this fraction to the passed {@code integer}, returning
+     * the result in reduced form.
      *
-     * @see Comparable#compareTo(Object)
+     * @param i
+     *            the {@code integer} to add.
+     * @return a {@code BigFraction} instance with the resulting values.
      */
-    @Override
-    public int compareTo(final BigFraction other) {
-        final int lhsSigNum = signum();
-        final int rhsSigNum = other.signum();
-
-        if (lhsSigNum != rhsSigNum) {
-            return (lhsSigNum > rhsSigNum) ? 1 : -1;
-        }
-        if (lhsSigNum == 0) {
-            return 0;
-        }
+    public BigFraction add(final int i) {
+        return add(BigInteger.valueOf(i));
+    }
 
-        final BigInteger nOd = numerator.multiply(other.denominator);
-        final BigInteger dOn = denominator.multiply(other.numerator);
-        return nOd.compareTo(dOn);
+    /**
+     * Adds the value of this fraction to the passed {@code long}, returning
+     * the result in reduced form.
+     *
+     * @param l
+     *            the {@code long} to add.
+     * @return a {@code BigFraction} instance with the resulting values.
+     */
+    public BigFraction add(final long l) {
+        return add(BigInteger.valueOf(l));
     }
 
     /**
-     * Divide the value of this fraction by the passed {@code BigInteger},
-     * ie {@code this * 1 / bg}, returning the result in reduced form.
+     * Adds the value of this fraction to the passed {@link BigInteger},
+     * returning the result in reduced form.
      *
-     * @param bg the {@code BigInteger} to divide by, must not be {@code null}
-     * @return a {@link BigFraction} instance with the resulting values
-     * @throws ArithmeticException if the value to divide by is zero
+     * @param bg
+     *            the {@link BigInteger} to add, must'nt be {@code null}.
+     * @return a {@code BigFraction} instance with the resulting values.
      */
-    public BigFraction divide(final BigInteger bg) {
+    public BigFraction add(final BigInteger bg) {
+        if (numerator.signum() == 0) {
+            return of(bg);
+        }
         if (bg.signum() == 0) {
-            throw new FractionException(FractionException.ERROR_ZERO_DENOMINATOR);
+            return this;
+        }
+
+        return new BigFraction(numerator.add(denominator.multiply(bg)), denominator);
+    }
+
+    /**
+     * Adds the value of this fraction to another, returning the result in
+     * reduced form.
+     *
+     * @param fraction
+     *            the {@link BigFraction} to add, must not be {@code null}.
+     * @return a {@link BigFraction} instance with the resulting values.
+     */
+    @Override
+    public BigFraction add(final BigFraction fraction) {
+        if (fraction.numerator.signum() == 0) {
+            return this;
         }
         if (numerator.signum() == 0) {
+            return fraction;
+        }
+
+        final BigInteger num;
+        final BigInteger den;
+
+        if (denominator.equals(fraction.denominator)) {
+            num = numerator.add(fraction.numerator);
+            den = denominator;
+        } else {
+            num = (numerator.multiply(fraction.denominator)).add((fraction.numerator).multiply(denominator));
+            den = denominator.multiply(fraction.denominator);
+        }
+
+        if (num.signum() == 0) {
             return ZERO;
         }
-        return new BigFraction(numerator, denominator.multiply(bg));
+
+        return new BigFraction(num, den);
+    }
+
+    /**
+     * Subtracts the value of an {@code integer} from the value of this
+     * {@code BigFraction}, returning the result in reduced form.
+     *
+     * @param i the {@code integer} to subtract.
+     * @return a {@code BigFraction} instance with the resulting values.
+     */
+    public BigFraction subtract(final int i) {
+        return subtract(BigInteger.valueOf(i));
+    }
+
+    /**
+     * Subtracts the value of a {@code long} from the value of this
+     * {@code BigFraction}, returning the result in reduced form.
+     *
+     * @param l the {@code long} to subtract.
+     * @return a {@code BigFraction} instance with the resulting values.
+     */
+    public BigFraction subtract(final long l) {
+        return subtract(BigInteger.valueOf(l));
+    }
+
+    /**
+     * Subtracts the value of an {@link BigInteger} from the value of this
+     * {@code BigFraction}, returning the result in reduced form.
+     *
+     * @param bg the {@link BigInteger} to subtract, cannot be {@code null}.
+     * @return a {@code BigFraction} instance with the resulting values.
+     */
+    public BigFraction subtract(final BigInteger bg) {
+        if (bg.signum() == 0) {
+            return this;
+        }
+        if (numerator.signum() == 0) {
+            return of(bg.negate());
+        }
+
+        return new BigFraction(numerator.subtract(denominator.multiply(bg)), denominator);
+    }
+
+    /**
+     * Subtracts the value of another fraction from the value of this one,
+     * returning the result in reduced form.
+     *
+     * @param fraction {@link BigFraction} to subtract, must not be {@code null}.
+     * @return a {@link BigFraction} instance with the resulting values
+     */
+    @Override
+    public BigFraction subtract(final BigFraction fraction) {
+        if (fraction.numerator.signum() == 0) {
+            return this;
+        }
+        if (numerator.signum() == 0) {
+            return fraction.negate();
+        }
+
+        final BigInteger num;
+        final BigInteger den;
+        if (denominator.equals(fraction.denominator)) {
+            num = numerator.subtract(fraction.numerator);
+            den = denominator;
+        } else {
+            num = (numerator.multiply(fraction.denominator)).subtract((fraction.numerator).multiply(denominator));
+            den = denominator.multiply(fraction.denominator);
+        }
+        return new BigFraction(num, den);
+    }
+
+    /**
+     * Multiply the value of this fraction by the passed {@code int}, returning
+     * the result in reduced form.
+     *
+     * @param i
+     *            the {@code int} to multiply by.
+     * @return a {@link BigFraction} instance with the resulting values.
+     */
+    @Override
+    public BigFraction multiply(final int i) {
+        if (i == 0 || numerator.signum() == 0) {
+            return ZERO;
+        }
+
+        return multiply(BigInteger.valueOf(i));
+    }
+
+    /**
+     * Multiply the value of this fraction by the passed {@code long},
+     * returning the result in reduced form.
+     *
+     * @param l
+     *            the {@code long} to multiply by.
+     * @return a {@link BigFraction} instance with the resulting values.
+     */
+    public BigFraction multiply(final long l) {
+        if (l == 0 || numerator.signum() == 0) {
+            return ZERO;
+        }
+
+        return multiply(BigInteger.valueOf(l));
+    }
+
+    /**
+     * Multiplies the value of this fraction by the passed
+     * {@code BigInteger}, returning the result in reduced form.
+     *
+     * @param bg the {@code BigInteger} to multiply by.
+     * @return a {@code BigFraction} instance with the resulting values.
+     */
+    public BigFraction multiply(final BigInteger bg) {
+        if (numerator.signum() == 0 || bg.signum() == 0) {
+            return ZERO;
+        }
+        return new BigFraction(bg.multiply(numerator), denominator);
+    }
+
+    /**
+     * Multiplies the value of this fraction by another, returning the result in
+     * reduced form.
+     *
+     * @param fraction Fraction to multiply by, must not be {@code null}.
+     * @return a {@link BigFraction} instance with the resulting values.
+     */
+    @Override
+    public BigFraction multiply(final BigFraction fraction) {
+        if (numerator.signum() == 0 ||
+            fraction.numerator.signum() == 0) {
+            return ZERO;
+        }
+        return new BigFraction(numerator.multiply(fraction.numerator),
+                               denominator.multiply(fraction.denominator));
     }
 
     /**
@@ -574,6 +837,24 @@ public final class BigFraction
     }
 
     /**
+     * Divide the value of this fraction by the passed {@code BigInteger},
+     * ie {@code this * 1 / bg}, returning the result in reduced form.
+     *
+     * @param bg the {@code BigInteger} to divide by, must not be {@code null}
+     * @return a {@link BigFraction} instance with the resulting values
+     * @throws ArithmeticException if the value to divide by is zero
+     */
+    public BigFraction divide(final BigInteger bg) {
+        if (bg.signum() == 0) {
+            throw new FractionException(FractionException.ERROR_ZERO_DENOMINATOR);
+        }
+        if (numerator.signum() == 0) {
+            return ZERO;
+        }
+        return new BigFraction(numerator, denominator.multiply(bg));
+    }
+
+    /**
      * Divide the value of this fraction by another, returning the result in
      * reduced form.
      *
@@ -594,40 +875,205 @@ public final class BigFraction
     }
 
     /**
-     * Calculates the sign bit, the biased exponent and the significand for a
-     * binary floating-point representation of this {@code BigFraction}
-     * according to the IEEE 754 standard, and encodes these values into a {@code long}
-     * variable. The representative bits are arranged adjacent to each other and
-     * placed at the low-order end of the returned {@code long} value, with the
-     * least significant bits used for the significand, the next more
-     * significant bits for the exponent, and next more significant bit for the
-     * sign.
-     *
-     * <p>Warning: The arguments are not validated.
+     * Returns a {@code BigFraction} whose value is
+     * {@code (this<sup>exponent</sup>)}, returning the result in reduced form.
      *
-     * @param exponentLength the number of bits allowed for the exponent; must be
-     *                       between 1 and 32 (inclusive), and must not be greater
-     *                       than {@code 63 - significandLength}
-     * @param significandLength the number of bits allowed for the significand
-     *                          (excluding the implicit leading 1-bit in
-     *                          normalized numbers, e.g. 52 for a double-precision
-     *                          floating-point number); must be between 1 and
-     *                          {@code 63 - exponentLength} (inclusive)
-     * @return the bits of an IEEE 754 binary floating-point representation of
-     * this fraction encoded in a {@code long}, as described above.
+     * @param exponent
+     *            exponent to which this {@code BigFraction} is to be
+     *            raised.
+     * @return \(\mathit{this}^{\mathit{exponent}}\).
      */
-    private long toFloatingPointBits(int exponentLength, int significandLength) {
-        // Assume the following conditions:
-        //assert exponentLength >= 1;
-        //assert exponentLength <= 32;
-        //assert significandLength >= 1;
-        //assert significandLength <= 63 - exponentLength;
-
+    @Override
+    public BigFraction pow(final int exponent) {
+        if (exponent == 0) {
+            return ONE;
+        }
         if (numerator.signum() == 0) {
-            return 0L;
+            return this;
         }
 
-        final long sign = (numerator.signum() * denominator.signum()) == -1 ? 1L : 0L;
+        if (exponent < 0) {
+            return new BigFraction(denominator.pow(-exponent), numerator.pow(-exponent));
+        }
+        return new BigFraction(numerator.pow(exponent), denominator.pow(exponent));
+    }
+
+    /**
+     * Returns a {@code BigFraction} whose value is
+     * \(\mathit{this}^{\mathit{exponent}}\), returning the result in reduced form.
+     *
+     * @param exponent
+     *            exponent to which this {@code BigFraction} is to be raised.
+     * @return \(\mathit{this}^{\mathit{exponent}}\) as a {@code BigFraction}.
+     */
+    public BigFraction pow(final long exponent) {
+        if (exponent == 0) {
+            return ONE;
+        }
+        if (numerator.signum() == 0) {
+            return this;
+        }
+
+        if (exponent < 0) {
+            return new BigFraction(ArithmeticUtils.pow(denominator, -exponent),
+                                   ArithmeticUtils.pow(numerator,   -exponent));
+        }
+        return new BigFraction(ArithmeticUtils.pow(numerator,   exponent),
+                               ArithmeticUtils.pow(denominator, exponent));
+    }
+
+    /**
+     * Returns a {@code BigFraction} whose value is
+     * \(\mathit{this}^{\mathit{exponent}}\), returning the result in reduced form.
+     *
+     * @param exponent
+     *            exponent to which this {@code BigFraction} is to be raised.
+     * @return \(\mathit{this}^{\mathit{exponent}}\) as a {@code BigFraction}.
+     */
+    public BigFraction pow(final BigInteger exponent) {
+        if (exponent.signum() == 0) {
+            return ONE;
+        }
+        if (numerator.signum() == 0) {
+            return this;
+        }
+
+        if (exponent.signum() == -1) {
+            final BigInteger eNeg = exponent.negate();
+            return new BigFraction(ArithmeticUtils.pow(denominator, eNeg),
+                                   ArithmeticUtils.pow(numerator,   eNeg));
+        }
+        return new BigFraction(ArithmeticUtils.pow(numerator,   exponent),
+                               ArithmeticUtils.pow(denominator, exponent));
+    }
+
+    /**
+     * Returns a {@code double} whose value is
+     * \(\mathit{this}^{\mathit{exponent}}\), returning the result in reduced form.
+     *
+     * @param exponent
+     *            exponent to which this {@code BigFraction} is to be raised.
+     * @return \(\mathit{this}^{\mathit{exponent}}\).
+     */
+    public double pow(final double exponent) {
+        return Math.pow(numerator.doubleValue(),   exponent) /
+               Math.pow(denominator.doubleValue(), exponent);
+    }
+
+    /**
+     * Returns the {@code String} representing this fraction.
+     * Uses:
+     * <ul>
+     *  <li>{@code "0"} if {@code numerator} is zero.
+     *  <li>{@code "numerator"} if {@code denominator} is one.
+     *  <li>{@code "numerator / denominator"} for all other cases.
+     * </ul>
+     *
+     * @return a string representation of the fraction.
+     */
+    @Override
+    public String toString() {
+        final String str;
+        if (BigInteger.ONE.equals(denominator)) {
+            str = numerator.toString();
+        } else if (BigInteger.ZERO.equals(numerator)) {
+            str = "0";
+        } else {
+            str = numerator + " / " + denominator;
+        }
+        return str;
+    }
+
+    /**
+     * Compares this object to another based on size.
+     *
+     * @param other Object to compare to, must not be {@code null}.
+     * @return -1 if this is less than {@code object}, +1 if this is greater
+     * than {@code object}, 0 if they are equal.
+     *
+     * @see Comparable#compareTo(Object)
+     */
+    @Override
+    public int compareTo(final BigFraction other) {
+        final int lhsSigNum = signum();
+        final int rhsSigNum = other.signum();
+
+        if (lhsSigNum != rhsSigNum) {
+            return (lhsSigNum > rhsSigNum) ? 1 : -1;
+        }
+        if (lhsSigNum == 0) {
+            return 0;
+        }
+
+        final BigInteger nOd = numerator.multiply(other.denominator);
+        final BigInteger dOn = denominator.multiply(other.numerator);
+        return nOd.compareTo(dOn);
+    }
+
+    /**
+     * Test for the equality of two fractions. If the lowest term numerator and
+     * denominators are the same for both fractions, the two fractions are
+     * considered to be equal.
+     *
+     * @param other {@inheritDoc}
+     * @return {@inheritDoc}
+     */
+    @Override
+    public boolean equals(final Object other) {
+        if (this == other) {
+            return true;
+        } else if (other instanceof BigFraction) {
+            final BigFraction rhs = (BigFraction) other;
+
+            if (signum() == rhs.signum()) {
+                return numerator.abs().equals(rhs.numerator.abs()) &&
+                       denominator.abs().equals(rhs.denominator.abs());
+            }
+        }
+
+        return false;
+    }
+
+    @Override
+    public int hashCode() {
+        return 37 * (37 * 17 + numerator.hashCode()) + denominator.hashCode();
+    }
+
+    /**
+     * Calculates the sign bit, the biased exponent and the significand for a
+     * binary floating-point representation of this {@code BigFraction}
+     * according to the IEEE 754 standard, and encodes these values into a {@code long}
+     * variable. The representative bits are arranged adjacent to each other and
+     * placed at the low-order end of the returned {@code long} value, with the
+     * least significant bits used for the significand, the next more
+     * significant bits for the exponent, and next more significant bit for the
+     * sign.
+     *
+     * <p>Warning: The arguments are not validated.
+     *
+     * @param exponentLength the number of bits allowed for the exponent; must be
+     *                       between 1 and 32 (inclusive), and must not be greater
+     *                       than {@code 63 - significandLength}
+     * @param significandLength the number of bits allowed for the significand
+     *                          (excluding the implicit leading 1-bit in
+     *                          normalized numbers, e.g. 52 for a double-precision
+     *                          floating-point number); must be between 1 and
+     *                          {@code 63 - exponentLength} (inclusive)
+     * @return the bits of an IEEE 754 binary floating-point representation of
+     * this fraction encoded in a {@code long}, as described above.
+     */
+    private long toFloatingPointBits(int exponentLength, int significandLength) {
+        // Assume the following conditions:
+        //assert exponentLength >= 1;
+        //assert exponentLength <= 32;
+        //assert significandLength >= 1;
+        //assert significandLength <= 63 - exponentLength;
+
+        if (numerator.signum() == 0) {
+            return 0L;
+        }
+
+        final long sign = (numerator.signum() * denominator.signum()) == -1 ? 1L : 0L;
         final BigInteger positiveNumerator = numerator.abs();
         final BigInteger positiveDenominator = denominator.abs();
 
@@ -757,18 +1203,6 @@ public final class BigFraction
     }
 
     /**
-     * Gets the fraction as a {@code double}. This calculates the fraction as
-     * the numerator divided by denominator.
-     *
-     * @return the fraction as a {@code double}
-     * @see java.lang.Number#doubleValue()
-     */
-    @Override
-    public double doubleValue() {
-        return Double.longBitsToDouble(toFloatingPointBits(11, 52));
-    }
-
-    /**
      * Rounds an integer to the specified power of two (i.e. the minimum number of
      * low-order bits that must be zero) and performs a right-shift by this
      * amount. The rounding mode applied is round to nearest, with ties rounding
@@ -798,445 +1232,4 @@ public final class BigFraction
 
         return result;
     }
-
-    /**
-     * Test for the equality of two fractions. If the lowest term numerator and
-     * denominators are the same for both fractions, the two fractions are
-     * considered to be equal.
-     *
-     * @param other
-     *            fraction to test for equality to this fraction, can be
-     *            {@code null}.
-     * @return true if two fractions are equal, false if object is
-     *         {@code null}, not an instance of {@link BigFraction}, or not
-     *         equal to this fraction instance.
-     * @see java.lang.Object#equals(java.lang.Object)
-     */
-    @Override
-    public boolean equals(final Object other) {
-        if (this == other) {
-            return true;
-        } else if (other instanceof BigFraction) {
-            final BigFraction rhs = (BigFraction) other;
-
-            if (signum() == rhs.signum()) {
-                return numerator.abs().equals(rhs.numerator.abs()) &&
-                    denominator.abs().equals(rhs.denominator.abs());
-            } else {
-                return false;
-            }
-        }
-
-        return false;
-    }
-
-    /**
-     * Retrieves the {@code float} value closest to this fraction.
-     * This calculates the fraction as numerator divided by denominator.
-     *
-     * @return the fraction as a {@code float}.
-     * @see java.lang.Number#floatValue()
-     */
-    @Override
-    public float floatValue() {
-        return Float.intBitsToFloat((int) toFloatingPointBits(8, 23));
-    }
-
-    /**
-     * Access the denominator as a {@code BigInteger}.
-     *
-     * @return the denominator as a {@code BigInteger}.
-     */
-    public BigInteger getDenominator() {
-        return denominator;
-    }
-
-    /**
-     * Access the denominator as an {@code int}.
-     *
-     * @return the denominator as an {@code int}.
-     */
-    public int getDenominatorAsInt() {
-        return denominator.intValue();
-    }
-
-    /**
-     * Access the denominator as a {@code long}.
-     *
-     * @return the denominator as a {@code long}.
-     */
-    public long getDenominatorAsLong() {
-        return denominator.longValue();
-    }
-
-    /**
-     * Access the numerator as a {@code BigInteger}.
-     *
-     * @return the numerator as a {@code BigInteger}.
-     */
-    public BigInteger getNumerator() {
-        return numerator;
-    }
-
-    /**
-     * Access the numerator as an {@code int}.
-     *
-     * @return the numerator as an {@code int}.
-     */
-    public int getNumeratorAsInt() {
-        return numerator.intValue();
-    }
-
-    /**
-     * Access the numerator as a {@code long}.
-     *
-     * @return the numerator as a {@code long}.
-     */
-    public long getNumeratorAsLong() {
-        return numerator.longValue();
-    }
-
-    /** {@inheritDoc} */
-    @Override
-    public int hashCode() {
-        return 37 * (37 * 17 + numerator.hashCode()) + denominator.hashCode();
-    }
-
-    /**
-     * Gets the fraction as an {@code int}. This returns the whole number part
-     * of the fraction.
-     *
-     * @return the whole number fraction part.
-     * @see java.lang.Number#intValue()
-     */
-    @Override
-    public int intValue() {
-        return numerator.divide(denominator).intValue();
-    }
-
-    /**
-     * Gets the fraction as a {@code long}. This returns the whole number part
-     * of the fraction.
-     *
-     * @return the whole number fraction part.
-     * @see java.lang.Number#longValue()
-     */
-    @Override
-    public long longValue() {
-        return numerator.divide(denominator).longValue();
-    }
-
-    /**
-     * Multiplies the value of this fraction by the passed
-     * {@code BigInteger}, returning the result in reduced form.
-     *
-     * @param bg the {@code BigInteger} to multiply by.
-     * @return a {@code BigFraction} instance with the resulting values.
-     */
-    public BigFraction multiply(final BigInteger bg) {
-        if (numerator.signum() == 0 || bg.signum() == 0) {
-            return ZERO;
-        }
-        return new BigFraction(bg.multiply(numerator), denominator);
-    }
-
-    /**
-     * Multiply the value of this fraction by the passed {@code int}, returning
-     * the result in reduced form.
-     *
-     * @param i
-     *            the {@code int} to multiply by.
-     * @return a {@link BigFraction} instance with the resulting values.
-     */
-    @Override
-    public BigFraction multiply(final int i) {
-        if (i == 0 || numerator.signum() == 0) {
-            return ZERO;
-        }
-
-        return multiply(BigInteger.valueOf(i));
-    }
-
-    /**
-     * Multiply the value of this fraction by the passed {@code long},
-     * returning the result in reduced form.
-     *
-     * @param l
-     *            the {@code long} to multiply by.
-     * @return a {@link BigFraction} instance with the resulting values.
-     */
-    public BigFraction multiply(final long l) {
-        if (l == 0 || numerator.signum() == 0) {
-            return ZERO;
-        }
-
-        return multiply(BigInteger.valueOf(l));
-    }
-
-    /**
-     * Multiplies the value of this fraction by another, returning the result in
-     * reduced form.
-     *
-     * @param fraction Fraction to multiply by, must not be {@code null}.
-     * @return a {@link BigFraction} instance with the resulting values.
-     */
-    @Override
-    public BigFraction multiply(final BigFraction fraction) {
-        if (numerator.signum() == 0 ||
-            fraction.numerator.signum() == 0) {
-            return ZERO;
-        }
-        return new BigFraction(numerator.multiply(fraction.numerator),
-                               denominator.multiply(fraction.denominator));
-    }
-
-    /**
-     * Retrieves the sign of this fraction.
-     *
-     * @return -1 if the value is strictly negative, 1 if it is strictly
-     * positive, 0 if it is 0.
-     */
-    public int signum() {
-        final int numS = numerator.signum();
-        final int denS = denominator.signum();
-
-        if ((numS > 0 && denS > 0) ||
-            (numS < 0 && denS < 0)) {
-            return 1;
-        } else if (numS == 0) {
-            return 0;
-        } else {
-            return -1;
-        }
-    }
-
-    /**
-     * Return the additive inverse of this fraction, returning the result in
-     * reduced form.
-     *
-     * @return the negation of this fraction.
-     */
-    @Override
-    public BigFraction negate() {
-        return new BigFraction(numerator.negate(), denominator);
-    }
-
-    /**
-     * Returns a {@code BigFraction} whose value is
-     * {@code (this<sup>exponent</sup>)}, returning the result in reduced form.
-     *
-     * @param exponent
-     *            exponent to which this {@code BigFraction} is to be
-     *            raised.
-     * @return \(\mathit{this}^{\mathit{exponent}}\).
-     */
-    @Override
-    public BigFraction pow(final int exponent) {
-        if (exponent == 0) {
-            return ONE;
-        }
-        if (numerator.signum() == 0) {
-            return this;
-        }
-
-        if (exponent < 0) {
-            return new BigFraction(denominator.pow(-exponent), numerator.pow(-exponent));
-        }
-        return new BigFraction(numerator.pow(exponent), denominator.pow(exponent));
-    }
-
-    /**
-     * Returns a {@code BigFraction} whose value is
-     * \(\mathit{this}^{\mathit{exponent}}\), returning the result in reduced form.
-     *
-     * @param exponent
-     *            exponent to which this {@code BigFraction} is to be raised.
-     * @return \(\mathit{this}^{\mathit{exponent}}\) as a {@code BigFraction}.
-     */
-    public BigFraction pow(final long exponent) {
-        if (exponent == 0) {
-            return ONE;
-        }
-        if (numerator.signum() == 0) {
-            return this;
-        }
-
-        if (exponent < 0) {
-            return new BigFraction(ArithmeticUtils.pow(denominator, -exponent),
-                                   ArithmeticUtils.pow(numerator,   -exponent));
-        }
-        return new BigFraction(ArithmeticUtils.pow(numerator,   exponent),
-                               ArithmeticUtils.pow(denominator, exponent));
-    }
-
-    /**
-     * Returns a {@code BigFraction} whose value is
-     * \(\mathit{this}^{\mathit{exponent}}\), returning the result in reduced form.
-     *
-     * @param exponent
-     *            exponent to which this {@code BigFraction} is to be raised.
-     * @return \(\mathit{this}^{\mathit{exponent}}\) as a {@code BigFraction}.
-     */
-    public BigFraction pow(final BigInteger exponent) {
-        if (exponent.signum() == 0) {
-            return ONE;
-        }
-        if (numerator.signum() == 0) {
-            return this;
-        }
-
-        if (exponent.signum() == -1) {
-            final BigInteger eNeg = exponent.negate();
-            return new BigFraction(ArithmeticUtils.pow(denominator, eNeg),
-                                   ArithmeticUtils.pow(numerator,   eNeg));
-        }
-        return new BigFraction(ArithmeticUtils.pow(numerator,   exponent),
-                               ArithmeticUtils.pow(denominator, exponent));
-    }
-
-    /**
-     * Returns a {@code double} whose value is
-     * \(\mathit{this}^{\mathit{exponent}}\), returning the result in reduced form.
-     *
-     * @param exponent
-     *            exponent to which this {@code BigFraction} is to be raised.
-     * @return \(\mathit{this}^{\mathit{exponent}}\).
-     */
-    public double pow(final double exponent) {
-        return Math.pow(numerator.doubleValue(),   exponent) /
-               Math.pow(denominator.doubleValue(), exponent);
-    }
-
-    /**
-     * Return the multiplicative inverse of this fraction.
-     *
-     * @return the reciprocal fraction.
-     */
-    @Override
-    public BigFraction reciprocal() {
-        return new BigFraction(denominator, numerator);
-    }
-
-    /**
-     * Subtracts the value of an {@link BigInteger} from the value of this
-     * {@code BigFraction}, returning the result in reduced form.
-     *
-     * @param bg the {@link BigInteger} to subtract, cannot be {@code null}.
-     * @return a {@code BigFraction} instance with the resulting values.
-     */
-    public BigFraction subtract(final BigInteger bg) {
-        if (bg.signum() == 0) {
-            return this;
-        }
-        if (numerator.signum() == 0) {
-            return of(bg.negate());
-        }
-
-        return new BigFraction(numerator.subtract(denominator.multiply(bg)), denominator);
-    }
-
-    /**
-     * Subtracts the value of an {@code integer} from the value of this
-     * {@code BigFraction}, returning the result in reduced form.
-     *
-     * @param i the {@code integer} to subtract.
-     * @return a {@code BigFraction} instance with the resulting values.
-     */
-    public BigFraction subtract(final int i) {
-        return subtract(BigInteger.valueOf(i));
-    }
-
-    /**
-     * Subtracts the value of a {@code long} from the value of this
-     * {@code BigFraction}, returning the result in reduced form.
-     *
-     * @param l the {@code long} to subtract.
-     * @return a {@code BigFraction} instance with the resulting values.
-     */
-    public BigFraction subtract(final long l) {
-        return subtract(BigInteger.valueOf(l));
-    }
-
-    /**
-     * Subtracts the value of another fraction from the value of this one,
-     * returning the result in reduced form.
-     *
-     * @param fraction {@link BigFraction} to subtract, must not be {@code null}.
-     * @return a {@link BigFraction} instance with the resulting values
-     */
-    @Override
-    public BigFraction subtract(final BigFraction fraction) {
-        if (fraction.numerator.signum() == 0) {
-            return this;
-        }
-        if (numerator.signum() == 0) {
-            return fraction.negate();
-        }
-
-        final BigInteger num;
-        final BigInteger den;
-        if (denominator.equals(fraction.denominator)) {
-            num = numerator.subtract(fraction.numerator);
-            den = denominator;
-        } else {
-            num = (numerator.multiply(fraction.denominator)).subtract((fraction.numerator).multiply(denominator));
-            den = denominator.multiply(fraction.denominator);
-        }
-        return new BigFraction(num, den);
-    }
-
-    /**
-     * Returns the {@code String} representing this fraction, ie
-     * "num / dem" or just "num" if the denominator is one.
-     *
-     * @return a string representation of the fraction.
-     * @see java.lang.Object#toString()
-     */
-    @Override
-    public String toString() {
-        final String str;
-        if (BigInteger.ONE.equals(denominator)) {
-            str = numerator.toString();
-        } else if (BigInteger.ZERO.equals(numerator)) {
-            str = "0";
-        } else {
-            str = numerator + " / " + denominator;
-        }
-        return str;
-    }
-
-    /** {@inheritDoc} */
-    @Override
-    public BigFraction zero() {
-        return ZERO;
-    }
-
-    /** {@inheritDoc} */
-    @Override
-    public BigFraction one() {
-        return ONE;
-    }
-
-    /**
-     * Parses a string that would be produced by {@link #toString()}
-     * and instantiates the corresponding object.
-     *
-     * @param s String representation.
-     * @return an instance.
-     * @throws NumberFormatException if the string does not conform
-     * to the specification.
-     */
-    public static BigFraction parse(String s) {
-        s = s.replace(",", "");
-        final int slashLoc = s.indexOf('/');
-        // if no slash, parse as single number
-        if (slashLoc == -1) {
-            return BigFraction.of(new BigInteger(s.trim()));
-        } else {
-            final BigInteger num = new BigInteger(
-                    s.substring(0, slashLoc).trim());
-            final BigInteger denom = new BigInteger(s.substring(slashLoc + 1).trim());
-            return of(num, denom);
-        }
-    }
 }
diff --git a/commons-numbers-fraction/src/main/java/org/apache/commons/numbers/fraction/Fraction.java b/commons-numbers-fraction/src/main/java/org/apache/commons/numbers/fraction/Fraction.java
index 00dd80e..8135438 100644
--- a/commons-numbers-fraction/src/main/java/org/apache/commons/numbers/fraction/Fraction.java
+++ b/commons-numbers-fraction/src/main/java/org/apache/commons/numbers/fraction/Fraction.java
@@ -35,23 +35,61 @@ public final class Fraction
     implements Comparable<Fraction>,
                NativeOperators<Fraction>,
                Serializable {
-    /** A fraction representing "1". */
-    public static final Fraction ONE = new Fraction(1, 1);
-
     /** A fraction representing "0". */
     public static final Fraction ZERO = new Fraction(0, 1);
 
+    /** A fraction representing "1". */
+    public static final Fraction ONE = new Fraction(1, 1);
+
     /** Serializable version identifier. */
     private static final long serialVersionUID = 20190701L;
 
     /** The default epsilon used for convergence. */
     private static final double DEFAULT_EPSILON = 1e-5;
 
+    /** The numerator of this fraction reduced to lowest terms. */
+    private final int numerator;
+
     /** The denominator of this fraction reduced to lowest terms. */
     private final int denominator;
 
-    /** The numerator of this fraction reduced to lowest terms. */
-    private final int numerator;
+
+    /**
+     * Constructs an instance.
+     *
+     * @param num Numerator.
+     * @param den Denominator.
+     * @throws ArithmeticException if the denominator is {@code zero}
+     * or if integer overflow occurs.
+     */
+    private Fraction(int num, int den) {
+        if (den == 0) {
+            throw new ArithmeticException("division by zero");
+        }
+
+        if (num == den) {
+            numerator = 1;
+            denominator = 1;
+        } else {
+            // If num and den are both 2^-31, or if one is 0 and the other is 2^-31,
+            // the calculation of the gcd below will fail. Ensure that this does not
+            // happen by dividing both by 2 in case both are even.
+            if (((num | den) & 1) == 0) {
+                num >>= 1;
+                den >>= 1;
+            }
+
+            // Reduce numerator and denominator by greatest common divisor.
+            final int d = ArithmeticUtils.gcd(num, den);
+            if (d > 1) {
+                num /= d;
+                den /= d;
+            }
+
+            numerator = num;
+            denominator = den;
+        }
+    }
 
     /**
      * Create a fraction given the double value and either the maximum error
@@ -85,7 +123,10 @@ public final class Fraction
      * @throws ArithmeticException if the continued fraction failed
      * to converge.
      */
-    private Fraction(double value, double epsilon, int maxDenominator, int maxIterations) {
+    private Fraction(final double value,
+                     final double epsilon,
+                     final int maxDenominator,
+                     final int maxIterations) {
         final long overflow = Integer.MAX_VALUE;
         double r0 = value;
         long a0 = (long)Math.floor(r0);
@@ -157,43 +198,6 @@ public final class Fraction
     }
 
     /**
-     * Constructs an instance.
-     *
-     * @param num Numerator.
-     * @param den Denominator.
-     * @throws ArithmeticException if the denominator is {@code zero}
-     * or if integer overflow occurs.
-     */
-    private Fraction(int num, int den) {
-        if (den == 0) {
-            throw new ArithmeticException("division by zero");
-        }
-
-        if (num == den) {
-            numerator = 1;
-            denominator = 1;
-        } else {
-            // If num and den are both 2^-31, or if one is 0 and the other is 2^-31,
-            // the calculation of the gcd below will fail. Ensure that this does not
-            // happen by dividing both by 2 in case both are even.
-            if (((num | den) & 1) == 0) {
-                num >>= 1;
-                den >>= 1;
-            }
-
-            // Reduce numerator and denominator by greatest common divisor.
-            final int d = ArithmeticUtils.gcd(num, den);
-            if (d > 1) {
-                num /= d;
-                den /= d;
-            }
-
-            numerator = num;
-            denominator = den;
-        }
-    }
-
-    /**
      * Create a fraction given the double value.
      *
      * @param value Value to convert to a fraction.
@@ -201,7 +205,7 @@ public final class Fraction
      * converge.
      * @return a new instance.
      */
-    public static Fraction from(double value) {
+    public static Fraction from(final double value) {
         return from(value, DEFAULT_EPSILON, 100);
     }
 
@@ -223,7 +227,9 @@ public final class Fraction
      * converge.
      * @return a new instance.
      */
-    public static Fraction from(double value, double epsilon, int maxIterations) {
+    public static Fraction from(final double value,
+                                final double epsilon,
+                                final int maxIterations) {
         return new Fraction(value, epsilon, Integer.MAX_VALUE, maxIterations);
     }
 
@@ -243,7 +249,8 @@ public final class Fraction
      * converge.
      * @return a new instance.
      */
-    public static Fraction from(double value, int maxDenominator) {
+    public static Fraction from(final double value,
+                                final int maxDenominator) {
         return new Fraction(value, 0, maxDenominator, 100);
     }
 
@@ -253,7 +260,7 @@ public final class Fraction
      * @param num Numerator.
      * @return a new instance.
      */
-    public static Fraction of(int num) {
+    public static Fraction of(final int num) {
         return of(num, 1);
     }
 
@@ -267,11 +274,73 @@ public final class Fraction
      * or if integer overflow occurs.
      * @return a new instance.
      */
-    public static Fraction of(int num, int den) {
+    public static Fraction of(final int num, final int den) {
         return new Fraction(num, den);
     }
 
     /**
+     * Parses a string that would be produced by {@link #toString()}
+     * and instantiates the corresponding object.
+     *
+     * @param s String representation.
+     * @return an instance.
+     * @throws NumberFormatException if the string does not conform to the
+     * specification.
+     */
+    public static Fraction parse(String s) {
+        final int slashLoc = s.indexOf('/');
+        // if no slash, parse as single number
+        if (slashLoc == -1) {
+            return Fraction.of(Integer.parseInt(s.trim()));
+        } else {
+            final int num = Integer.parseInt(s.substring(0, slashLoc).trim());
+            final int denom = Integer.parseInt(s.substring(slashLoc + 1).trim());
+            return of(num, denom);
+        }
+    }
+
+    @Override
+    public Fraction zero() {
+        return ZERO;
+    }
+
+    @Override
+    public Fraction one() {
+        return ONE;
+    }
+
+    /**
+     * @return the numerator.
+     */
+    public int getNumerator() {
+        return numerator;
+    }
+
+    /**
+     * @return the denominator.
+     */
+    public int getDenominator() {
+        return denominator;
+    }
+
+    /**
+     * Retrieves the sign of this fraction.
+     *
+     * @return -1 if the value is strictly negative, 1 if it is strictly
+     * positive, 0 if it is 0.
+     */
+    public int signum() {
+        if ((numerator > 0 && denominator > 0) ||
+            (numerator < 0 && denominator < 0)) {
+            return 1;
+        } else if (numerator == 0) {
+            return 0;
+        } else {
+            return -1;
+        }
+    }
+
+    /**
      * Returns the absolute value of this fraction.
      *
      * @return the absolute value.
@@ -283,56 +352,36 @@ public final class Fraction
     }
 
     /**
-     * Compares this object to another based on size.
+     * Computes the additive inverse of this fraction.
      *
-     * @param other Object to compare to.
-     * @return -1 if this is less than {@code object}, +1 if this is greater
-     * than {@code object}, 0 if they are equal.
+     * @return the opposite.
      */
     @Override
-    public int compareTo(Fraction other) {
-        return Long.compare(((long) numerator) * other.denominator,
-                            ((long) denominator) * other.numerator);
+    public Fraction negate() {
+        return numerator == Integer.MIN_VALUE ?
+            new Fraction(numerator, -denominator) :
+            new Fraction(-numerator, denominator);
     }
 
     /**
-     * Retrieves the {@code double} value closest to this fraction.
-     * This calculates the fraction as numerator divided by denominator.
+     * Computes the multiplicative inverse of this fraction.
      *
-     * @return the fraction as a {@code double}.
+     * @return the reciprocal.
      */
     @Override
-    public double doubleValue() {
-        return (double) numerator / (double) denominator;
+    public Fraction reciprocal() {
+        return new Fraction(denominator, numerator);
     }
 
     /**
-     * Test for the equality of two fractions.
-     * If the lowest term numerator and denominators are the same for
-     * both fractions, the two fractions are considered to be equal.
-     * @param other Fraction to test for equality with.
-     * @return {@code true} if the two fractions are equal, {@code false}
-     * otherwise.
+     * Retrieves the {@code double} value closest to this fraction.
+     * This calculates the fraction as numerator divided by denominator.
+     *
+     * @return the fraction as a {@code double}.
      */
     @Override
-    public boolean equals(Object other) {
-        if (this == other) {
-            return true;
-        }
-
-        if (other instanceof Fraction) {
-            // Since fractions are always in lowest terms, numerators and
-            // denominators can be compared directly for equality.
-            final Fraction rhs = (Fraction) other;
-            if (signum() == rhs.signum()) {
-                return Math.abs(numerator) == Math.abs(rhs.numerator) &&
-                    Math.abs(denominator) == Math.abs(rhs.denominator);
-            } else {
-                return false;
-            }
-        }
-
-        return false;
+    public double doubleValue() {
+        return (double) numerator / (double) denominator;
     }
 
     /**
@@ -347,26 +396,6 @@ public final class Fraction
     }
 
     /**
-     * @return the denominator.
-     */
-    public int getDenominator() {
-        return denominator;
-    }
-
-    /**
-     * @return the numerator.
-     */
-    public int getNumerator() {
-        return numerator;
-    }
-
-    /** {@inheritDoc} */
-    @Override
-    public int hashCode() {
-        return 37 * (37 * 17 + numerator) + denominator;
-    }
-
-    /**
      * Retrieves the whole number part of the fraction.
      *
      * @return the largest {@code int} value that is not larger than
@@ -389,42 +418,13 @@ public final class Fraction
     }
 
     /**
-     * Retrieves the sign of this fraction.
-     *
-     * @return -1 if the value is strictly negative, 1 if it is strictly
-     * positive, 0 if it is 0.
-     */
-    public int signum() {
-        if ((numerator > 0 && denominator > 0) ||
-            (numerator < 0 && denominator < 0)) {
-            return 1;
-        } else if (numerator == 0) {
-            return 0;
-        } else {
-            return -1;
-        }
-    }
-
-    /**
-     * Computes the additive inverse of this fraction.
-     *
-     * @return the opposite.
-     */
-    @Override
-    public Fraction negate() {
-        return numerator == Integer.MIN_VALUE ?
-            new Fraction(numerator, -denominator) :
-            new Fraction(-numerator, denominator);
-    }
-
-    /**
-     * Computes the multiplicative inverse of this fraction.
+     * Adds an integer to the fraction.
      *
-     * @return the reciprocal.
+     * @param i Value to add.
+     * @return {@code this + i}.
      */
-    @Override
-    public Fraction reciprocal() {
-        return new Fraction(denominator, numerator);
+    public Fraction add(final int i) {
+        return new Fraction(numerator + i * denominator, denominator);
     }
 
     /**
@@ -443,13 +443,13 @@ public final class Fraction
     }
 
     /**
-     * Adds an integer to the fraction.
+     * Subtracts an integer from this fraction.
      *
-     * @param i Value to add.
-     * @return {@code this + i}.
+     * @param i Value to subtract.
+     * @return {@code this - i}.
      */
-    public Fraction add(final int i) {
-        return new Fraction(numerator + i * denominator, denominator);
+    public Fraction subtract(final int i) {
+        return new Fraction(numerator - i * denominator, denominator);
     }
 
     /**
@@ -467,16 +467,6 @@ public final class Fraction
     }
 
     /**
-     * Subtracts an integer from this fraction.
-     *
-     * @param i Value to subtract.
-     * @return {@code this - i}.
-     */
-    public Fraction subtract(final int i) {
-        return new Fraction(numerator - i * denominator, denominator);
-    }
-
-    /**
      * Implements add and subtract using algorithm described in Knuth 4.5.1.
      *
      * @param fraction Fraction to add or subtract.
@@ -529,6 +519,17 @@ public final class Fraction
     }
 
     /**
+     * Multiplies the fraction by an integer.
+     *
+     * @param i Value to multiply by.
+     * @return {@code this * i}.
+     */
+    @Override
+    public Fraction multiply(final int i) {
+        return multiply(of(i));
+    }
+
+    /**
      * Multiplies the value of this fraction by another, returning the
      * result in reduced form.
      *
@@ -553,14 +554,13 @@ public final class Fraction
     }
 
     /**
-     * Multiplies the fraction by an integer.
+     * Divides the fraction by an integer.
      *
-     * @param i Value to multiply by.
+     * @param i Value to divide by.
      * @return {@code this * i}.
      */
-    @Override
-    public Fraction multiply(final int i) {
-        return multiply(of(i));
+    public Fraction divide(final int i) {
+        return divide(of(i));
     }
 
     /**
@@ -583,36 +583,38 @@ public final class Fraction
     }
 
     /**
-     * Divides the fraction by an integer.
+     * {@inheritDoc}
      *
-     * @param i Value to divide by.
-     * @return {@code this * i}.
-     */
-    public Fraction divide(final int i) {
-        return divide(of(i));
-    }
-
-    /**
-     * @param n Power.
-     * @return <code>this<sup>n</sup></code>.
+     * @param exponent {@inheritDoc}
+     * @return <code>this<sup>exponent</sup></code>.
      */
     @Override
-    public Fraction pow(final int n) {
-        if (n == 0) {
+    public Fraction pow(final int exponent) {
+        if (exponent == 0) {
             return ONE;
         }
         if (numerator == 0) {
             return this;
         }
 
-        return n < 0 ?
-            new Fraction(ArithmeticUtils.pow(denominator, -n),
-                         ArithmeticUtils.pow(numerator, -n)) :
-            new Fraction(ArithmeticUtils.pow(numerator, n),
-                         ArithmeticUtils.pow(denominator, n));
+        return exponent < 0 ?
+            new Fraction(ArithmeticUtils.pow(denominator, -exponent),
+                         ArithmeticUtils.pow(numerator, -exponent)) :
+            new Fraction(ArithmeticUtils.pow(numerator, exponent),
+                         ArithmeticUtils.pow(denominator, exponent));
     }
 
-    /** {@inheritDoc} */
+    /**
+     * Returns the {@code String} representing this fraction.
+     * Uses:
+     * <ul>
+     *  <li>{@code "0"} if {@code numerator} is zero.
+     *  <li>{@code "numerator"} if {@code denominator} is one.
+     *  <li>{@code "numerator / denominator"} for all other cases.
+     * </ul>
+     *
+     * @return a string representation of the fraction.
+     */
     @Override
     public String toString() {
         final String str;
@@ -626,36 +628,46 @@ public final class Fraction
         return str;
     }
 
-    /** {@inheritDoc} */
-    @Override
-    public Fraction zero() {
-        return ZERO;
-    }
-
-    /** {@inheritDoc} */
+    /**
+     * Compares this object with the specified object for order using the signed magnitude.
+     *
+     * @param other {@inheritDoc}
+     * @return {@inheritDoc}
+     */
     @Override
-    public Fraction one() {
-        return ONE;
+    public int compareTo(Fraction other) {
+        return Long.compare(((long) numerator) * other.denominator,
+                            ((long) denominator) * other.numerator);
     }
 
     /**
-     * Parses a string that would be produced by {@link #toString()}
-     * and instantiates the corresponding object.
+     * Test for equality with another object. If the other object is a {@code Fraction} then a
+     * comparison is made of the sign and magnitude; otherwise {@code false} is returned.
      *
-     * @param s String representation.
-     * @return an instance.
-     * @throws NumberFormatException if the string does not conform to the
-     * specification.
+     * @param other {@inheritDoc}
+     * @return {@inheritDoc}
      */
-    public static Fraction parse(String s) {
-        final int slashLoc = s.indexOf('/');
-        // if no slash, parse as single number
-        if (slashLoc == -1) {
-            return Fraction.of(Integer.parseInt(s.trim()));
-        } else {
-            final int num = Integer.parseInt(s.substring(0, slashLoc).trim());
-            final int denom = Integer.parseInt(s.substring(slashLoc + 1).trim());
-            return of(num, denom);
+    @Override
+    public boolean equals(Object other) {
+        if (this == other) {
+            return true;
         }
+
+        if (other instanceof Fraction) {
+            // Since fractions are always in lowest terms, numerators and
+            // denominators can be compared directly for equality.
+            final Fraction rhs = (Fraction) other;
+            if (signum() == rhs.signum()) {
+                return Math.abs(numerator) == Math.abs(rhs.numerator) &&
+                    Math.abs(denominator) == Math.abs(rhs.denominator);
+            }
+        }
+
+        return false;
+    }
+
+    @Override
+    public int hashCode() {
+        return 37 * (37 * 17 + numerator) + denominator;
     }
 }


[commons-numbers] 05/09: Fraction/BigFraction to use consistent javadoc.

Posted by ah...@apache.org.
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 8b6ba200cad92f37c0127d45bd58ad28d52e07ad
Author: aherbert <ah...@apache.org>
AuthorDate: Tue Apr 7 12:34:07 2020 +0100

    Fraction/BigFraction to use consistent javadoc.
---
 .../commons/numbers/fraction/BigFraction.java      | 407 ++++++++++-----------
 .../apache/commons/numbers/fraction/Fraction.java  | 230 +++++++-----
 2 files changed, 326 insertions(+), 311 deletions(-)

diff --git a/commons-numbers-fraction/src/main/java/org/apache/commons/numbers/fraction/BigFraction.java b/commons-numbers-fraction/src/main/java/org/apache/commons/numbers/fraction/BigFraction.java
index 152a33e..617f386 100644
--- a/commons-numbers-fraction/src/main/java/org/apache/commons/numbers/fraction/BigFraction.java
+++ b/commons-numbers-fraction/src/main/java/org/apache/commons/numbers/fraction/BigFraction.java
@@ -274,8 +274,6 @@ public final class BigFraction
      * @throws IllegalArgumentException if the given {@code value} is NaN or infinite.
      * @throws ArithmeticException if the continued fraction failed to converge.
      * @return a new instance.
-     *
-     * @see #from(double,int)
      */
     public static BigFraction from(final double value,
                                    final double epsilon,
@@ -294,10 +292,9 @@ public final class BigFraction
      *
      * @param value Value to convert to a fraction.
      * @param maxDenominator Maximum allowed value for denominator.
+     * @throws IllegalArgumentException if the given {@code value} is NaN or infinite.
      * @throws ArithmeticException if the continued fraction failed to converge.
      * @return a new instance.
-     *
-     * @see #from(double,double,int)
      */
     public static BigFraction from(final double value,
                                    final int maxDenominator) {
@@ -318,7 +315,7 @@ public final class BigFraction
     /**
      * Create a fraction given the numerator. The denominator is {@code 1}.
      *
-     * @param num the numerator.
+     * @param num Numerator.
      * @return a new instance.
      */
     public static BigFraction of(final long num) {
@@ -328,7 +325,7 @@ public final class BigFraction
     /**
      * Create a fraction given the numerator. The denominator is {@code 1}.
      *
-     * @param num the numerator.
+     * @param num Numerator.
      * @return a new instance.
      * @throws NullPointerException if numerator is null.
      */
@@ -340,8 +337,8 @@ public final class BigFraction
      * Create a fraction given the numerator and denominator.
      * The fraction is reduced to lowest terms.
      *
-     * @param num the numerator.
-     * @param den the denominator.
+     * @param num Numerator.
+     * @param den Denominator.
      * @return a new instance.
      * @throws ArithmeticException if {@code den} is zero.
      */
@@ -353,8 +350,8 @@ public final class BigFraction
      * Create a fraction given the numerator and denominator.
      * The fraction is reduced to lowest terms.
      *
-     * @param num the numerator.
-     * @param den the denominator.
+     * @param num Numerator.
+     * @param den Denominator.
      * @return a new instance.
      * @throws ArithmeticException if {@code den} is zero.
      */
@@ -366,36 +363,58 @@ public final class BigFraction
      * Create a fraction given the numerator and denominator.
      * The fraction is reduced to lowest terms.
      *
-     * @param num the numerator.
-     * @param den the denominator.
+     * @param num Numerator.
+     * @param den Denominator.
      * @return a new instance.
-     * @throws ArithmeticException if the denominator is zero.
      * @throws NullPointerException if numerator or denominator are null.
+     * @throws ArithmeticException if the denominator is zero.
      */
     public static BigFraction of(final BigInteger num, final BigInteger den) {
         return new BigFraction(num, den);
     }
 
-
     /**
-     * Parses a string that would be produced by {@link #toString()}
-     * and instantiates the corresponding object.
+     * Returns a {@code BigFraction} instance representing the specified string {@code s}.
+     *
+     * <p>If {@code s} is {@code null}, then a {@code NullPointerException} is thrown.
+     *
+     * <p>The string must be in a format compatible with that produced by
+     * {@link #toString() BigFraction.toString()}.
+     * The format expects an integer optionally followed by a {@code '/'} character and
+     * and second integer. Leading and trailing spaces are allowed around each numeric part.
+     * Each numeric part is parsed using {@link BigInteger#BigInteger(String)}. The parts
+     * are interpreted as the numerator and optional denominator of the fraction. If absent
+     * the denominator is assumed to be "1".
+     *
+     * <p>Examples of valid strings and the equivalent {@code BigFraction} are shown below:
+     *
+     * <pre>
+     * "0"                 = BigFraction.of(0)
+     * "42"                = BigFraction.of(42)
+     * "0 / 1"             = BigFraction.of(0, 1)
+     * "1 / 3"             = BigFraction.of(1, 3)
+     * "-4 / 13"           = BigFraction.of(-4, 13)</pre>
+     *
+     * <p>Note: The fraction is returned in reduced form and the numerator and denominator
+     * may not match the values in the input string. For this reason the result of
+     * {@code BigFraction.parse(s).toString().equals(s)} may not be {@code true}.
      *
      * @param s String representation.
      * @return an instance.
-     * @throws NumberFormatException if the string does not conform
-     * to the specification.
+     * @throws NullPointerException if the string is null.
+     * @throws NumberFormatException if the string does not contain a parsable fraction.
+     * @see BigInteger#BigInteger(String)
+     * @see #toString()
      */
     public static BigFraction parse(String s) {
-        s = s.replace(",", "");
-        final int slashLoc = s.indexOf('/');
+        final String stripped = s.replace(",", "");
+        final int slashLoc = stripped.indexOf('/');
         // if no slash, parse as single number
         if (slashLoc == -1) {
-            return BigFraction.of(new BigInteger(s.trim()));
+            return BigFraction.of(new BigInteger(stripped.trim()));
         }
-        final BigInteger num = new BigInteger(
-                s.substring(0, slashLoc).trim());
-        final BigInteger denom = new BigInteger(s.substring(slashLoc + 1).trim());
+        final BigInteger num = new BigInteger(stripped.substring(0, slashLoc).trim());
+        final BigInteger denom = new BigInteger(stripped.substring(slashLoc + 1).trim());
         return of(num, denom);
     }
 
@@ -494,33 +513,20 @@ public final class BigFraction
             negate();
     }
 
-    /**
-     * Return the additive inverse of this fraction, returning the result in
-     * reduced form.
-     *
-     * @return the negation of this fraction.
-     */
     @Override
     public BigFraction negate() {
         return new BigFraction(numerator.negate(), denominator);
     }
 
-    /**
-     * Return the multiplicative inverse of this fraction.
-     *
-     * @return the reciprocal fraction.
-     */
     @Override
     public BigFraction reciprocal() {
         return new BigFraction(denominator, numerator);
     }
 
     /**
-     * Gets the fraction as a {@code double}. This calculates the fraction as
-     * the numerator divided by denominator.
+     * Returns the {@code double} value closest to this fraction.
      *
-     * @return the fraction as a {@code double}
-     * @see java.lang.Number#doubleValue()
+     * @return the fraction as a {@code double}.
      */
     @Override
     public double doubleValue() {
@@ -528,11 +534,9 @@ public final class BigFraction
     }
 
     /**
-     * Retrieves the {@code float} value closest to this fraction.
-     * This calculates the fraction as numerator divided by denominator.
+     * Returns the {@code float} value closest to this fraction.
      *
-     * @return the fraction as a {@code float}.
-     * @see java.lang.Number#floatValue()
+     * @return the fraction as a {@code double}.
      */
     @Override
     public float floatValue() {
@@ -540,11 +544,9 @@ public final class BigFraction
     }
 
     /**
-     * Gets the fraction as an {@code int}. This returns the whole number part
-     * of the fraction.
+     * Returns the whole number part of the fraction.
      *
-     * @return the whole number fraction part.
-     * @see java.lang.Number#intValue()
+     * @return the largest {@code int} value that is not larger than this fraction.
      */
     @Override
     public int intValue() {
@@ -552,11 +554,9 @@ public final class BigFraction
     }
 
     /**
-     * Gets the fraction as a {@code long}. This returns the whole number part
-     * of the fraction.
+     * Returns the whole number part of the fraction.
      *
-     * @return the whole number fraction part.
-     * @see java.lang.Number#longValue()
+     * @return the largest {@code long} value that is not larger than this fraction.
      */
     @Override
     public long longValue() {
@@ -564,8 +564,8 @@ public final class BigFraction
     }
 
     /**
-     * Gets the fraction as a {@code BigDecimal}. This calculates the
-     * fraction as the numerator divided by denominator.
+     * Returns the {@code BigDecimal} representation of this fraction.
+     * This calculates the fraction as numerator divided by denominator.
      *
      * @return the fraction as a {@code BigDecimal}.
      * @throws ArithmeticException
@@ -578,9 +578,9 @@ public final class BigFraction
     }
 
     /**
-     * Gets the fraction as a {@code BigDecimal} following the passed
-     * rounding mode. This calculates the fraction as the numerator divided by
-     * denominator.
+     * Returns the {@code BigDecimal} representation of this fraction.
+     * This calculates the fraction as numerator divided by denominator
+     * following the passed rounding mode.
      *
      * @param roundingMode Rounding mode to apply.
      * @return the fraction as a {@code BigDecimal}.
@@ -591,9 +591,9 @@ public final class BigFraction
     }
 
     /**
-     * Gets the fraction as a {@code BigDecimal} following the passed scale
-     * and rounding mode. This calculates the fraction as the numerator divided
-     * by denominator.
+     * Returns the {@code BigDecimal} representation of this fraction.
+     * This calculates the fraction as numerator divided by denominator
+     * following the passed scale and rounding mode.
      *
      * @param scale
      *            scale of the {@code BigDecimal} quotient to be returned.
@@ -609,74 +609,70 @@ public final class BigFraction
     }
 
     /**
-     * Adds the value of this fraction to the passed {@code integer}, returning
+     * Adds the specified {@code value} to this fraction, returning
      * the result in reduced form.
      *
-     * @param i
-     *            the {@code integer} to add.
-     * @return a {@code BigFraction} instance with the resulting values.
+     * @param value Value to add.
+     * @return {@code this + value}.
      */
-    public BigFraction add(final int i) {
-        return add(BigInteger.valueOf(i));
+    public BigFraction add(final int value) {
+        return add(BigInteger.valueOf(value));
     }
 
     /**
-     * Adds the value of this fraction to the passed {@code long}, returning
+     * Adds the specified {@code value} to this fraction, returning
      * the result in reduced form.
      *
-     * @param l
-     *            the {@code long} to add.
-     * @return a {@code BigFraction} instance with the resulting values.
+     * @param value Value to add.
+     * @return {@code this + value}.
      */
-    public BigFraction add(final long l) {
-        return add(BigInteger.valueOf(l));
+    public BigFraction add(final long value) {
+        return add(BigInteger.valueOf(value));
     }
 
     /**
-     * Adds the value of this fraction to the passed {@link BigInteger},
-     * returning the result in reduced form.
+     * Adds the specified {@code value} to this fraction, returning
+     * the result in reduced form.
      *
-     * @param bg
-     *            the {@link BigInteger} to add, must'nt be {@code null}.
-     * @return a {@code BigFraction} instance with the resulting values.
+     * @param value Value to add.
+     * @return {@code this + value}.
      */
-    public BigFraction add(final BigInteger bg) {
+    public BigFraction add(final BigInteger value) {
         if (numerator.signum() == 0) {
-            return of(bg);
+            return of(value);
         }
-        if (bg.signum() == 0) {
+        if (value.signum() == 0) {
             return this;
         }
 
-        return new BigFraction(numerator.add(denominator.multiply(bg)), denominator);
+        return new BigFraction(numerator.add(denominator.multiply(value)), denominator);
     }
 
     /**
-     * Adds the value of this fraction to another, returning the result in
-     * reduced form.
+     * Adds the specified {@code value} to this fraction, returning
+     * the result in reduced form.
      *
-     * @param fraction
-     *            the {@link BigFraction} to add, must not be {@code null}.
-     * @return a {@link BigFraction} instance with the resulting values.
+     * @param value Value to add.
+     * @return {@code this + value}.
      */
     @Override
-    public BigFraction add(final BigFraction fraction) {
-        if (fraction.numerator.signum() == 0) {
+    public BigFraction add(final BigFraction value) {
+        if (value.numerator.signum() == 0) {
             return this;
         }
         if (numerator.signum() == 0) {
-            return fraction;
+            return value;
         }
 
         final BigInteger num;
         final BigInteger den;
 
-        if (denominator.equals(fraction.denominator)) {
-            num = numerator.add(fraction.numerator);
+        if (denominator.equals(value.denominator)) {
+            num = numerator.add(value.numerator);
             den = denominator;
         } else {
-            num = (numerator.multiply(fraction.denominator)).add((fraction.numerator).multiply(denominator));
-            den = denominator.multiply(fraction.denominator);
+            num = (numerator.multiply(value.denominator)).add((value.numerator).multiply(denominator));
+            den = denominator.multiply(value.denominator);
         }
 
         if (num.signum() == 0) {
@@ -687,207 +683,202 @@ public final class BigFraction
     }
 
     /**
-     * Subtracts the value of an {@code integer} from the value of this
-     * {@code BigFraction}, returning the result in reduced form.
+     * Subtracts the specified {@code value} from this fraction, returning
+     * the result in reduced form.
      *
-     * @param i the {@code integer} to subtract.
-     * @return a {@code BigFraction} instance with the resulting values.
+     * @param value Value to subtract.
+     * @return {@code this - value}.
      */
-    public BigFraction subtract(final int i) {
-        return subtract(BigInteger.valueOf(i));
+    public BigFraction subtract(final int value) {
+        return subtract(BigInteger.valueOf(value));
     }
 
     /**
-     * Subtracts the value of a {@code long} from the value of this
-     * {@code BigFraction}, returning the result in reduced form.
+     * Subtracts the specified {@code value} from this fraction, returning
+     * the result in reduced form.
      *
-     * @param l the {@code long} to subtract.
-     * @return a {@code BigFraction} instance with the resulting values.
+     * @param value Value to subtract.
+     * @return {@code this - value}.
      */
-    public BigFraction subtract(final long l) {
-        return subtract(BigInteger.valueOf(l));
+    public BigFraction subtract(final long value) {
+        return subtract(BigInteger.valueOf(value));
     }
 
     /**
-     * Subtracts the value of an {@link BigInteger} from the value of this
-     * {@code BigFraction}, returning the result in reduced form.
+     * Subtracts the specified {@code value} from this fraction, returning
+     * the result in reduced form.
      *
-     * @param bg the {@link BigInteger} to subtract, cannot be {@code null}.
-     * @return a {@code BigFraction} instance with the resulting values.
+     * @param value Value to subtract.
+     * @return {@code this - value}.
      */
-    public BigFraction subtract(final BigInteger bg) {
-        if (bg.signum() == 0) {
+    public BigFraction subtract(final BigInteger value) {
+        if (value.signum() == 0) {
             return this;
         }
         if (numerator.signum() == 0) {
-            return of(bg.negate());
+            return of(value.negate());
         }
 
-        return new BigFraction(numerator.subtract(denominator.multiply(bg)), denominator);
+        return new BigFraction(numerator.subtract(denominator.multiply(value)), denominator);
     }
 
     /**
-     * Subtracts the value of another fraction from the value of this one,
-     * returning the result in reduced form.
+     * Subtracts the specified {@code value} from this fraction, returning
+     * the result in reduced form.
      *
-     * @param fraction {@link BigFraction} to subtract, must not be {@code null}.
-     * @return a {@link BigFraction} instance with the resulting values
+     * @param value Value to subtract.
+     * @return {@code this - value}.
      */
     @Override
-    public BigFraction subtract(final BigFraction fraction) {
-        if (fraction.numerator.signum() == 0) {
+    public BigFraction subtract(final BigFraction value) {
+        if (value.numerator.signum() == 0) {
             return this;
         }
         if (numerator.signum() == 0) {
-            return fraction.negate();
+            return value.negate();
         }
 
         final BigInteger num;
         final BigInteger den;
-        if (denominator.equals(fraction.denominator)) {
-            num = numerator.subtract(fraction.numerator);
+        if (denominator.equals(value.denominator)) {
+            num = numerator.subtract(value.numerator);
             den = denominator;
         } else {
-            num = (numerator.multiply(fraction.denominator)).subtract((fraction.numerator).multiply(denominator));
-            den = denominator.multiply(fraction.denominator);
+            num = (numerator.multiply(value.denominator)).subtract((value.numerator).multiply(denominator));
+            den = denominator.multiply(value.denominator);
         }
         return new BigFraction(num, den);
     }
 
     /**
-     * Multiply the value of this fraction by the passed {@code int}, returning
+     * Multiply this fraction by the passed {@code value}, returning
      * the result in reduced form.
      *
-     * @param i
-     *            the {@code int} to multiply by.
-     * @return a {@link BigFraction} instance with the resulting values.
+     * @param value Value to multiply by.
+     * @return {@code this * value}.
      */
     @Override
-    public BigFraction multiply(final int i) {
-        if (i == 0 || numerator.signum() == 0) {
+    public BigFraction multiply(final int value) {
+        if (value == 0 || numerator.signum() == 0) {
             return ZERO;
         }
 
-        return multiply(BigInteger.valueOf(i));
+        return multiply(BigInteger.valueOf(value));
     }
 
     /**
-     * Multiply the value of this fraction by the passed {@code long},
-     * returning the result in reduced form.
+     * Multiply this fraction by the passed {@code value}, returning
+     * the result in reduced form.
      *
-     * @param l
-     *            the {@code long} to multiply by.
-     * @return a {@link BigFraction} instance with the resulting values.
+     * @param value Value to multiply by.
+     * @return {@code this * value}.
      */
-    public BigFraction multiply(final long l) {
-        if (l == 0 || numerator.signum() == 0) {
+    public BigFraction multiply(final long value) {
+        if (value == 0 || numerator.signum() == 0) {
             return ZERO;
         }
 
-        return multiply(BigInteger.valueOf(l));
+        return multiply(BigInteger.valueOf(value));
     }
 
     /**
-     * Multiplies the value of this fraction by the passed
-     * {@code BigInteger}, returning the result in reduced form.
+     * Multiply this fraction by the passed {@code value}, returning
+     * the result in reduced form.
      *
-     * @param bg the {@code BigInteger} to multiply by.
-     * @return a {@code BigFraction} instance with the resulting values.
+     * @param value Value to multiply by.
+     * @return {@code this * value}.
      */
-    public BigFraction multiply(final BigInteger bg) {
-        if (numerator.signum() == 0 || bg.signum() == 0) {
+    public BigFraction multiply(final BigInteger value) {
+        if (numerator.signum() == 0 || value.signum() == 0) {
             return ZERO;
         }
-        return new BigFraction(bg.multiply(numerator), denominator);
+        return new BigFraction(value.multiply(numerator), denominator);
     }
 
     /**
-     * Multiplies the value of this fraction by another, returning the result in
-     * reduced form.
+     * Multiply this fraction by the passed {@code value}, returning
+     * the result in reduced form.
      *
-     * @param fraction Fraction to multiply by, must not be {@code null}.
-     * @return a {@link BigFraction} instance with the resulting values.
+     * @param value Value to multiply by.
+     * @return {@code this * value}.
      */
     @Override
-    public BigFraction multiply(final BigFraction fraction) {
+    public BigFraction multiply(final BigFraction value) {
         if (numerator.signum() == 0 ||
-            fraction.numerator.signum() == 0) {
+            value.numerator.signum() == 0) {
             return ZERO;
         }
-        return new BigFraction(numerator.multiply(fraction.numerator),
-                               denominator.multiply(fraction.denominator));
+        return new BigFraction(numerator.multiply(value.numerator),
+                               denominator.multiply(value.denominator));
     }
 
     /**
-     * Divide the value of this fraction by the passed {@code int}, ie
-     * {@code this * 1 / i}, returning the result in reduced form.
+     * Divide this fraction by the passed {@code value}, returning
+     * the result in reduced form.
      *
-     * @param i the {@code int} to divide by
-     * @return a {@link BigFraction} instance with the resulting values
+     * @param value Value to divide by
+     * @return {@code this / value}.
      * @throws ArithmeticException if the value to divide by is zero
      */
-    public BigFraction divide(final int i) {
-        return divide(BigInteger.valueOf(i));
+    public BigFraction divide(final int value) {
+        return divide(BigInteger.valueOf(value));
     }
 
     /**
-     * Divide the value of this fraction by the passed {@code long}, ie
-     * {@code this * 1 / l}, returning the result in reduced form.
+     * Divide this fraction by the passed {@code value}, returning
+     * the result in reduced form.
      *
-     * @param l the {@code long} to divide by
-     * @return a {@link BigFraction} instance with the resulting values
+     * @param value Value to divide by
+     * @return {@code this / value}.
      * @throws ArithmeticException if the value to divide by is zero
      */
-    public BigFraction divide(final long l) {
-        return divide(BigInteger.valueOf(l));
+    public BigFraction divide(final long value) {
+        return divide(BigInteger.valueOf(value));
     }
 
     /**
-     * Divide the value of this fraction by the passed {@code BigInteger},
-     * ie {@code this * 1 / bg}, returning the result in reduced form.
+     * Divide this fraction by the passed {@code value}, returning
+     * the result in reduced form.
      *
-     * @param bg the {@code BigInteger} to divide by, must not be {@code null}
-     * @return a {@link BigFraction} instance with the resulting values
+     * @param value Value to divide by
+     * @return {@code this / value}.
      * @throws ArithmeticException if the value to divide by is zero
      */
-    public BigFraction divide(final BigInteger bg) {
-        if (bg.signum() == 0) {
+    public BigFraction divide(final BigInteger value) {
+        if (value.signum() == 0) {
             throw new FractionException(FractionException.ERROR_ZERO_DENOMINATOR);
         }
         if (numerator.signum() == 0) {
             return ZERO;
         }
-        return new BigFraction(numerator, denominator.multiply(bg));
+        return new BigFraction(numerator, denominator.multiply(value));
     }
 
     /**
-     * Divide the value of this fraction by another, returning the result in
-     * reduced form.
+     * Divide this fraction by the passed {@code value}, returning
+     * the result in reduced form.
      *
-     * @param fraction Fraction to divide by, must not be {@code null}.
-     * @return a {@link BigFraction} instance with the resulting values.
-     * @throws ArithmeticException if the fraction to divide by is zero
+     * @param value Value to divide by
+     * @return {@code this / value}.
+     * @throws ArithmeticException if the value to divide by is zero
      */
     @Override
-    public BigFraction divide(final BigFraction fraction) {
-        if (fraction.numerator.signum() == 0) {
+    public BigFraction divide(final BigFraction value) {
+        if (value.numerator.signum() == 0) {
             throw new FractionException(FractionException.ERROR_ZERO_DENOMINATOR);
         }
         if (numerator.signum() == 0) {
             return ZERO;
         }
-
-        return multiply(fraction.reciprocal());
+        return multiply(value.reciprocal());
     }
 
     /**
      * Returns a {@code BigFraction} whose value is
-     * {@code (this<sup>exponent</sup>)}, returning the result in reduced form.
+     * <code>this<sup>exponent</sup></code>, returning the result in reduced form.
      *
-     * @param exponent
-     *            exponent to which this {@code BigFraction} is to be
-     *            raised.
-     * @return \(\mathit{this}^{\mathit{exponent}}\).
+     * @param exponent exponent to which this {@code BigFraction} is to be raised.
+     * @return <code>this<sup>exponent</sup></code>.
      */
     @Override
     public BigFraction pow(final int exponent) {
@@ -906,11 +897,10 @@ public final class BigFraction
 
     /**
      * Returns a {@code BigFraction} whose value is
-     * \(\mathit{this}^{\mathit{exponent}}\), returning the result in reduced form.
+     * <code>this<sup>exponent</sup></code>, returning the result in reduced form.
      *
-     * @param exponent
-     *            exponent to which this {@code BigFraction} is to be raised.
-     * @return \(\mathit{this}^{\mathit{exponent}}\) as a {@code BigFraction}.
+     * @param exponent exponent to which this {@code BigFraction} is to be raised.
+     * @return <code>this<sup>exponent</sup></code>.
      */
     public BigFraction pow(final long exponent) {
         if (exponent == 0) {
@@ -930,11 +920,10 @@ public final class BigFraction
 
     /**
      * Returns a {@code BigFraction} whose value is
-     * \(\mathit{this}^{\mathit{exponent}}\), returning the result in reduced form.
+     * <code>this<sup>exponent</sup></code>, returning the result in reduced form.
      *
-     * @param exponent
-     *            exponent to which this {@code BigFraction} is to be raised.
-     * @return \(\mathit{this}^{\mathit{exponent}}\) as a {@code BigFraction}.
+     * @param exponent exponent to which this {@code BigFraction} is to be raised.
+     * @return <code>this<sup>exponent</sup></code>.
      */
     public BigFraction pow(final BigInteger exponent) {
         if (exponent.signum() == 0) {
@@ -954,12 +943,11 @@ public final class BigFraction
     }
 
     /**
-     * Returns a {@code double} whose value is
-     * \(\mathit{this}^{\mathit{exponent}}\), returning the result in reduced form.
+     * Returns a {@code BigFraction} whose value is
+     * <code>this<sup>exponent</sup></code>, returning the result in reduced form.
      *
-     * @param exponent
-     *            exponent to which this {@code BigFraction} is to be raised.
-     * @return \(\mathit{this}^{\mathit{exponent}}\).
+     * @param exponent exponent to which this {@code BigFraction} is to be raised.
+     * @return <code>this<sup>exponent</sup></code>.
      */
     public double pow(final double exponent) {
         return Math.pow(numerator.doubleValue(),   exponent) /
@@ -991,13 +979,10 @@ public final class BigFraction
     }
 
     /**
-     * Compares this object to another based on size.
-     *
-     * @param other Object to compare to, must not be {@code null}.
-     * @return -1 if this is less than {@code object}, +1 if this is greater
-     * than {@code object}, 0 if they are equal.
+     * Compares this object with the specified object for order using the signed magnitude.
      *
-     * @see Comparable#compareTo(Object)
+     * @param other {@inheritDoc}
+     * @return {@inheritDoc}
      */
     @Override
     public int compareTo(final BigFraction other) {
@@ -1017,9 +1002,8 @@ public final class BigFraction
     }
 
     /**
-     * Test for the equality of two fractions. If the lowest term numerator and
-     * denominators are the same for both fractions, the two fractions are
-     * considered to be equal.
+     * Test for equality with another object. If the other object is a {@code Fraction} then a
+     * comparison is made of the sign and magnitude; otherwise {@code false} is returned.
      *
      * @param other {@inheritDoc}
      * @return {@inheritDoc}
@@ -1028,9 +1012,12 @@ public final class BigFraction
     public boolean equals(final Object other) {
         if (this == other) {
             return true;
-        } else if (other instanceof BigFraction) {
-            final BigFraction rhs = (BigFraction) other;
+        }
 
+        if (other instanceof BigFraction) {
+            // Since fractions are always in lowest terms, numerators and
+            // denominators can be compared directly for equality.
+            final BigFraction rhs = (BigFraction) other;
             if (signum() == rhs.signum()) {
                 return numerator.abs().equals(rhs.numerator.abs()) &&
                        denominator.abs().equals(rhs.denominator.abs());
diff --git a/commons-numbers-fraction/src/main/java/org/apache/commons/numbers/fraction/Fraction.java b/commons-numbers-fraction/src/main/java/org/apache/commons/numbers/fraction/Fraction.java
index 0ec2009..389dabe 100644
--- a/commons-numbers-fraction/src/main/java/org/apache/commons/numbers/fraction/Fraction.java
+++ b/commons-numbers-fraction/src/main/java/org/apache/commons/numbers/fraction/Fraction.java
@@ -229,13 +229,12 @@ public final class Fraction
      * Continued Fraction</a> equations (11) and (22)-(26)</li>
      * </ul>
      *
-     * @param value the double value to convert to a fraction.
-     * @param epsilon maximum error allowed.  The resulting fraction is within
+     * @param value Value to convert to a fraction.
+     * @param epsilon Maximum error allowed. The resulting fraction is within
      * {@code epsilon} of {@code value}, in absolute terms.
-     * @param maxIterations maximum number of convergents
+     * @param maxIterations Maximum number of convergents.
      * @throws IllegalArgumentException if the given {@code value} is NaN or infinite.
-     * @throws ArithmeticException if the continued fraction failed to
-     * converge.
+     * @throws ArithmeticException if the continued fraction failed to converge.
      * @return a new instance.
      */
     public static Fraction from(final double value,
@@ -254,11 +253,10 @@ public final class Fraction
      * Continued Fraction</a> equations (11) and (22)-(26)</li>
      * </ul>
      *
-     * @param value the double value to convert to a fraction.
-     * @param maxDenominator The maximum allowed value for denominator
+     * @param value Value to convert to a fraction.
+     * @param maxDenominator Maximum allowed value for denominator.
      * @throws IllegalArgumentException if the given {@code value} is NaN or infinite.
-     * @throws ArithmeticException if the continued fraction failed to
-     * converge.
+     * @throws ArithmeticException if the continued fraction failed to converge.
      * @return a new instance.
      */
     public static Fraction from(final double value,
@@ -291,24 +289,48 @@ public final class Fraction
     }
 
     /**
-     * Parses a string that would be produced by {@link #toString()}
-     * and instantiates the corresponding object.
+     * Returns a {@code Fraction} instance representing the specified string {@code s}.
+     *
+     * <p>If {@code s} is {@code null}, then a {@code NullPointerException} is thrown.
+     *
+     * <p>The string must be in a format compatible with that produced by
+     * {@link #toString() Fraction.toString()}.
+     * The format expects an integer optionally followed by a {@code '/'} character and
+     * and second integer. Leading and trailing spaces are allowed around each numeric part.
+     * Each numeric part is parsed using {@link Integer#parseInt(String)}. The parts
+     * are interpreted as the numerator and optional denominator of the fraction. If absent
+     * the denominator is assumed to be "1".
+     *
+     * <p>Examples of valid strings and the equivalent {@code Fraction} are shown below:
+     *
+     * <pre>
+     * "0"                 = Fraction.of(0)
+     * "42"                = Fraction.of(42)
+     * "0 / 1"             = Fraction.of(0, 1)
+     * "1 / 3"             = Fraction.of(1, 3)
+     * "-4 / 13"           = Fraction.of(-4, 13)</pre>
+     *
+     * <p>Note: The fraction is returned in reduced form and the numerator and denominator
+     * may not match the values in the input string. For this reason the result of
+     * {@code Fraction.parse(s).toString().equals(s)} may not be {@code true}.
      *
      * @param s String representation.
      * @return an instance.
-     * @throws NumberFormatException if the string does not conform to the
-     * specification.
+     * @throws NullPointerException if the string is null.
+     * @throws NumberFormatException if the string does not contain a parsable fraction.
+     * @see Integer#parseInt(String)
+     * @see #toString()
      */
     public static Fraction parse(String s) {
-        final int slashLoc = s.indexOf('/');
+        final String stripped = s.replace(",", "");
+        final int slashLoc = stripped.indexOf('/');
         // if no slash, parse as single number
         if (slashLoc == -1) {
-            return Fraction.of(Integer.parseInt(s.trim()));
-        } else {
-            final int num = Integer.parseInt(s.substring(0, slashLoc).trim());
-            final int denom = Integer.parseInt(s.substring(slashLoc + 1).trim());
-            return of(num, denom);
+            return Fraction.of(Integer.parseInt(stripped.trim()));
         }
+        final int num = Integer.parseInt(stripped.substring(0, slashLoc).trim());
+        final int denom = Integer.parseInt(stripped.substring(slashLoc + 1).trim());
+        return of(num, denom);
     }
 
     @Override
@@ -322,14 +344,18 @@ public final class Fraction
     }
 
     /**
-     * @return the numerator.
+     * Access the numerator as an {@code int}.
+     *
+     * @return the numerator as an {@code int}.
      */
     public int getNumerator() {
         return numerator;
     }
 
     /**
-     * @return the denominator.
+     * Access the denominator as an {@code int}.
+     *
+     * @return the denominator as an {@code int}.
      */
     public int getDenominator() {
         return denominator;
@@ -363,11 +389,6 @@ public final class Fraction
             negate();
     }
 
-    /**
-     * Computes the additive inverse of this fraction.
-     *
-     * @return the opposite.
-     */
     @Override
     public Fraction negate() {
         return numerator == Integer.MIN_VALUE ?
@@ -375,18 +396,13 @@ public final class Fraction
             new Fraction(-numerator, denominator);
     }
 
-    /**
-     * Computes the multiplicative inverse of this fraction.
-     *
-     * @return the reciprocal.
-     */
     @Override
     public Fraction reciprocal() {
         return new Fraction(denominator, numerator);
     }
 
     /**
-     * Retrieves the {@code double} value closest to this fraction.
+     * Returns the {@code double} value closest to this fraction.
      * This calculates the fraction as numerator divided by denominator.
      *
      * @return the fraction as a {@code double}.
@@ -397,7 +413,7 @@ public final class Fraction
     }
 
     /**
-     * Retrieves the {@code float} value closest to this fraction.
+     * Returns the {@code float} value closest to this fraction.
      * This calculates the fraction as numerator divided by denominator.
      *
      * @return the fraction as {@code float}.
@@ -408,10 +424,9 @@ public final class Fraction
     }
 
     /**
-     * Retrieves the whole number part of the fraction.
+     * Returns the whole number part of the fraction.
      *
-     * @return the largest {@code int} value that is not larger than
-     * this fraction.
+     * @return the largest {@code int} value that is not larger than this fraction.
      */
     @Override
     public int intValue() {
@@ -419,10 +434,9 @@ public final class Fraction
     }
 
     /**
-     * Retrieves the whole number part of the fraction.
+     * Returns the whole number part of the fraction.
      *
-     * @return the largest {@code long} value that is not larger than
-     * this fraction.
+     * @return the largest {@code long} value that is not larger than this fraction.
      */
     @Override
     public long longValue() {
@@ -430,70 +444,75 @@ public final class Fraction
     }
 
     /**
-     * Adds an integer to the fraction.
+     * Adds the specified {@code value} to this fraction, returning
+     * the result in reduced form.
      *
-     * @param i Value to add.
-     * @return {@code this + i}.
+     * @param value Value to add.
+     * @return {@code this + value}.
+     * @throws ArithmeticException if the resulting numerator or denominator
+     * cannot be represented in an {@code int}.
      */
-    public Fraction add(final int i) {
-        return new Fraction(numerator + i * denominator, denominator);
+    public Fraction add(final int value) {
+        return new Fraction(numerator + value * denominator, denominator);
     }
 
     /**
-     * Adds the value of this fraction to another, returning the result
-     * in reduced form.
-     * The algorithm follows Knuth, 4.5.1.
+     * Adds the specified {@code value} to this fraction, returning
+     * the result in reduced form.
      *
-     * @param fraction Fraction to add.
-     * @return a new instance.
+     * @param value Value to add.
+     * @return {@code this + value}.
      * @throws ArithmeticException if the resulting numerator or denominator
      * cannot be represented in an {@code int}.
      */
     @Override
-    public Fraction add(Fraction fraction) {
-        return addSub(fraction, true /* add */);
+    public Fraction add(Fraction value) {
+        return addSub(value, true /* add */);
     }
 
     /**
-     * Subtracts an integer from this fraction.
+     * Subtracts the specified {@code value} from this fraction, returning
+     * the result in reduced form.
      *
-     * @param i Value to subtract.
-     * @return {@code this - i}.
+     * @param value Value to subtract.
+     * @return {@code this - value}.
+     * @throws ArithmeticException if the resulting numerator or denominator
+     * cannot be represented in an {@code int}.
      */
-    public Fraction subtract(final int i) {
-        return new Fraction(numerator - i * denominator, denominator);
+    public Fraction subtract(final int value) {
+        return new Fraction(numerator - value * denominator, denominator);
     }
 
     /**
-     * Subtracts the value of another fraction from the value of this one,
-     * returning the result in reduced form.
+     * Subtracts the specified {@code value} from this fraction, returning
+     * the result in reduced form.
      *
-     * @param fraction Fraction to subtract.
-     * @return a new instance.
+     * @param value Value to subtract.
+     * @return {@code this - value}.
      * @throws ArithmeticException if the resulting numerator or denominator
      * cannot be represented in an {@code int}.
      */
     @Override
-    public Fraction subtract(Fraction fraction) {
-        return addSub(fraction, false /* subtract */);
+    public Fraction subtract(Fraction value) {
+        return addSub(value, false /* subtract */);
     }
 
     /**
      * Implements add and subtract using algorithm described in Knuth 4.5.1.
      *
-     * @param fraction Fraction to add or subtract.
+     * @param value Fraction to add or subtract.
      * @param isAdd Whether the operation is "add" or "subtract".
      * @return a new instance.
      * @throws ArithmeticException if the resulting numerator or denominator
      * cannot be represented in an {@code int}.
      */
-    private Fraction addSub(Fraction fraction, boolean isAdd) {
+    private Fraction addSub(Fraction value, boolean isAdd) {
         // Zero is identity for addition.
         if (numerator == 0) {
-            return isAdd ? fraction : fraction.negate();
+            return isAdd ? value : value.negate();
         }
 
-        if (fraction.numerator == 0) {
+        if (value.numerator == 0) {
             return this;
         }
 
@@ -503,9 +522,9 @@ public final class Fraction
          *
          * t = u(v'/d1) +/- v(u'/d1)
          */
-        final int d1 = ArithmeticUtils.gcd(denominator, fraction.denominator);
-        final long uvp = (long) numerator * (long) (fraction.denominator / d1);
-        final long upv = (long) fraction.numerator * (long) (denominator / d1);
+        final int d1 = ArithmeticUtils.gcd(denominator, value.denominator);
+        final long uvp = (long) numerator * (long) (value.denominator / d1);
+        final long upv = (long) value.numerator * (long) (denominator / d1);
 
         /*
          * The largest possible absolute value of a product of two ints is 2^62,
@@ -527,77 +546,86 @@ public final class Fraction
         // result is (t/d2) / (u'/d1)(v'/d2)
         return of(Math.toIntExact(t / d2),
                   Math.multiplyExact(denominator / d1,
-                                     fraction.denominator / (int) d2));
+                                     value.denominator / (int) d2));
     }
 
     /**
-     * Multiplies the fraction by an integer.
+     * Multiply this fraction by the passed {@code value}, returning
+     * the result in reduced form.
      *
-     * @param i Value to multiply by.
-     * @return {@code this * i}.
+     * @param value Value to multiply by.
+     * @return {@code this * value}.
+     * @throws ArithmeticException if the resulting numerator or denominator
+     * cannot be represented in an {@code int}.
      */
     @Override
-    public Fraction multiply(final int i) {
-        return multiply(of(i));
+    public Fraction multiply(final int value) {
+        return multiply(of(value));
     }
 
     /**
-     * Multiplies the value of this fraction by another, returning the
-     * result in reduced form.
+     * Multiply this fraction by the passed {@code value}, returning
+     * the result in reduced form.
      *
-     * @param fraction Fraction to multiply by.
-     * @return a new instance.
+     * @param value Value to multiply by.
+     * @return {@code this * value}.
      * @throws ArithmeticException if the resulting numerator or denominator
      * cannot be represented in an {@code int}.
      */
     @Override
-    public Fraction multiply(Fraction fraction) {
+    public Fraction multiply(Fraction value) {
         if (numerator == 0 ||
-            fraction.numerator == 0) {
+            value.numerator == 0) {
             return ZERO;
         }
 
         // knuth 4.5.1
         // Make sure we don't overflow unless the result *must* overflow.
-        final int d1 = ArithmeticUtils.gcd(numerator, fraction.denominator);
-        final int d2 = ArithmeticUtils.gcd(fraction.numerator, denominator);
-        return of(Math.multiplyExact(numerator / d1, fraction.numerator / d2),
-                  Math.multiplyExact(denominator / d2, fraction.denominator / d1));
+        final int d1 = ArithmeticUtils.gcd(numerator, value.denominator);
+        final int d2 = ArithmeticUtils.gcd(value.numerator, denominator);
+        return of(Math.multiplyExact(numerator / d1, value.numerator / d2),
+                  Math.multiplyExact(denominator / d2, value.denominator / d1));
     }
 
     /**
-     * Divides the fraction by an integer.
+     * Divide this fraction by the passed {@code value}, returning
+     * the result in reduced form.
      *
-     * @param i Value to divide by.
-     * @return {@code this * i}.
+     * @param value Value to divide by
+     * @return {@code this / value}.
+     * @throws ArithmeticException if the value to divide by is zero
+     * or if the resulting numerator or denominator cannot be represented
+     * by an {@code int}.
      */
-    public Fraction divide(final int i) {
-        return divide(of(i));
+    public Fraction divide(final int value) {
+        return divide(of(value));
     }
 
     /**
-     * Divides the value of this fraction by another.
+     * Divide this fraction by the passed {@code value}, returning
+     * the result in reduced form.
      *
-     * @param fraction Fraction to divide by.
-     * @return a new instance.
-     * @throws ArithmeticException if the fraction to divide by is zero
+     * @param value Value to divide by
+     * @return {@code this / value}.
+     * @throws ArithmeticException if the value to divide by is zero
      * or if the resulting numerator or denominator cannot be represented
      * by an {@code int}.
      */
     @Override
-    public Fraction divide(Fraction fraction) {
-        if (fraction.numerator == 0) {
+    public Fraction divide(Fraction value) {
+        if (value.numerator == 0) {
             throw new FractionException("the fraction to divide by must not be zero: {0}/{1}",
-                                        fraction.numerator, fraction.denominator);
+                                        value.numerator, value.denominator);
         }
 
-        return multiply(fraction.reciprocal());
+        return multiply(value.reciprocal());
     }
 
     /**
-     * {@inheritDoc}
+     * Returns a {@code Fraction} whose value is
+     * <code>this<sup>exponent</sup></code>, returning the result in reduced form.
      *
-     * @param exponent {@inheritDoc}
+     * @param exponent exponent to which this {@code Fraction} is to be raised.
      * @return <code>this<sup>exponent</sup></code>.
      */
     @Override
@@ -671,7 +699,7 @@ public final class Fraction
             final Fraction rhs = (Fraction) other;
             if (signum() == rhs.signum()) {
                 return Math.abs(numerator) == Math.abs(rhs.numerator) &&
-                    Math.abs(denominator) == Math.abs(rhs.denominator);
+                       Math.abs(denominator) == Math.abs(rhs.denominator);
             }
         }
 


[commons-numbers] 09/09: PMD: Allow certain violations in Fraction/BigFraction

Posted by ah...@apache.org.
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 233223542e392be0055edddfe7bcc54f5e49300f
Author: aherbert <ah...@apache.org>
AuthorDate: Tue Apr 7 13:40:09 2020 +0100

    PMD: Allow certain violations in Fraction/BigFraction
    
    Allow field ZERO and ONE to match method name in Fraction.
    
    Allow GodClass and ExcessiveMethodLength for BigFraction.
---
 src/main/resources/pmd/pmd-ruleset.xml | 10 +++++++---
 1 file changed, 7 insertions(+), 3 deletions(-)

diff --git a/src/main/resources/pmd/pmd-ruleset.xml b/src/main/resources/pmd/pmd-ruleset.xml
index 5ee62ef..7d51f4a 100644
--- a/src/main/resources/pmd/pmd-ruleset.xml
+++ b/src/main/resources/pmd/pmd-ruleset.xml
@@ -109,7 +109,8 @@
   <rule ref="category/java/design.xml/GodClass">
     <properties>
       <property name="violationSuppressXPath"
-        value="//ClassOrInterfaceType[@Image='Fraction']"/>
+        value="//ClassOrInterfaceType[@Image='Fraction'
+               or @Image='BigFraction']"/>
     </properties>
   </rule>
 
@@ -127,7 +128,9 @@
   <rule ref="category/java/errorprone.xml/AvoidFieldNameMatchingMethodName">
     <properties>
       <property name="violationSuppressXPath"
-        value="//ClassOrInterfaceType[@Image='Complex']"/>
+        value="//ClassOrInterfaceType[@Image='Complex'
+               or @Image='Fraction'
+               or @Image='BigFraction']"/>
     </properties>
   </rule>
 
@@ -135,7 +138,8 @@
   <rule ref="category/java/design.xml/ExcessiveMethodLength">
     <properties>
       <property name="violationSuppressXPath"
-        value="//ClassOrInterfaceType[@Image='Complex']"/>
+        value="//ClassOrInterfaceType[@Image='Complex'
+               or @Image='BigFraction']"/>
     </properties>
   </rule>