BigFraction.java

  1. /*
  2.  * Licensed to the Apache Software Foundation (ASF) under one or more
  3.  * contributor license agreements.  See the NOTICE file distributed with
  4.  * this work for additional information regarding copyright ownership.
  5.  * The ASF licenses this file to You under the Apache License, Version 2.0
  6.  * (the "License"); you may not use this file except in compliance with
  7.  * the License.  You may obtain a copy of the License at
  8.  *
  9.  *      http://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  * Unless required by applicable law or agreed to in writing, software
  12.  * distributed under the License is distributed on an "AS IS" BASIS,
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  * See the License for the specific language governing permissions and
  15.  * limitations under the License.
  16.  */
  17. package org.apache.commons.numbers.fraction;

  18. import java.io.Serializable;
  19. import java.math.BigDecimal;
  20. import java.math.BigInteger;
  21. import java.math.RoundingMode;
  22. import java.util.Objects;
  23. import org.apache.commons.numbers.core.NativeOperators;

  24. /**
  25.  * Representation of a rational number using arbitrary precision.
  26.  *
  27.  * <p>The number is expressed as the quotient {@code p/q} of two {@link BigInteger}s,
  28.  * a numerator {@code p} and a non-zero denominator {@code q}.
  29.  *
  30.  * <p>This class is immutable.
  31.  *
  32.  * <a href="https://en.wikipedia.org/wiki/Rational_number">Rational number</a>
  33.  */
  34. public final class BigFraction
  35.     extends Number
  36.     implements Comparable<BigFraction>,
  37.                NativeOperators<BigFraction>,
  38.                Serializable {
  39.     /** A fraction representing "0". */
  40.     public static final BigFraction ZERO = new BigFraction(BigInteger.ZERO);

  41.     /** A fraction representing "1". */
  42.     public static final BigFraction ONE = new BigFraction(BigInteger.ONE);

  43.     /** Serializable version identifier. */
  44.     private static final long serialVersionUID = 20190701L;

  45.     /** The default iterations used for convergence. */
  46.     private static final int DEFAULT_MAX_ITERATIONS = 100;

  47.     /** Message for non-finite input double argument to factory constructors. */
  48.     private static final String NOT_FINITE = "Not finite: ";

  49.     /** The overflow limit for conversion from a double (2^31). */
  50.     private static final long OVERFLOW = 1L << 31;

  51.     /** The numerator of this fraction reduced to lowest terms. */
  52.     private final BigInteger numerator;

  53.     /** The denominator of this fraction reduced to lowest terms. */
  54.     private final BigInteger denominator;

  55.     /**
  56.      * Private constructor: Instances are created using factory methods.
  57.      *
  58.      * <p>This constructor should only be invoked when the fraction is known
  59.      * to be non-zero; otherwise use {@link #ZERO}. This avoids creating
  60.      * the zero representation {@code 0 / -1}.
  61.      *
  62.      * @param num Numerator, must not be {@code null}.
  63.      * @param den Denominator, must not be {@code null}.
  64.      * @throws ArithmeticException if the denominator is zero.
  65.      */
  66.     private BigFraction(BigInteger num, BigInteger den) {
  67.         if (den.signum() == 0) {
  68.             throw new FractionException(FractionException.ERROR_ZERO_DENOMINATOR);
  69.         }

  70.         // reduce numerator and denominator by greatest common denominator
  71.         final BigInteger gcd = num.gcd(den);
  72.         if (BigInteger.ONE.compareTo(gcd) < 0) {
  73.             numerator = num.divide(gcd);
  74.             denominator = den.divide(gcd);
  75.         } else {
  76.             numerator = num;
  77.             denominator = den;
  78.         }
  79.     }

  80.     /**
  81.      * Private constructor: Instances are created using factory methods.
  82.      *
  83.      * <p>This sets the denominator to 1.
  84.      *
  85.      * @param num Numerator (must not be null).
  86.      */
  87.     private BigFraction(BigInteger num) {
  88.         numerator = num;
  89.         denominator = BigInteger.ONE;
  90.     }

  91.     /**
  92.      * Create a fraction given the double value and either the maximum
  93.      * error allowed or the maximum number of denominator digits.
  94.      *
  95.      * <p>
  96.      * NOTE: This method is called with:
  97.      * </p>
  98.      * <ul>
  99.      *  <li>EITHER a valid epsilon value and the maxDenominator set to
  100.      *      Integer.MAX_VALUE (that way the maxDenominator has no effect)
  101.      *  <li>OR a valid maxDenominator value and the epsilon value set to
  102.      *      zero (that way epsilon only has effect if there is an exact
  103.      *      match before the maxDenominator value is reached).
  104.      * </ul>
  105.      * <p>
  106.      * It has been done this way so that the same code can be reused for
  107.      * both scenarios. However this could be confusing to users if it
  108.      * were part of the public API and this method should therefore remain
  109.      * PRIVATE.
  110.      * </p>
  111.      *
  112.      * <p>
  113.      * See JIRA issue ticket MATH-181 for more details:
  114.      *     https://issues.apache.org/jira/browse/MATH-181
  115.      * </p>
  116.      *
  117.      * @param value Value to convert to a fraction.
  118.      * @param epsilon Maximum error allowed.
  119.      * The resulting fraction is within {@code epsilon} of {@code value},
  120.      * in absolute terms.
  121.      * @param maxDenominator Maximum denominator value allowed.
  122.      * @param maxIterations Maximum number of convergents.
  123.      * @return a new instance.
  124.      * @throws IllegalArgumentException if the given {@code value} is NaN or infinite.
  125.      * @throws ArithmeticException if the continued fraction failed to converge.
  126.      */
  127.     private static BigFraction from(final double value,
  128.                                     final double epsilon,
  129.                                     final int maxDenominator,
  130.                                     final int maxIterations) {
  131.         if (!Double.isFinite(value)) {
  132.             throw new IllegalArgumentException(NOT_FINITE + value);
  133.         }
  134.         if (value == 0) {
  135.             return ZERO;
  136.         }

  137.         // Remove sign, this is restored at the end.
  138.         // (Assumes the value is not zero and thus signum(value) is not zero).
  139.         final double absValue = Math.abs(value);
  140.         double r0 = absValue;
  141.         long a0 = (long) Math.floor(r0);
  142.         if (a0 > OVERFLOW) {
  143.             throw new FractionException(FractionException.ERROR_CONVERSION_OVERFLOW, value, a0, 1);
  144.         }

  145.         // check for (almost) integer arguments, which should not go to iterations.
  146.         if (r0 - a0 <= epsilon) {
  147.             // Restore the sign.
  148.             if (value < 0) {
  149.                 a0 = -a0;
  150.             }
  151.             return new BigFraction(BigInteger.valueOf(a0));
  152.         }

  153.         // Support 2^31 as maximum denominator.
  154.         // This is negative as an integer so convert to long.
  155.         final long maxDen = Math.abs((long) maxDenominator);

  156.         long p0 = 1;
  157.         long q0 = 0;
  158.         long p1 = a0;
  159.         long q1 = 1;

  160.         long p2;
  161.         long q2;

  162.         int n = 0;
  163.         boolean stop = false;
  164.         do {
  165.             ++n;
  166.             final double r1 = 1.0 / (r0 - a0);
  167.             final long a1 = (long) Math.floor(r1);
  168.             p2 = (a1 * p1) + p0;
  169.             q2 = (a1 * q1) + q0;
  170.             if (Long.compareUnsigned(p2, OVERFLOW) > 0 ||
  171.                 Long.compareUnsigned(q2, OVERFLOW) > 0) {
  172.                 // In maxDenominator mode, fall-back to the previous valid fraction.
  173.                 if (epsilon == 0) {
  174.                     p2 = p1;
  175.                     q2 = q1;
  176.                     break;
  177.                 }
  178.                 throw new FractionException(FractionException.ERROR_CONVERSION_OVERFLOW, value, p2, q2);
  179.             }

  180.             final double convergent = (double) p2 / (double) q2;
  181.             if (n < maxIterations &&
  182.                 Math.abs(convergent - absValue) > epsilon &&
  183.                 q2 < maxDen) {
  184.                 p0 = p1;
  185.                 p1 = p2;
  186.                 q0 = q1;
  187.                 q1 = q2;
  188.                 a0 = a1;
  189.                 r0 = r1;
  190.             } else {
  191.                 stop = true;
  192.             }
  193.         } while (!stop);

  194.         if (n >= maxIterations) {
  195.             throw new FractionException(FractionException.ERROR_CONVERSION, value, maxIterations);
  196.         }

  197.         // Use p2 / q2 or p1 / q1 if q2 has grown too large in maxDenominator mode
  198.         long num;
  199.         long den;
  200.         if (q2 <= maxDen) {
  201.             num = p2;
  202.             den = q2;
  203.         } else {
  204.             num = p1;
  205.             den = q1;
  206.         }

  207.         // Restore the sign.
  208.         if (Math.signum(num) * Math.signum(den) != Math.signum(value)) {
  209.             num = -num;
  210.         }

  211.         return new BigFraction(BigInteger.valueOf(num),
  212.                                BigInteger.valueOf(den));
  213.     }

  214.     /**
  215.      * Create a fraction given the double value.
  216.      * <p>
  217.      * This factory method behaves <em>differently</em> to the method
  218.      * {@link #from(double, double, int)}. It converts the double value
  219.      * exactly, considering its internal bits representation. This works for all
  220.      * values except NaN and infinities and does not requires any loop or
  221.      * convergence threshold.
  222.      * </p>
  223.      * <p>
  224.      * Since this conversion is exact and since double numbers are sometimes
  225.      * approximated, the fraction created may seem strange in some cases. For example,
  226.      * calling {@code from(1.0 / 3.0)} does <em>not</em> create
  227.      * the fraction \( \frac{1}{3} \), but the fraction \( \frac{6004799503160661}{18014398509481984} \)
  228.      * because the double number passed to the method is not exactly \( \frac{1}{3} \)
  229.      * (which cannot be represented exactly in IEEE754).
  230.      * </p>
  231.      *
  232.      * @param value Value to convert to a fraction.
  233.      * @throws IllegalArgumentException if the given {@code value} is NaN or infinite.
  234.      * @return a new instance.
  235.      *
  236.      * @see #from(double,double,int)
  237.      */
  238.     public static BigFraction from(final double value) {
  239.         if (!Double.isFinite(value)) {
  240.             throw new IllegalArgumentException(NOT_FINITE + value);
  241.         }
  242.         if (value == 0) {
  243.             return ZERO;
  244.         }

  245.         final long bits = Double.doubleToLongBits(value);
  246.         final long sign = bits & 0x8000000000000000L;
  247.         final long exponent = bits & 0x7ff0000000000000L;
  248.         final long mantissa = bits & 0x000fffffffffffffL;

  249.         // Compute m and k such that value = m * 2^k
  250.         long m;
  251.         int k;

  252.         if (exponent == 0) {
  253.             // Subnormal number, the effective exponent bias is 1022, not 1023.
  254.             // Note: mantissa is never zero as that case has been eliminated.
  255.             m = mantissa;
  256.             k = -1074;
  257.         } else {
  258.             // Normalized number: Add the implicit most significant bit.
  259.             m = mantissa | 0x0010000000000000L;
  260.             k = ((int) (exponent >> 52)) - 1075; // Exponent bias is 1023.
  261.         }
  262.         if (sign != 0) {
  263.             m = -m;
  264.         }
  265.         while ((m & 0x001ffffffffffffeL) != 0 &&
  266.                (m & 0x1) == 0) {
  267.             m >>= 1;
  268.             ++k;
  269.         }

  270.         return k < 0 ?
  271.             new BigFraction(BigInteger.valueOf(m),
  272.                             BigInteger.ZERO.flipBit(-k)) :
  273.             new BigFraction(BigInteger.valueOf(m).multiply(BigInteger.ZERO.flipBit(k)),
  274.                             BigInteger.ONE);
  275.     }

  276.     /**
  277.      * Create a fraction given the double value and maximum error allowed.
  278.      * <p>
  279.      * References:
  280.      * <ul>
  281.      * <li><a href="http://mathworld.wolfram.com/ContinuedFraction.html">
  282.      * Continued Fraction</a> equations (11) and (22)-(26)</li>
  283.      * </ul>
  284.      *
  285.      * @param value Value to convert to a fraction.
  286.      * @param epsilon Maximum error allowed. The resulting fraction is within
  287.      * {@code epsilon} of {@code value}, in absolute terms.
  288.      * @param maxIterations Maximum number of convergents.
  289.      * @throws IllegalArgumentException if the given {@code value} is NaN or infinite;
  290.      * {@code epsilon} is not positive; or {@code maxIterations < 1}.
  291.      * @throws ArithmeticException if the continued fraction failed to converge.
  292.      * @return a new instance.
  293.      */
  294.     public static BigFraction from(final double value,
  295.                                    final double epsilon,
  296.                                    final int maxIterations) {
  297.         if (maxIterations < 1) {
  298.             throw new IllegalArgumentException("Max iterations must be strictly positive: " + maxIterations);
  299.         }
  300.         if (epsilon >= 0) {
  301.             return from(value, epsilon, Integer.MIN_VALUE, maxIterations);
  302.         }
  303.         throw new IllegalArgumentException("Epsilon must be positive: " + maxIterations);
  304.     }

  305.     /**
  306.      * Create a fraction given the double value and maximum denominator.
  307.      *
  308.      * <p>
  309.      * References:
  310.      * <ul>
  311.      * <li><a href="http://mathworld.wolfram.com/ContinuedFraction.html">
  312.      * Continued Fraction</a> equations (11) and (22)-(26)</li>
  313.      * </ul>
  314.      *
  315.      * <p>Note: The magnitude of the {@code maxDenominator} is used allowing use of
  316.      * {@link Integer#MIN_VALUE} for a supported maximum denominator of 2<sup>31</sup>.
  317.      *
  318.      * @param value Value to convert to a fraction.
  319.      * @param maxDenominator Maximum allowed value for denominator.
  320.      * @throws IllegalArgumentException if the given {@code value} is NaN or infinite
  321.      * or {@code maxDenominator} is zero.
  322.      * @throws ArithmeticException if the continued fraction failed to converge.
  323.      * @return a new instance.
  324.      */
  325.     public static BigFraction from(final double value,
  326.                                    final int maxDenominator) {
  327.         if (maxDenominator == 0) {
  328.             // Re-use the zero denominator message
  329.             throw new IllegalArgumentException(FractionException.ERROR_ZERO_DENOMINATOR);
  330.         }
  331.         return from(value, 0, maxDenominator, DEFAULT_MAX_ITERATIONS);
  332.     }

  333.     /**
  334.      * Create a fraction given the numerator. The denominator is {@code 1}.
  335.      *
  336.      * @param num
  337.      *            the numerator.
  338.      * @return a new instance.
  339.      */
  340.     public static BigFraction of(final int num) {
  341.         if (num == 0) {
  342.             return ZERO;
  343.         }
  344.         return new BigFraction(BigInteger.valueOf(num));
  345.     }

  346.     /**
  347.      * Create a fraction given the numerator. The denominator is {@code 1}.
  348.      *
  349.      * @param num Numerator.
  350.      * @return a new instance.
  351.      */
  352.     public static BigFraction of(final long num) {
  353.         if (num == 0) {
  354.             return ZERO;
  355.         }
  356.         return new BigFraction(BigInteger.valueOf(num));
  357.     }

  358.     /**
  359.      * Create a fraction given the numerator. The denominator is {@code 1}.
  360.      *
  361.      * @param num Numerator.
  362.      * @return a new instance.
  363.      * @throws NullPointerException if numerator is null.
  364.      */
  365.     public static BigFraction of(final BigInteger num) {
  366.         Objects.requireNonNull(num, "numerator");
  367.         if (num.signum() == 0) {
  368.             return ZERO;
  369.         }
  370.         return new BigFraction(num);
  371.     }

  372.     /**
  373.      * Create a fraction given the numerator and denominator.
  374.      * The fraction is reduced to lowest terms.
  375.      *
  376.      * @param num Numerator.
  377.      * @param den Denominator.
  378.      * @return a new instance.
  379.      * @throws ArithmeticException if {@code den} is zero.
  380.      */
  381.     public static BigFraction of(final int num, final int den) {
  382.         if (num == 0) {
  383.             return ZERO;
  384.         }
  385.         return new BigFraction(BigInteger.valueOf(num), BigInteger.valueOf(den));
  386.     }

  387.     /**
  388.      * Create a fraction given the numerator and denominator.
  389.      * The fraction is reduced to lowest terms.
  390.      *
  391.      * @param num Numerator.
  392.      * @param den Denominator.
  393.      * @return a new instance.
  394.      * @throws ArithmeticException if {@code den} is zero.
  395.      */
  396.     public static BigFraction of(final long num, final long den) {
  397.         if (num == 0) {
  398.             return ZERO;
  399.         }
  400.         return new BigFraction(BigInteger.valueOf(num), BigInteger.valueOf(den));
  401.     }

  402.     /**
  403.      * Create a fraction given the numerator and denominator.
  404.      * The fraction is reduced to lowest terms.
  405.      *
  406.      * @param num Numerator.
  407.      * @param den Denominator.
  408.      * @return a new instance.
  409.      * @throws NullPointerException if numerator or denominator are null.
  410.      * @throws ArithmeticException if the denominator is zero.
  411.      */
  412.     public static BigFraction of(final BigInteger num, final BigInteger den) {
  413.         if (num.signum() == 0) {
  414.             return ZERO;
  415.         }
  416.         return new BigFraction(num, den);
  417.     }

  418.     /**
  419.      * Returns a {@code BigFraction} instance representing the specified string {@code s}.
  420.      *
  421.      * <p>If {@code s} is {@code null}, then a {@code NullPointerException} is thrown.
  422.      *
  423.      * <p>The string must be in a format compatible with that produced by
  424.      * {@link #toString() BigFraction.toString()}.
  425.      * The format expects an integer optionally followed by a {@code '/'} character and
  426.      * and second integer. Leading and trailing spaces are allowed around each numeric part.
  427.      * Each numeric part is parsed using {@link BigInteger#BigInteger(String)}. The parts
  428.      * are interpreted as the numerator and optional denominator of the fraction. If absent
  429.      * the denominator is assumed to be "1".
  430.      *
  431.      * <p>Examples of valid strings and the equivalent {@code BigFraction} are shown below:
  432.      *
  433.      * <pre>
  434.      * "0"                 = BigFraction.of(0)
  435.      * "42"                = BigFraction.of(42)
  436.      * "0 / 1"             = BigFraction.of(0, 1)
  437.      * "1 / 3"             = BigFraction.of(1, 3)
  438.      * "-4 / 13"           = BigFraction.of(-4, 13)</pre>
  439.      *
  440.      * <p>Note: The fraction is returned in reduced form and the numerator and denominator
  441.      * may not match the values in the input string. For this reason the result of
  442.      * {@code BigFraction.parse(s).toString().equals(s)} may not be {@code true}.
  443.      *
  444.      * @param s String representation.
  445.      * @return an instance.
  446.      * @throws NullPointerException if the string is null.
  447.      * @throws NumberFormatException if the string does not contain a parsable fraction.
  448.      * @see BigInteger#BigInteger(String)
  449.      * @see #toString()
  450.      */
  451.     public static BigFraction parse(String s) {
  452.         final String stripped = s.replace(",", "");
  453.         final int slashLoc = stripped.indexOf('/');
  454.         // if no slash, parse as single number
  455.         if (slashLoc == -1) {
  456.             return of(new BigInteger(stripped.trim()));
  457.         }
  458.         final BigInteger num = new BigInteger(stripped.substring(0, slashLoc).trim());
  459.         final BigInteger denom = new BigInteger(stripped.substring(slashLoc + 1).trim());
  460.         return of(num, denom);
  461.     }

  462.     @Override
  463.     public BigFraction zero() {
  464.         return ZERO;
  465.     }

  466.     /** {@inheritDoc} */
  467.     @Override
  468.     public boolean isZero() {
  469.         return numerator.signum() == 0;
  470.     }

  471.     @Override
  472.     public BigFraction one() {
  473.         return ONE;
  474.     }

  475.     /** {@inheritDoc} */
  476.     @Override
  477.     public boolean isOne() {
  478.         return numerator.equals(denominator);
  479.     }

  480.     /**
  481.      * Access the numerator as a {@code BigInteger}.
  482.      *
  483.      * @return the numerator as a {@code BigInteger}.
  484.      */
  485.     public BigInteger getNumerator() {
  486.         return numerator;
  487.     }

  488.     /**
  489.      * Access the numerator as an {@code int}.
  490.      *
  491.      * @return the numerator as an {@code int}.
  492.      */
  493.     public int getNumeratorAsInt() {
  494.         return numerator.intValue();
  495.     }

  496.     /**
  497.      * Access the numerator as a {@code long}.
  498.      *
  499.      * @return the numerator as a {@code long}.
  500.      */
  501.     public long getNumeratorAsLong() {
  502.         return numerator.longValue();
  503.     }

  504.     /**
  505.      * Access the denominator as a {@code BigInteger}.
  506.      *
  507.      * @return the denominator as a {@code BigInteger}.
  508.      */
  509.     public BigInteger getDenominator() {
  510.         return denominator;
  511.     }

  512.     /**
  513.      * Access the denominator as an {@code int}.
  514.      *
  515.      * @return the denominator as an {@code int}.
  516.      */
  517.     public int getDenominatorAsInt() {
  518.         return denominator.intValue();
  519.     }

  520.     /**
  521.      * Access the denominator as a {@code long}.
  522.      *
  523.      * @return the denominator as a {@code long}.
  524.      */
  525.     public long getDenominatorAsLong() {
  526.         return denominator.longValue();
  527.     }

  528.     /**
  529.      * Retrieves the sign of this fraction.
  530.      *
  531.      * @return -1 if the value is strictly negative, 1 if it is strictly
  532.      * positive, 0 if it is 0.
  533.      */
  534.     public int signum() {
  535.         return numerator.signum() * denominator.signum();
  536.     }

  537.     /**
  538.      * Returns the absolute value of this fraction.
  539.      *
  540.      * @return the absolute value.
  541.      */
  542.     public BigFraction abs() {
  543.         return signum() >= 0 ?
  544.             this :
  545.             negate();
  546.     }

  547.     @Override
  548.     public BigFraction negate() {
  549.         return new BigFraction(numerator.negate(), denominator);
  550.     }

  551.     /**
  552.      * {@inheritDoc}
  553.      *
  554.      * <p>Raises an exception if the fraction is equal to zero.
  555.      *
  556.      * @throws ArithmeticException if the current numerator is {@code zero}
  557.      */
  558.     @Override
  559.     public BigFraction reciprocal() {
  560.         return new BigFraction(denominator, numerator);
  561.     }

  562.     /**
  563.      * Returns the {@code double} value closest to this fraction.
  564.      *
  565.      * @return the fraction as a {@code double}.
  566.      */
  567.     @Override
  568.     public double doubleValue() {
  569.         return Double.longBitsToDouble(toFloatingPointBits(11, 52));
  570.     }

  571.     /**
  572.      * Returns the {@code float} value closest to this fraction.
  573.      *
  574.      * @return the fraction as a {@code double}.
  575.      */
  576.     @Override
  577.     public float floatValue() {
  578.         return Float.intBitsToFloat((int) toFloatingPointBits(8, 23));
  579.     }

  580.     /**
  581.      * Returns the whole number part of the fraction.
  582.      *
  583.      * @return the largest {@code int} value that is not larger than this fraction.
  584.      */
  585.     @Override
  586.     public int intValue() {
  587.         return numerator.divide(denominator).intValue();
  588.     }

  589.     /**
  590.      * Returns the whole number part of the fraction.
  591.      *
  592.      * @return the largest {@code long} value that is not larger than this fraction.
  593.      */
  594.     @Override
  595.     public long longValue() {
  596.         return numerator.divide(denominator).longValue();
  597.     }

  598.     /**
  599.      * Returns the {@code BigDecimal} representation of this fraction.
  600.      * This calculates the fraction as numerator divided by denominator.
  601.      *
  602.      * @return the fraction as a {@code BigDecimal}.
  603.      * @throws ArithmeticException
  604.      *             if the exact quotient does not have a terminating decimal
  605.      *             expansion.
  606.      * @see BigDecimal
  607.      */
  608.     public BigDecimal bigDecimalValue() {
  609.         return new BigDecimal(numerator).divide(new BigDecimal(denominator));
  610.     }

  611.     /**
  612.      * Returns the {@code BigDecimal} representation of this fraction.
  613.      * This calculates the fraction as numerator divided by denominator
  614.      * following the passed rounding mode.
  615.      *
  616.      * @param roundingMode Rounding mode to apply.
  617.      * @return the fraction as a {@code BigDecimal}.
  618.      * @see BigDecimal
  619.      */
  620.     public BigDecimal bigDecimalValue(RoundingMode roundingMode) {
  621.         return new BigDecimal(numerator).divide(new BigDecimal(denominator), roundingMode);
  622.     }

  623.     /**
  624.      * Returns the {@code BigDecimal} representation of this fraction.
  625.      * This calculates the fraction as numerator divided by denominator
  626.      * following the passed scale and rounding mode.
  627.      *
  628.      * @param scale
  629.      *            scale of the {@code BigDecimal} quotient to be returned.
  630.      *            see {@link BigDecimal} for more information.
  631.      * @param roundingMode Rounding mode to apply.
  632.      * @return the fraction as a {@code BigDecimal}.
  633.      * @throws ArithmeticException if {@code roundingMode} == {@link RoundingMode#UNNECESSARY} and
  634.      *      the specified scale is insufficient to represent the result of the division exactly.
  635.      * @see BigDecimal
  636.      */
  637.     public BigDecimal bigDecimalValue(final int scale, RoundingMode roundingMode) {
  638.         return new BigDecimal(numerator).divide(new BigDecimal(denominator), scale, roundingMode);
  639.     }

  640.     /**
  641.      * Adds the specified {@code value} to this fraction, returning
  642.      * the result in reduced form.
  643.      *
  644.      * @param value Value to add.
  645.      * @return {@code this + value}.
  646.      */
  647.     public BigFraction add(final int value) {
  648.         return add(BigInteger.valueOf(value));
  649.     }

  650.     /**
  651.      * Adds the specified {@code value} to this fraction, returning
  652.      * the result in reduced form.
  653.      *
  654.      * @param value Value to add.
  655.      * @return {@code this + value}.
  656.      */
  657.     public BigFraction add(final long value) {
  658.         return add(BigInteger.valueOf(value));
  659.     }

  660.     /**
  661.      * Adds the specified {@code value} to this fraction, returning
  662.      * the result in reduced form.
  663.      *
  664.      * @param value Value to add.
  665.      * @return {@code this + value}.
  666.      */
  667.     public BigFraction add(final BigInteger value) {
  668.         if (value.signum() == 0) {
  669.             return this;
  670.         }
  671.         if (isZero()) {
  672.             return of(value);
  673.         }

  674.         return of(numerator.add(denominator.multiply(value)), denominator);
  675.     }

  676.     /**
  677.      * Adds the specified {@code value} to this fraction, returning
  678.      * the result in reduced form.
  679.      *
  680.      * @param value Value to add.
  681.      * @return {@code this + value}.
  682.      */
  683.     @Override
  684.     public BigFraction add(final BigFraction value) {
  685.         if (value.isZero()) {
  686.             return this;
  687.         }
  688.         if (isZero()) {
  689.             return value;
  690.         }

  691.         final BigInteger num;
  692.         final BigInteger den;

  693.         if (denominator.equals(value.denominator)) {
  694.             num = numerator.add(value.numerator);
  695.             den = denominator;
  696.         } else {
  697.             num = (numerator.multiply(value.denominator)).add((value.numerator).multiply(denominator));
  698.             den = denominator.multiply(value.denominator);
  699.         }

  700.         if (num.signum() == 0) {
  701.             return ZERO;
  702.         }

  703.         return new BigFraction(num, den);
  704.     }

  705.     /**
  706.      * Subtracts the specified {@code value} from this fraction, returning
  707.      * the result in reduced form.
  708.      *
  709.      * @param value Value to subtract.
  710.      * @return {@code this - value}.
  711.      */
  712.     public BigFraction subtract(final int value) {
  713.         return subtract(BigInteger.valueOf(value));
  714.     }

  715.     /**
  716.      * Subtracts the specified {@code value} from this fraction, returning
  717.      * the result in reduced form.
  718.      *
  719.      * @param value Value to subtract.
  720.      * @return {@code this - value}.
  721.      */
  722.     public BigFraction subtract(final long value) {
  723.         return subtract(BigInteger.valueOf(value));
  724.     }

  725.     /**
  726.      * Subtracts the specified {@code value} from this fraction, returning
  727.      * the result in reduced form.
  728.      *
  729.      * @param value Value to subtract.
  730.      * @return {@code this - value}.
  731.      */
  732.     public BigFraction subtract(final BigInteger value) {
  733.         if (value.signum() == 0) {
  734.             return this;
  735.         }
  736.         if (isZero()) {
  737.             return of(value.negate());
  738.         }

  739.         return of(numerator.subtract(denominator.multiply(value)), denominator);
  740.     }

  741.     /**
  742.      * Subtracts the specified {@code value} from this fraction, returning
  743.      * the result in reduced form.
  744.      *
  745.      * @param value Value to subtract.
  746.      * @return {@code this - value}.
  747.      */
  748.     @Override
  749.     public BigFraction subtract(final BigFraction value) {
  750.         if (value.isZero()) {
  751.             return this;
  752.         }
  753.         if (isZero()) {
  754.             return value.negate();
  755.         }

  756.         final BigInteger num;
  757.         final BigInteger den;
  758.         if (denominator.equals(value.denominator)) {
  759.             num = numerator.subtract(value.numerator);
  760.             den = denominator;
  761.         } else {
  762.             num = (numerator.multiply(value.denominator)).subtract((value.numerator).multiply(denominator));
  763.             den = denominator.multiply(value.denominator);
  764.         }

  765.         if (num.signum() == 0) {
  766.             return ZERO;
  767.         }

  768.         return new BigFraction(num, den);
  769.     }

  770.     /**
  771.      * Multiply this fraction by the passed {@code value}, returning
  772.      * the result in reduced form.
  773.      *
  774.      * @param value Value to multiply by.
  775.      * @return {@code this * value}.
  776.      */
  777.     @Override
  778.     public BigFraction multiply(final int value) {
  779.         if (value == 0 || isZero()) {
  780.             return ZERO;
  781.         }

  782.         return multiply(BigInteger.valueOf(value));
  783.     }

  784.     /**
  785.      * Multiply this fraction by the passed {@code value}, returning
  786.      * the result in reduced form.
  787.      *
  788.      * @param value Value to multiply by.
  789.      * @return {@code this * value}.
  790.      */
  791.     public BigFraction multiply(final long value) {
  792.         if (value == 0 || isZero()) {
  793.             return ZERO;
  794.         }

  795.         return multiply(BigInteger.valueOf(value));
  796.     }

  797.     /**
  798.      * Multiply this fraction by the passed {@code value}, returning
  799.      * the result in reduced form.
  800.      *
  801.      * @param value Value to multiply by.
  802.      * @return {@code this * value}.
  803.      */
  804.     public BigFraction multiply(final BigInteger value) {
  805.         if (value.signum() == 0 || isZero()) {
  806.             return ZERO;
  807.         }
  808.         return new BigFraction(value.multiply(numerator), denominator);
  809.     }

  810.     /**
  811.      * Multiply this fraction by the passed {@code value}, returning
  812.      * the result in reduced form.
  813.      *
  814.      * @param value Value to multiply by.
  815.      * @return {@code this * value}.
  816.      */
  817.     @Override
  818.     public BigFraction multiply(final BigFraction value) {
  819.         if (value.isZero() || isZero()) {
  820.             return ZERO;
  821.         }
  822.         return new BigFraction(numerator.multiply(value.numerator),
  823.                                denominator.multiply(value.denominator));
  824.     }

  825.     /**
  826.      * Divide this fraction by the passed {@code value}, returning
  827.      * the result in reduced form.
  828.      *
  829.      * @param value Value to divide by
  830.      * @return {@code this / value}.
  831.      * @throws ArithmeticException if the value to divide by is zero
  832.      */
  833.     public BigFraction divide(final int value) {
  834.         return divide(BigInteger.valueOf(value));
  835.     }

  836.     /**
  837.      * Divide this fraction by the passed {@code value}, returning
  838.      * the result in reduced form.
  839.      *
  840.      * @param value Value to divide by
  841.      * @return {@code this / value}.
  842.      * @throws ArithmeticException if the value to divide by is zero
  843.      */
  844.     public BigFraction divide(final long value) {
  845.         return divide(BigInteger.valueOf(value));
  846.     }

  847.     /**
  848.      * Divide this fraction by the passed {@code value}, returning
  849.      * the result in reduced form.
  850.      *
  851.      * @param value Value to divide by
  852.      * @return {@code this / value}.
  853.      * @throws ArithmeticException if the value to divide by is zero
  854.      */
  855.     public BigFraction divide(final BigInteger value) {
  856.         if (value.signum() == 0) {
  857.             throw new FractionException(FractionException.ERROR_DIVIDE_BY_ZERO);
  858.         }
  859.         if (isZero()) {
  860.             return ZERO;
  861.         }
  862.         return new BigFraction(numerator, denominator.multiply(value));
  863.     }

  864.     /**
  865.      * Divide this fraction by the passed {@code value}, returning
  866.      * the result in reduced form.
  867.      *
  868.      * @param value Value to divide by
  869.      * @return {@code this / value}.
  870.      * @throws ArithmeticException if the value to divide by is zero
  871.      */
  872.     @Override
  873.     public BigFraction divide(final BigFraction value) {
  874.         if (value.isZero()) {
  875.             throw new FractionException(FractionException.ERROR_DIVIDE_BY_ZERO);
  876.         }
  877.         if (isZero()) {
  878.             return ZERO;
  879.         }
  880.         // Multiply by reciprocal
  881.         return new BigFraction(numerator.multiply(value.denominator),
  882.                                denominator.multiply(value.numerator));
  883.     }

  884.     /**
  885.      * Returns a {@code BigFraction} whose value is
  886.      * <code>this<sup>exponent</sup></code>, returning the result in reduced form.
  887.      *
  888.      * @param exponent exponent to which this {@code BigFraction} is to be raised.
  889.      * @return <code>this<sup>exponent</sup></code>.
  890.      * @throws ArithmeticException if the intermediate result would overflow.
  891.      */
  892.     @Override
  893.     public BigFraction pow(final int exponent) {
  894.         if (exponent == 1) {
  895.             return this;
  896.         }
  897.         if (exponent == 0) {
  898.             return ONE;
  899.         }
  900.         if (isZero()) {
  901.             if (exponent < 0) {
  902.                 throw new FractionException(FractionException.ERROR_ZERO_DENOMINATOR);
  903.             }
  904.             return ZERO;
  905.         }
  906.         if (exponent > 0) {
  907.             return new BigFraction(numerator.pow(exponent),
  908.                                    denominator.pow(exponent));
  909.         }
  910.         if (exponent == -1) {
  911.             return this.reciprocal();
  912.         }
  913.         if (exponent == Integer.MIN_VALUE) {
  914.             // MIN_VALUE can't be negated
  915.             return new BigFraction(denominator.pow(Integer.MAX_VALUE).multiply(denominator),
  916.                                    numerator.pow(Integer.MAX_VALUE).multiply(numerator));
  917.         }
  918.         // Note: Raise the BigIntegers to the power and then reduce.
  919.         // The supported range for BigInteger is currently
  920.         // +/-2^(Integer.MAX_VALUE) exclusive thus larger
  921.         // exponents (long, BigInteger) are currently not supported.
  922.         return new BigFraction(denominator.pow(-exponent),
  923.                                numerator.pow(-exponent));
  924.     }

  925.     /**
  926.      * Returns the {@code String} representing this fraction.
  927.      * Uses:
  928.      * <ul>
  929.      *  <li>{@code "0"} if {@code numerator} is zero.
  930.      *  <li>{@code "numerator"} if {@code denominator} is one.
  931.      *  <li>{@code "numerator / denominator"} for all other cases.
  932.      * </ul>
  933.      *
  934.      * @return a string representation of the fraction.
  935.      */
  936.     @Override
  937.     public String toString() {
  938.         final String str;
  939.         if (isZero()) {
  940.             str = "0";
  941.         } else if (BigInteger.ONE.equals(denominator)) {
  942.             str = numerator.toString();
  943.         } else {
  944.             str = numerator + " / " + denominator;
  945.         }
  946.         return str;
  947.     }

  948.     /**
  949.      * Compares this object with the specified object for order using the signed magnitude.
  950.      *
  951.      * @param other {@inheritDoc}
  952.      * @return {@inheritDoc}
  953.      */
  954.     @Override
  955.     public int compareTo(final BigFraction other) {
  956.         final int lhsSigNum = signum();
  957.         final int rhsSigNum = other.signum();

  958.         if (lhsSigNum != rhsSigNum) {
  959.             return (lhsSigNum > rhsSigNum) ? 1 : -1;
  960.         }
  961.         // Same sign.
  962.         // Avoid a multiply if both fractions are zero
  963.         if (lhsSigNum == 0) {
  964.             return 0;
  965.         }
  966.         // Compare absolute magnitude
  967.         final BigInteger nOd = numerator.abs().multiply(other.denominator.abs());
  968.         final BigInteger dOn = denominator.abs().multiply(other.numerator.abs());
  969.         return nOd.compareTo(dOn);
  970.     }

  971.     /**
  972.      * Test for equality with another object. If the other object is a {@code Fraction} then a
  973.      * comparison is made of the sign and magnitude; otherwise {@code false} is returned.
  974.      *
  975.      * @param other {@inheritDoc}
  976.      * @return {@inheritDoc}
  977.      */
  978.     @Override
  979.     public boolean equals(final Object other) {
  980.         if (this == other) {
  981.             return true;
  982.         }

  983.         if (other instanceof BigFraction) {
  984.             // Since fractions are always in lowest terms, numerators and
  985.             // denominators can be compared directly for equality.
  986.             final BigFraction rhs = (BigFraction) other;
  987.             if (signum() == rhs.signum()) {
  988.                 return numerator.abs().equals(rhs.numerator.abs()) &&
  989.                        denominator.abs().equals(rhs.denominator.abs());
  990.             }
  991.         }

  992.         return false;
  993.     }

  994.     @Override
  995.     public int hashCode() {
  996.         // Incorporate the sign and absolute values of the numerator and denominator.
  997.         // Equivalent to:
  998.         // int hash = 1;
  999.         // hash = 31 * hash + numerator.abs().hashCode();
  1000.         // hash = 31 * hash + denominator.abs().hashCode();
  1001.         // hash = hash * signum()
  1002.         // Note: BigInteger.hashCode() * BigInteger.signum() == BigInteger.abs().hashCode().
  1003.         final int numS = numerator.signum();
  1004.         final int denS = denominator.signum();
  1005.         return (31 * (31 + numerator.hashCode() * numS) + denominator.hashCode() * denS) * numS * denS;
  1006.     }

  1007.     /**
  1008.      * Calculates the sign bit, the biased exponent and the significand for a
  1009.      * binary floating-point representation of this {@code BigFraction}
  1010.      * according to the IEEE 754 standard, and encodes these values into a {@code long}
  1011.      * variable. The representative bits are arranged adjacent to each other and
  1012.      * placed at the low-order end of the returned {@code long} value, with the
  1013.      * least significant bits used for the significand, the next more
  1014.      * significant bits for the exponent, and next more significant bit for the
  1015.      * sign.
  1016.      *
  1017.      * <p>Warning: The arguments are not validated.
  1018.      *
  1019.      * @param exponentLength the number of bits allowed for the exponent; must be
  1020.      *                       between 1 and 32 (inclusive), and must not be greater
  1021.      *                       than {@code 63 - significandLength}
  1022.      * @param significandLength the number of bits allowed for the significand
  1023.      *                          (excluding the implicit leading 1-bit in
  1024.      *                          normalized numbers, e.g. 52 for a double-precision
  1025.      *                          floating-point number); must be between 1 and
  1026.      *                          {@code 63 - exponentLength} (inclusive)
  1027.      * @return the bits of an IEEE 754 binary floating-point representation of
  1028.      * this fraction encoded in a {@code long}, as described above.
  1029.      */
  1030.     private long toFloatingPointBits(int exponentLength, int significandLength) {
  1031.         // Assume the following conditions:
  1032.         //assert exponentLength >= 1;
  1033.         //assert exponentLength <= 32;
  1034.         //assert significandLength >= 1;
  1035.         //assert significandLength <= 63 - exponentLength;

  1036.         if (isZero()) {
  1037.             return 0L;
  1038.         }

  1039.         final long sign = (numerator.signum() * denominator.signum()) == -1 ? 1L : 0L;
  1040.         final BigInteger positiveNumerator = numerator.abs();
  1041.         final BigInteger positiveDenominator = denominator.abs();

  1042.         /*
  1043.          * The most significant 1-bit of a non-zero number is not explicitly
  1044.          * stored in the significand of an IEEE 754 normalized binary
  1045.          * floating-point number, so we need to round the value of this fraction
  1046.          * to (significandLength + 1) bits. In order to do this, we calculate
  1047.          * the most significant (significandLength + 2) bits, and then, based on
  1048.          * the least significant of those bits, find out whether we need to
  1049.          * round up or down.
  1050.          *
  1051.          * First, we'll remove all powers of 2 from the denominator because they
  1052.          * are not relevant for the significand of the prospective binary
  1053.          * floating-point value.
  1054.          */
  1055.         final int denRightShift = positiveDenominator.getLowestSetBit();
  1056.         final BigInteger divisor = positiveDenominator.shiftRight(denRightShift);

  1057.         /*
  1058.          * Now, we're going to calculate the (significandLength + 2) most
  1059.          * significant bits of the fraction's value using integer division. To
  1060.          * guarantee that the quotient of the division has at least
  1061.          * (significandLength + 2) bits, the bit length of the dividend must
  1062.          * exceed that of the divisor by at least that amount.
  1063.          *
  1064.          * If the denominator has prime factors other than 2, i.e. if the
  1065.          * divisor was not reduced to 1, an excess of exactly
  1066.          * (significandLength + 2) bits is sufficient, because the knowledge
  1067.          * that the fractional part of the precise quotient's binary
  1068.          * representation does not terminate is enough information to resolve
  1069.          * cases where the most significant (significandLength + 2) bits alone
  1070.          * are not conclusive.
  1071.          *
  1072.          * Otherwise, the quotient must be calculated exactly and the bit length
  1073.          * of the numerator can only be reduced as long as no precision is lost
  1074.          * in the process (meaning it can have powers of 2 removed, like the
  1075.          * denominator).
  1076.          */
  1077.         int numRightShift = positiveNumerator.bitLength() - divisor.bitLength() - (significandLength + 2);
  1078.         if (numRightShift > 0 &&
  1079.             divisor.equals(BigInteger.ONE)) {
  1080.             numRightShift = Math.min(numRightShift, positiveNumerator.getLowestSetBit());
  1081.         }
  1082.         final BigInteger dividend = positiveNumerator.shiftRight(numRightShift);

  1083.         final BigInteger quotient = dividend.divide(divisor);

  1084.         int quotRightShift = quotient.bitLength() - (significandLength + 1);
  1085.         long significand = roundAndRightShift(
  1086.                 quotient,
  1087.                 quotRightShift,
  1088.                 !divisor.equals(BigInteger.ONE)
  1089.         ).longValue();

  1090.         /*
  1091.          * If the significand had to be rounded up, this could have caused the
  1092.          * bit length of the significand to increase by one.
  1093.          */
  1094.         if ((significand & (1L << (significandLength + 1))) != 0) {
  1095.             significand >>= 1;
  1096.             quotRightShift++;
  1097.         }

  1098.         /*
  1099.          * Now comes the exponent. The absolute value of this fraction based on
  1100.          * the current local variables is:
  1101.          *
  1102.          * significand * 2^(numRightShift - denRightShift + quotRightShift)
  1103.          *
  1104.          * To get the unbiased exponent for the floating-point value, we need to
  1105.          * add (significandLength) to the above exponent, because all but the
  1106.          * most significant bit of the significand will be treated as a
  1107.          * fractional part. To convert the unbiased exponent to a biased
  1108.          * exponent, we also need to add the exponent bias.
  1109.          */
  1110.         final int exponentBias = (1 << (exponentLength - 1)) - 1;
  1111.         long exponent = (long) numRightShift - denRightShift + quotRightShift + significandLength + exponentBias;
  1112.         final long maxExponent = (1L << exponentLength) - 1L; //special exponent for infinities and NaN

  1113.         if (exponent >= maxExponent) { //infinity
  1114.             exponent = maxExponent;
  1115.             significand = 0L;
  1116.         } else if (exponent > 0) { //normalized number
  1117.             significand &= -1L >>> (64 - significandLength); //remove implicit leading 1-bit
  1118.         } else { //smaller than the smallest normalized number
  1119.             /*
  1120.              * We need to round the quotient to fewer than
  1121.              * (significandLength + 1) bits. This must be done with the original
  1122.              * quotient and not with the current significand, because the loss
  1123.              * of precision in the previous rounding might cause a rounding of
  1124.              * the current significand's value to produce a different result
  1125.              * than a rounding of the original quotient.
  1126.              *
  1127.              * So we find out how many high-order bits from the quotient we can
  1128.              * transfer into the significand. The absolute value of the fraction
  1129.              * is:
  1130.              *
  1131.              * quotient * 2^(numRightShift - denRightShift)
  1132.              *
  1133.              * To get the significand, we need to right shift the quotient so
  1134.              * that the above exponent becomes (1 - exponentBias - significandLength)
  1135.              * (the unbiased exponent of a subnormal floating-point number is
  1136.              * defined as equivalent to the minimum unbiased exponent of a
  1137.              * normalized floating-point number, and (- significandLength)
  1138.              * because the significand will be treated as the fractional part).
  1139.              */
  1140.             significand = roundAndRightShift(quotient,
  1141.                                              (1 - exponentBias - significandLength) - (numRightShift - denRightShift),
  1142.                                              !divisor.equals(BigInteger.ONE)).longValue();
  1143.             exponent = 0L;

  1144.             /*
  1145.              * Note: It is possible that an otherwise subnormal number will
  1146.              * round up to the smallest normal number. However, this special
  1147.              * case does not need to be treated separately, because the
  1148.              * overflowing highest-order bit of the significand will then simply
  1149.              * become the lowest-order bit of the exponent, increasing the
  1150.              * exponent from 0 to 1 and thus establishing the implicity of the
  1151.              * leading 1-bit.
  1152.              */
  1153.         }

  1154.         return (sign << (significandLength + exponentLength)) |
  1155.             (exponent << significandLength) |
  1156.             significand;
  1157.     }

  1158.     /**
  1159.      * Rounds an integer to the specified power of two (i.e. the minimum number of
  1160.      * low-order bits that must be zero) and performs a right-shift by this
  1161.      * amount. The rounding mode applied is round to nearest, with ties rounding
  1162.      * to even (meaning the prospective least significant bit must be zero). The
  1163.      * number can optionally be treated as though it contained at
  1164.      * least one 0-bit and one 1-bit in its fractional part, to influence the result in cases
  1165.      * that would otherwise be a tie.
  1166.      * @param value the number to round and right-shift
  1167.      * @param bits the power of two to which to round; must be positive
  1168.      * @param hasFractionalBits whether the number should be treated as though
  1169.      *                          it contained a non-zero fractional part
  1170.      * @return a {@code BigInteger} as described above
  1171.      */
  1172.     private static BigInteger roundAndRightShift(BigInteger value, int bits, boolean hasFractionalBits) {
  1173.         // Assumptions:
  1174.         // assert bits > 0

  1175.         BigInteger result = value.shiftRight(bits);
  1176.         if (value.testBit(bits - 1) &&
  1177.             (hasFractionalBits ||
  1178.              value.getLowestSetBit() < bits - 1 ||
  1179.              value.testBit(bits))) {
  1180.             result = result.add(BigInteger.ONE); //round up
  1181.         }

  1182.         return result;
  1183.     }
  1184. }