001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.commons.numbers.fraction;
018
019import java.io.Serializable;
020import java.math.BigDecimal;
021import java.math.BigInteger;
022import java.math.RoundingMode;
023import org.apache.commons.numbers.core.ArithmeticUtils;
024import org.apache.commons.numbers.core.NativeOperators;
025
026/**
027 * Representation of a rational number without any overflow. This class is
028 * immutable.
029 */
030public final class BigFraction
031    extends Number
032    implements Comparable<BigFraction>,
033               NativeOperators<BigFraction>,
034               Serializable {
035    /** A fraction representing "0". */
036    public static final BigFraction ZERO = of(0);
037
038    /** A fraction representing "1". */
039    public static final BigFraction ONE = of(1);
040
041    /** Serializable version identifier. */
042    private static final long serialVersionUID = 20190701L;
043
044    /** The numerator of this fraction reduced to lowest terms. */
045    private final BigInteger numerator;
046
047    /** The denominator of this fraction reduced to lowest terms. */
048    private final BigInteger denominator;
049
050    /**
051     * Private constructor: Instances are created using factory methods.
052     *
053     * @param num Numerator, must not be {@code null}.
054     * @param den Denominator, must not be {@code null}.
055     * @throws ArithmeticException if the denominator is zero.
056     */
057    private BigFraction(BigInteger num, BigInteger den) {
058        if (den.signum() == 0) {
059            throw new FractionException(FractionException.ERROR_ZERO_DENOMINATOR);
060        }
061
062        // reduce numerator and denominator by greatest common denominator
063        final BigInteger gcd = num.gcd(den);
064        if (BigInteger.ONE.compareTo(gcd) < 0) {
065            num = num.divide(gcd);
066            den = den.divide(gcd);
067        }
068
069        // store the values in the final fields
070        numerator = num;
071        denominator = den;
072    }
073
074    /**
075     * Create a fraction given the double value and either the maximum
076     * error allowed or the maximum number of denominator digits.
077     *
078     * <p>
079     * NOTE: This method is called with
080     *  - EITHER a valid epsilon value and the maxDenominator set to
081     *    Integer.MAX_VALUE (that way the maxDenominator has no effect)
082     *  - OR a valid maxDenominator value and the epsilon value set to
083     *    zero (that way epsilon only has effect if there is an exact
084     *    match before the maxDenominator value is reached).
085     * </p>
086     * <p>
087     * It has been done this way so that the same code can be reused for
088     * both scenarios.  However this could be confusing to users if it
089     * were part of the public API and this method should therefore remain
090     * PRIVATE.
091     * </p>
092     *
093     * See JIRA issue ticket MATH-181 for more details:
094     *   https://issues.apache.org/jira/browse/MATH-181
095     *
096     * @param value Value to convert to a fraction.
097     * @param epsilon Maximum error allowed.
098     * The resulting fraction is within {@code epsilon} of {@code value},
099     * in absolute terms.
100     * @param maxDenominator Maximum denominator value allowed.
101     * @param maxIterations Maximum number of convergents.
102     * @return a new instance.
103     * @throws ArithmeticException if the continued fraction failed to converge.
104     */
105    private static BigFraction from(final double value,
106                                    final double epsilon,
107                                    final int maxDenominator,
108                                    final int maxIterations) {
109        final long overflow = Integer.MAX_VALUE;
110        double r0 = value;
111        long a0 = (long) Math.floor(r0);
112
113        if (Math.abs(a0) > overflow) {
114            throw new FractionException(FractionException.ERROR_CONVERSION_OVERFLOW, value, a0, 1L);
115        }
116
117        // check for (almost) integer arguments, which should not go
118        // to iterations.
119        if (Math.abs(a0 - value) < epsilon) {
120            return new BigFraction(BigInteger.valueOf(a0),
121                                   BigInteger.ONE);
122        }
123
124        long p0 = 1;
125        long q0 = 0;
126        long p1 = a0;
127        long q1 = 1;
128
129        long p2 = 0;
130        long q2 = 1;
131
132        int n = 0;
133        boolean stop = false;
134        do {
135            ++n;
136            final double r1 = 1d / (r0 - a0);
137            final long a1 = (long) Math.floor(r1);
138            p2 = (a1 * p1) + p0;
139            q2 = (a1 * q1) + q0;
140            if (p2 > overflow ||
141                q2 > overflow) {
142                // in maxDenominator mode, if the last fraction was very close to the actual value
143                // q2 may overflow in the next iteration; in this case return the last one.
144                if (epsilon == 0 &&
145                    Math.abs(q1) < maxDenominator) {
146                    break;
147                }
148                throw new FractionException(FractionException.ERROR_CONVERSION_OVERFLOW, value, p2, q2);
149            }
150
151            final double convergent = (double) p2 / (double) q2;
152            if (n < maxIterations &&
153                Math.abs(convergent - value) > epsilon &&
154                q2 < maxDenominator) {
155                p0 = p1;
156                p1 = p2;
157                q0 = q1;
158                q1 = q2;
159                a0 = a1;
160                r0 = r1;
161            } else {
162                stop = true;
163            }
164        } while (!stop);
165
166        if (n >= maxIterations) {
167            throw new FractionException(FractionException.ERROR_CONVERSION, value, maxIterations);
168        }
169
170        return q2 < maxDenominator ?
171            new BigFraction(BigInteger.valueOf(p2),
172                            BigInteger.valueOf(q2)) :
173            new BigFraction(BigInteger.valueOf(p1),
174                            BigInteger.valueOf(q1));
175    }
176
177    /**
178     * <p>
179     * Create a {@link BigFraction} equivalent to the passed {@code BigInteger}, ie
180     * "num / 1".
181     * </p>
182     *
183     * @param num the numerator.
184     * @return a new instance.
185     */
186    public static BigFraction of(final BigInteger num) {
187        return new BigFraction(num, BigInteger.ONE);
188    }
189
190    /**
191     * Create a {@link BigFraction} given the numerator and denominator as
192     * {@code BigInteger}. The {@link BigFraction} is reduced to lowest terms.
193     *
194     * @param num the numerator, must not be {@code null}.
195     * @param den the denominator, must not be {@code null}.
196     * @throws ArithmeticException if the denominator is zero.
197     * @return a new instance.
198     */
199    public static BigFraction of(BigInteger num, BigInteger den) {
200        return new BigFraction(num, den);
201    }
202
203    /**
204     * Create a fraction given the double value.
205     * <p>
206     * This factory method behaves <em>differently</em> from
207     * {@link #from(double, double, int)}. It converts the double value
208     * exactly, considering its internal bits representation. This works for all
209     * values except NaN and infinities and does not requires any loop or
210     * convergence threshold.
211     * </p>
212     * <p>
213     * Since this conversion is exact and since double numbers are sometimes
214     * approximated, the fraction created may seem strange in some cases. For example,
215     * calling {@code from(1.0 / 3.0)} does <em>not</em> create
216     * the fraction \( \frac{1}{3} \), but the fraction \( \frac{6004799503160661}{18014398509481984} \)
217     * because the double number passed to the method is not exactly \( \frac{1}{3} \)
218     * (which cannot be represented exactly in IEEE754).
219     * </p>
220     *
221     * @param value Value to convert to a fraction.
222     * @throws IllegalArgumentException if the given {@code value} is NaN or infinite.
223     * @return a new instance.
224     *
225     * @see #from(double,double,int)
226     */
227    public static BigFraction from(final double value) {
228        if (Double.isNaN(value)) {
229            throw new IllegalArgumentException("Cannot convert NaN value");
230        }
231        if (Double.isInfinite(value)) {
232            throw new IllegalArgumentException("Cannot convert infinite value");
233        }
234
235        final long bits = Double.doubleToLongBits(value);
236        final long sign = bits & 0x8000000000000000L;
237        final long exponent = bits & 0x7ff0000000000000L;
238        final long mantissa = bits & 0x000fffffffffffffL;
239
240        // Compute m and k such that value = m * 2^k
241        long m;
242        int k;
243
244        if (exponent == 0) {
245            m = mantissa;
246            k = 0; // For simplicity, when number is 0.
247            if (m != 0) {
248                // Subnormal number, the effective exponent bias is 1022, not 1023.
249                k = -1074;
250            }
251        } else {
252            // Normalized number: Add the implicit most significant bit.
253            m = mantissa | 0x0010000000000000L;
254            k = ((int) (exponent >> 52)) - 1075; // Exponent bias is 1023.
255        }
256        if (sign != 0) {
257            m = -m;
258        }
259        while ((m & 0x001ffffffffffffeL) != 0 &&
260               (m & 0x1) == 0) {
261            m >>= 1;
262            ++k;
263        }
264
265        return k < 0 ?
266            new BigFraction(BigInteger.valueOf(m),
267                            BigInteger.ZERO.flipBit(-k)) :
268            new BigFraction(BigInteger.valueOf(m).multiply(BigInteger.ZERO.flipBit(k)),
269                            BigInteger.ONE);
270    }
271
272    /**
273     * Create a fraction given the double value and maximum error allowed.
274     * <p>
275     * References:
276     * <ul>
277     * <li><a href="http://mathworld.wolfram.com/ContinuedFraction.html">
278     * Continued Fraction</a> equations (11) and (22)-(26)</li>
279     * </ul>
280     *
281     * @param value Value to convert to a fraction.
282     * @param epsilon Maximum error allowed. The resulting fraction is within
283     * {@code epsilon} of {@code value}, in absolute terms.
284     * @param maxIterations Maximum number of convergents.
285     * @throws ArithmeticException if the continued fraction failed to converge.
286     * @return a new instance.
287     *
288     * @see #from(double,int)
289     */
290    public static BigFraction from(final double value,
291                                   final double epsilon,
292                                   final int maxIterations) {
293        return from(value, epsilon, Integer.MAX_VALUE, maxIterations);
294    }
295
296    /**
297     * Create a fraction given the double value and maximum denominator.
298     * <p>
299     * References:
300     * <ul>
301     * <li><a href="http://mathworld.wolfram.com/ContinuedFraction.html">
302     * Continued Fraction</a> equations (11) and (22)-(26)</li>
303     * </ul>
304     *
305     * @param value Value to convert to a fraction.
306     * @param maxDenominator Maximum allowed value for denominator.
307     * @throws ArithmeticException if the continued fraction failed to converge.
308     * @return a new instance.
309     *
310     * @see #from(double,double,int)
311     */
312    public static BigFraction from(final double value,
313                                   final int maxDenominator) {
314        return from(value, 0, maxDenominator, 100);
315    }
316
317    /**
318     * <p>
319     * Create a {@link BigFraction} equivalent to the passed {@code int}, ie
320     * "num / 1".
321     * </p>
322     *
323     * @param num
324     *            the numerator.
325     * @return a new instance.
326     */
327    public static BigFraction of(final int num) {
328        return new BigFraction(BigInteger.valueOf(num), BigInteger.ONE);
329    }
330
331    /**
332     * <p>
333     * Create a {@link BigFraction} given the numerator and denominator as simple
334     * {@code int}. The {@link BigFraction} is reduced to lowest terms.
335     * </p>
336     *
337     * @param num the numerator.
338     * @param den the denominator.
339     * @return a new instance.
340     * @throws ArithmeticException if {@code den} is zero.
341     */
342    public static BigFraction of(final int num, final int den) {
343        return new BigFraction(BigInteger.valueOf(num), BigInteger.valueOf(den));
344    }
345
346    /**
347     * <p>
348     * Create a {@link BigFraction} equivalent to the passed long, ie "num / 1".
349     * </p>
350     *
351     * @param num the numerator.
352     * @return a new instance.
353     */
354    public static BigFraction of(final long num) {
355        return new BigFraction(BigInteger.valueOf(num), BigInteger.ONE);
356    }
357
358    /**
359     * <p>
360     * Create a {@link BigFraction} given the numerator and denominator as simple
361     * {@code long}. The {@link BigFraction} is reduced to lowest terms.
362     * </p>
363     *
364     * @param num the numerator.
365     * @param den the denominator.
366     * @return a new instance.
367     * @throws ArithmeticException if {@code den} is zero.
368     */
369    public static BigFraction of(final long num, final long den) {
370        return new BigFraction(BigInteger.valueOf(num), BigInteger.valueOf(den));
371    }
372
373    /**
374     * <p>
375     * Returns the absolute value of this {@link BigFraction}.
376     * </p>
377     *
378     * @return the absolute value as a {@link BigFraction}.
379     */
380    public BigFraction abs() {
381        return signum() >= 0 ?
382            this :
383            negate();
384    }
385
386    /**
387     * <p>
388     * Adds the value of this fraction to the passed {@link BigInteger},
389     * returning the result in reduced form.
390     * </p>
391     *
392     * @param bg
393     *            the {@link BigInteger} to add, must'nt be <code>null</code>.
394     * @return a <code>BigFraction</code> instance with the resulting values.
395     */
396    public BigFraction add(final BigInteger bg) {
397        if (numerator.signum() == 0) {
398            return of(bg);
399        }
400        if (bg.signum() == 0) {
401            return this;
402        }
403
404        return new BigFraction(numerator.add(denominator.multiply(bg)), denominator);
405    }
406
407    /**
408     * <p>
409     * Adds the value of this fraction to the passed {@code integer}, returning
410     * the result in reduced form.
411     * </p>
412     *
413     * @param i
414     *            the {@code integer} to add.
415     * @return a <code>BigFraction</code> instance with the resulting values.
416     */
417    public BigFraction add(final int i) {
418        return add(BigInteger.valueOf(i));
419    }
420
421    /**
422     * <p>
423     * Adds the value of this fraction to the passed {@code long}, returning
424     * the result in reduced form.
425     * </p>
426     *
427     * @param l
428     *            the {@code long} to add.
429     * @return a <code>BigFraction</code> instance with the resulting values.
430     */
431    public BigFraction add(final long l) {
432        return add(BigInteger.valueOf(l));
433    }
434
435    /**
436     * <p>
437     * Adds the value of this fraction to another, returning the result in
438     * reduced form.
439     * </p>
440     *
441     * @param fraction
442     *            the {@link BigFraction} to add, must not be <code>null</code>.
443     * @return a {@link BigFraction} instance with the resulting values.
444     */
445    @Override
446    public BigFraction add(final BigFraction fraction) {
447        if (fraction.numerator.signum() == 0) {
448            return this;
449        }
450        if (numerator.signum() == 0) {
451            return fraction;
452        }
453
454        final BigInteger num;
455        final BigInteger den;
456
457        if (denominator.equals(fraction.denominator)) {
458            num = numerator.add(fraction.numerator);
459            den = denominator;
460        } else {
461            num = (numerator.multiply(fraction.denominator)).add((fraction.numerator).multiply(denominator));
462            den = denominator.multiply(fraction.denominator);
463        }
464
465        if (num.signum() == 0) {
466            return ZERO;
467        }
468
469        return new BigFraction(num, den);
470
471    }
472
473    /**
474     * <p>
475     * Gets the fraction as a <code>BigDecimal</code>. This calculates the
476     * fraction as the numerator divided by denominator.
477     * </p>
478     *
479     * @return the fraction as a <code>BigDecimal</code>.
480     * @throws ArithmeticException
481     *             if the exact quotient does not have a terminating decimal
482     *             expansion.
483     * @see BigDecimal
484     */
485    public BigDecimal bigDecimalValue() {
486        return new BigDecimal(numerator).divide(new BigDecimal(denominator));
487    }
488
489    /**
490     * <p>
491     * Gets the fraction as a <code>BigDecimal</code> following the passed
492     * rounding mode. This calculates the fraction as the numerator divided by
493     * denominator.
494     * </p>
495     *
496     * @param roundingMode Rounding mode to apply.
497     * @return the fraction as a <code>BigDecimal</code>.
498     * @see BigDecimal
499     */
500    public BigDecimal bigDecimalValue(RoundingMode roundingMode) {
501        return new BigDecimal(numerator).divide(new BigDecimal(denominator), roundingMode);
502    }
503
504    /**
505     * <p>
506     * Gets the fraction as a <code>BigDecimal</code> following the passed scale
507     * and rounding mode. This calculates the fraction as the numerator divided
508     * by denominator.
509     * </p>
510     *
511     * @param scale
512     *            scale of the <code>BigDecimal</code> quotient to be returned.
513     *            see {@link BigDecimal} for more information.
514     * @param roundingMode Rounding mode to apply.
515     * @return the fraction as a <code>BigDecimal</code>.
516     * @throws ArithmeticException if {@code roundingMode} == {@link RoundingMode#UNNECESSARY} and
517     *      the specified scale is insufficient to represent the result of the division exactly.
518     * @see BigDecimal
519     */
520    public BigDecimal bigDecimalValue(final int scale, RoundingMode roundingMode) {
521        return new BigDecimal(numerator).divide(new BigDecimal(denominator), scale, roundingMode);
522    }
523
524    /**
525     * <p>
526     * Compares this object to another based on size.
527     * </p>
528     *
529     * @param other Object to compare to, must not be {@code null}.
530     * @return -1 if this is less than {@code object}, +1 if this is greater
531     * than {@code object}, 0 if they are equal.
532     *
533     * @see Comparable#compareTo(Object)
534     */
535    @Override
536    public int compareTo(final BigFraction other) {
537        final int lhsSigNum = signum();
538        final int rhsSigNum = other.signum();
539
540        if (lhsSigNum != rhsSigNum) {
541            return (lhsSigNum > rhsSigNum) ? 1 : -1;
542        }
543        if (lhsSigNum == 0) {
544            return 0;
545        }
546
547        final BigInteger nOd = numerator.multiply(other.denominator);
548        final BigInteger dOn = denominator.multiply(other.numerator);
549        return nOd.compareTo(dOn);
550    }
551
552    /**
553     * <p>
554     * Divide the value of this fraction by the passed {@code BigInteger},
555     * ie {@code this * 1 / bg}, returning the result in reduced form.
556     * </p>
557     *
558     * @param bg the {@code BigInteger} to divide by, must not be {@code null}
559     * @return a {@link BigFraction} instance with the resulting values
560     * @throws ArithmeticException if the value to divide by is zero
561     */
562    public BigFraction divide(final BigInteger bg) {
563        if (bg.signum() == 0) {
564            throw new FractionException(FractionException.ERROR_ZERO_DENOMINATOR);
565        }
566        if (numerator.signum() == 0) {
567            return ZERO;
568        }
569        return new BigFraction(numerator, denominator.multiply(bg));
570    }
571
572    /**
573     * <p>
574     * Divide the value of this fraction by the passed {@code int}, ie
575     * {@code this * 1 / i}, returning the result in reduced form.
576     * </p>
577     *
578     * @param i the {@code int} to divide by
579     * @return a {@link BigFraction} instance with the resulting values
580     * @throws ArithmeticException if the value to divide by is zero
581     */
582    public BigFraction divide(final int i) {
583        return divide(BigInteger.valueOf(i));
584    }
585
586    /**
587     * <p>
588     * Divide the value of this fraction by the passed {@code long}, ie
589     * {@code this * 1 / l}, returning the result in reduced form.
590     * </p>
591     *
592     * @param l the {@code long} to divide by
593     * @return a {@link BigFraction} instance with the resulting values
594     * @throws ArithmeticException if the value to divide by is zero
595     */
596    public BigFraction divide(final long l) {
597        return divide(BigInteger.valueOf(l));
598    }
599
600    /**
601     * <p>
602     * Divide the value of this fraction by another, returning the result in
603     * reduced form.
604     * </p>
605     *
606     * @param fraction Fraction to divide by, must not be {@code null}.
607     * @return a {@link BigFraction} instance with the resulting values.
608     * @throws ArithmeticException if the fraction to divide by is zero
609     */
610    @Override
611    public BigFraction divide(final BigFraction fraction) {
612        if (fraction.numerator.signum() == 0) {
613            throw new FractionException(FractionException.ERROR_ZERO_DENOMINATOR);
614        }
615        if (numerator.signum() == 0) {
616            return ZERO;
617        }
618
619        return multiply(fraction.reciprocal());
620    }
621
622    /**
623     * Calculates the sign bit, the biased exponent and the significand for a
624     * binary floating-point representation of this {@code BigFraction}
625     * according to the IEEE 754 standard, and encodes these values into a {@code long}
626     * variable. The representative bits are arranged adjacent to each other and
627     * placed at the low-order end of the returned {@code long} value, with the
628     * least significant bits used for the significand, the next more
629     * significant bits for the exponent, and next more significant bit for the
630     * sign.
631     * @param exponentLength the number of bits allowed for the exponent; must be
632     *                       between 1 and 32 (inclusive), and must not be greater
633     *                       than {@code 63 - significandLength}
634     * @param significandLength the number of bits allowed for the significand
635     *                          (excluding the implicit leading 1-bit in
636     *                          normalized numbers, e.g. 52 for a double-precision
637     *                          floating-point number); must be between 1 and
638     *                          {@code 63 - exponentLength} (inclusive)
639     * @return the bits of an IEEE 754 binary floating-point representation of
640     * this fraction encoded in a {@code long}, as described above.
641     * @throws IllegalArgumentException if the arguments do not meet the
642     *         criteria described above
643     */
644    private long toFloatingPointBits(int exponentLength, int significandLength) {
645        if (exponentLength < 1 ||
646            significandLength < 1 ||
647            exponentLength > Math.min(32, 63 - significandLength)) {
648            throw new IllegalArgumentException("exponent length: " + exponentLength +
649                                               "; significand length: " + significandLength);
650        }
651        if (numerator.signum() == 0) {
652            return 0L;
653        }
654
655        final long sign = (numerator.signum() * denominator.signum()) == -1 ? 1L : 0L;
656        final BigInteger positiveNumerator = numerator.abs();
657        final BigInteger positiveDenominator = denominator.abs();
658
659        /*
660         * The most significant 1-bit of a non-zero number is not explicitly
661         * stored in the significand of an IEEE 754 normalized binary
662         * floating-point number, so we need to round the value of this fraction
663         * to (significandLength + 1) bits. In order to do this, we calculate
664         * the most significant (significandLength + 2) bits, and then, based on
665         * the least significant of those bits, find out whether we need to
666         * round up or down.
667         *
668         * First, we'll remove all powers of 2 from the denominator because they
669         * are not relevant for the significand of the prospective binary
670         * floating-point value.
671         */
672        final int denRightShift = positiveDenominator.getLowestSetBit();
673        final BigInteger divisor = positiveDenominator.shiftRight(denRightShift);
674
675        /*
676         * Now, we're going to calculate the (significandLength + 2) most
677         * significant bits of the fraction's value using integer division. To
678         * guarantee that the quotient of the division has at least
679         * (significandLength + 2) bits, the bit length of the dividend must
680         * exceed that of the divisor by at least that amount.
681         *
682         * If the denominator has prime factors other than 2, i.e. if the
683         * divisor was not reduced to 1, an excess of exactly
684         * (significandLength + 2) bits is sufficient, because the knowledge
685         * that the fractional part of the precise quotient's binary
686         * representation does not terminate is enough information to resolve
687         * cases where the most significant (significandLength + 2) bits alone
688         * are not conclusive.
689         *
690         * Otherwise, the quotient must be calculated exactly and the bit length
691         * of the numerator can only be reduced as long as no precision is lost
692         * in the process (meaning it can have powers of 2 removed, like the
693         * denominator).
694         */
695        int numRightShift = positiveNumerator.bitLength() - divisor.bitLength() - (significandLength + 2);
696        if (numRightShift > 0 &&
697            divisor.equals(BigInteger.ONE)) {
698            numRightShift = Math.min(numRightShift, positiveNumerator.getLowestSetBit());
699        }
700        final BigInteger dividend = positiveNumerator.shiftRight(numRightShift);
701
702        final BigInteger quotient = dividend.divide(divisor);
703
704        int quotRightShift = quotient.bitLength() - (significandLength + 1);
705        long significand = roundAndRightShift(
706                quotient,
707                quotRightShift,
708                !divisor.equals(BigInteger.ONE)
709        ).longValue();
710
711        /*
712         * If the significand had to be rounded up, this could have caused the
713         * bit length of the significand to increase by one.
714         */
715        if ((significand & (1L << (significandLength + 1))) != 0) {
716            significand >>= 1;
717            quotRightShift++;
718        }
719
720        /*
721         * Now comes the exponent. The absolute value of this fraction based on
722         * the current local variables is:
723         *
724         * significand * 2^(numRightShift - denRightShift + quotRightShift)
725         *
726         * To get the unbiased exponent for the floating-point value, we need to
727         * add (significandLength) to the above exponent, because all but the
728         * most significant bit of the significand will be treated as a
729         * fractional part. To convert the unbiased exponent to a biased
730         * exponent, we also need to add the exponent bias.
731         */
732        final int exponentBias = (1 << (exponentLength - 1)) - 1;
733        long exponent = (long) numRightShift - denRightShift + quotRightShift + significandLength + exponentBias;
734        final long maxExponent = (1L << exponentLength) - 1L; //special exponent for infinities and NaN
735
736        if (exponent >= maxExponent) { //infinity
737            exponent = maxExponent;
738            significand = 0L;
739        } else if (exponent > 0) { //normalized number
740            significand &= -1L >>> (64 - significandLength); //remove implicit leading 1-bit
741        } else { //smaller than the smallest normalized number
742            /*
743             * We need to round the quotient to fewer than
744             * (significandLength + 1) bits. This must be done with the original
745             * quotient and not with the current significand, because the loss
746             * of precision in the previous rounding might cause a rounding of
747             * the current significand's value to produce a different result
748             * than a rounding of the original quotient.
749             *
750             * So we find out how many high-order bits from the quotient we can
751             * transfer into the significand. The absolute value of the fraction
752             * is:
753             *
754             * quotient * 2^(numRightShift - denRightShift)
755             *
756             * To get the significand, we need to right shift the quotient so
757             * that the above exponent becomes (1 - exponentBias - significandLength)
758             * (the unbiased exponent of a subnormal floating-point number is
759             * defined as equivalent to the minimum unbiased exponent of a
760             * normalized floating-point number, and (- significandLength)
761             * because the significand will be treated as the fractional part).
762             */
763            significand = roundAndRightShift(quotient,
764                                             (1 - exponentBias - significandLength) - (numRightShift - denRightShift),
765                                             !divisor.equals(BigInteger.ONE)).longValue();
766            exponent = 0L;
767
768            /*
769             * Note: It is possible that an otherwise subnormal number will
770             * round up to the smallest normal number. However, this special
771             * case does not need to be treated separately, because the
772             * overflowing highest-order bit of the significand will then simply
773             * become the lowest-order bit of the exponent, increasing the
774             * exponent from 0 to 1 and thus establishing the implicity of the
775             * leading 1-bit.
776             */
777        }
778
779        return (sign << (significandLength + exponentLength)) |
780            (exponent << significandLength) |
781            significand;
782    }
783
784    /**
785     * <p>
786     * Gets the fraction as a {@code double}. This calculates the fraction as
787     * the numerator divided by denominator.
788     * </p>
789     *
790     * @return the fraction as a {@code double}
791     * @see java.lang.Number#doubleValue()
792     */
793    @Override
794    public double doubleValue() {
795        return Double.longBitsToDouble(toFloatingPointBits(11, 52));
796    }
797
798    /**
799     * Rounds an integer to the specified power of two (i.e. the minimum number of
800     * low-order bits that must be zero) and performs a right-shift by this
801     * amount. The rounding mode applied is round to nearest, with ties rounding
802     * to even (meaning the prospective least significant bit must be zero). The
803     * number can optionally be treated as though it contained at
804     * least one 0-bit and one 1-bit in its fractional part, to influence the result in cases
805     * that would otherwise be a tie.
806     * @param value the number to round and right-shift
807     * @param bits the power of two to which to round; must be positive
808     * @param hasFractionalBits whether the number should be treated as though
809     *                          it contained a non-zero fractional part
810     * @return a {@code BigInteger} as described above
811     * @throws IllegalArgumentException if {@code bits <= 0}
812     */
813    private static BigInteger roundAndRightShift(BigInteger value, int bits, boolean hasFractionalBits) {
814        if (bits <= 0) {
815            throw new IllegalArgumentException("bits: " + bits);
816        }
817
818        BigInteger result = value.shiftRight(bits);
819        if (value.testBit(bits - 1) &&
820            (hasFractionalBits ||
821             (value.getLowestSetBit() < bits - 1) ||
822             value.testBit(bits))) {
823            result = result.add(BigInteger.ONE); //round up
824        }
825
826        return result;
827    }
828
829    /**
830     * <p>
831     * Test for the equality of two fractions. If the lowest term numerator and
832     * denominators are the same for both fractions, the two fractions are
833     * considered to be equal.
834     * </p>
835     *
836     * @param other
837     *            fraction to test for equality to this fraction, can be
838     *            <code>null</code>.
839     * @return true if two fractions are equal, false if object is
840     *         <code>null</code>, not an instance of {@link BigFraction}, or not
841     *         equal to this fraction instance.
842     * @see java.lang.Object#equals(java.lang.Object)
843     */
844    @Override
845    public boolean equals(final Object other) {
846        if (this == other) {
847            return true;
848        } else if (other instanceof BigFraction) {
849            final BigFraction rhs = (BigFraction) other;
850
851            if (signum() == rhs.signum()) {
852                return numerator.abs().equals(rhs.numerator.abs()) &&
853                    denominator.abs().equals(rhs.denominator.abs());
854            } else {
855                return false;
856            }
857        }
858
859        return false;
860    }
861
862    /**
863     * <p>
864     * Gets the fraction as a {@code float}. This calculates the fraction as
865     * the numerator divided by denominator.
866     * </p>
867     *
868     * @return the fraction as a {@code float}.
869     * @see java.lang.Number#floatValue()
870     */
871    @Override
872    public float floatValue() {
873        return Float.intBitsToFloat((int) toFloatingPointBits(8, 23));
874    }
875
876    /**
877     * <p>
878     * Access the denominator as a <code>BigInteger</code>.
879     * </p>
880     *
881     * @return the denominator as a <code>BigInteger</code>.
882     */
883    public BigInteger getDenominator() {
884        return denominator;
885    }
886
887    /**
888     * <p>
889     * Access the denominator as a {@code int}.
890     * </p>
891     *
892     * @return the denominator as a {@code int}.
893     */
894    public int getDenominatorAsInt() {
895        return denominator.intValue();
896    }
897
898    /**
899     * <p>
900     * Access the denominator as a {@code long}.
901     * </p>
902     *
903     * @return the denominator as a {@code long}.
904     */
905    public long getDenominatorAsLong() {
906        return denominator.longValue();
907    }
908
909    /**
910     * <p>
911     * Access the numerator as a <code>BigInteger</code>.
912     * </p>
913     *
914     * @return the numerator as a <code>BigInteger</code>.
915     */
916    public BigInteger getNumerator() {
917        return numerator;
918    }
919
920    /**
921     * <p>
922     * Access the numerator as a {@code int}.
923     * </p>
924     *
925     * @return the numerator as a {@code int}.
926     */
927    public int getNumeratorAsInt() {
928        return numerator.intValue();
929    }
930
931    /**
932     * <p>
933     * Access the numerator as a {@code long}.
934     * </p>
935     *
936     * @return the numerator as a {@code long}.
937     */
938    public long getNumeratorAsLong() {
939        return numerator.longValue();
940    }
941
942    /**
943     * <p>
944     * Gets a hashCode for the fraction.
945     * </p>
946     *
947     * @return a hash code value for this object.
948     * @see java.lang.Object#hashCode()
949     */
950    @Override
951    public int hashCode() {
952        return 37 * (37 * 17 + numerator.hashCode()) + denominator.hashCode();
953    }
954
955    /**
956     * <p>
957     * Gets the fraction as an {@code int}. This returns the whole number part
958     * of the fraction.
959     * </p>
960     *
961     * @return the whole number fraction part.
962     * @see java.lang.Number#intValue()
963     */
964    @Override
965    public int intValue() {
966        return numerator.divide(denominator).intValue();
967    }
968
969    /**
970     * <p>
971     * Gets the fraction as a {@code long}. This returns the whole number part
972     * of the fraction.
973     * </p>
974     *
975     * @return the whole number fraction part.
976     * @see java.lang.Number#longValue()
977     */
978    @Override
979    public long longValue() {
980        return numerator.divide(denominator).longValue();
981    }
982
983    /**
984     * <p>
985     * Multiplies the value of this fraction by the passed
986     * <code>BigInteger</code>, returning the result in reduced form.
987     * </p>
988     *
989     * @param bg the {@code BigInteger} to multiply by.
990     * @return a {@code BigFraction} instance with the resulting values.
991     */
992    public BigFraction multiply(final BigInteger bg) {
993        if (numerator.signum() == 0 || bg.signum() == 0) {
994            return ZERO;
995        }
996        return new BigFraction(bg.multiply(numerator), denominator);
997    }
998
999    /**
1000     * <p>
1001     * Multiply the value of this fraction by the passed {@code int}, returning
1002     * the result in reduced form.
1003     * </p>
1004     *
1005     * @param i
1006     *            the {@code int} to multiply by.
1007     * @return a {@link BigFraction} instance with the resulting values.
1008     */
1009    @Override
1010    public BigFraction multiply(final int i) {
1011        if (i == 0 || numerator.signum() == 0) {
1012            return ZERO;
1013        }
1014
1015        return multiply(BigInteger.valueOf(i));
1016    }
1017
1018    /**
1019     * <p>
1020     * Multiply the value of this fraction by the passed {@code long},
1021     * returning the result in reduced form.
1022     * </p>
1023     *
1024     * @param l
1025     *            the {@code long} to multiply by.
1026     * @return a {@link BigFraction} instance with the resulting values.
1027     */
1028    public BigFraction multiply(final long l) {
1029        if (l == 0 || numerator.signum() == 0) {
1030            return ZERO;
1031        }
1032
1033        return multiply(BigInteger.valueOf(l));
1034    }
1035
1036    /**
1037     * <p>
1038     * Multiplies the value of this fraction by another, returning the result in
1039     * reduced form.
1040     * </p>
1041     *
1042     * @param fraction Fraction to multiply by, must not be {@code null}.
1043     * @return a {@link BigFraction} instance with the resulting values.
1044     */
1045    @Override
1046    public BigFraction multiply(final BigFraction fraction) {
1047        if (numerator.signum() == 0 ||
1048            fraction.numerator.signum() == 0) {
1049            return ZERO;
1050        }
1051        return new BigFraction(numerator.multiply(fraction.numerator),
1052                               denominator.multiply(fraction.denominator));
1053    }
1054
1055    /**
1056     * Retrieves the sign of this fraction.
1057     *
1058     * @return -1 if the value is strictly negative, 1 if it is strictly
1059     * positive, 0 if it is 0.
1060     */
1061    public int signum() {
1062        final int numS = numerator.signum();
1063        final int denS = denominator.signum();
1064
1065        if ((numS > 0 && denS > 0) ||
1066            (numS < 0 && denS < 0)) {
1067            return 1;
1068        } else if (numS == 0) {
1069            return 0;
1070        } else {
1071            return -1;
1072        }
1073    }
1074
1075    /**
1076     * <p>
1077     * Return the additive inverse of this fraction, returning the result in
1078     * reduced form.
1079     * </p>
1080     *
1081     * @return the negation of this fraction.
1082     */
1083    @Override
1084    public BigFraction negate() {
1085        return new BigFraction(numerator.negate(), denominator);
1086    }
1087
1088    /**
1089     * <p>
1090     * Returns a {@code BigFraction} whose value is
1091     * {@code (this<sup>exponent</sup>)}, returning the result in reduced form.
1092     * </p>
1093     *
1094     * @param exponent
1095     *            exponent to which this {@code BigFraction} is to be
1096     *            raised.
1097     * @return \(\mathit{this}^{\mathit{exponent}}\).
1098     */
1099    @Override
1100    public BigFraction pow(final int exponent) {
1101        if (exponent == 0) {
1102            return ONE;
1103        }
1104        if (numerator.signum() == 0) {
1105            return this;
1106        }
1107
1108        if (exponent < 0) {
1109            return new BigFraction(denominator.pow(-exponent), numerator.pow(-exponent));
1110        }
1111        return new BigFraction(numerator.pow(exponent), denominator.pow(exponent));
1112    }
1113
1114    /**
1115     * <p>
1116     * Returns a <code>BigFraction</code> whose value is
1117     * \(\mathit{this}^{\mathit{exponent}}\), returning the result in reduced form.
1118     * </p>
1119     *
1120     * @param exponent
1121     *            exponent to which this <code>BigFraction</code> is to be raised.
1122     * @return \(\mathit{this}^{\mathit{exponent}}\) as a <code>BigFraction</code>.
1123     */
1124    public BigFraction pow(final long exponent) {
1125        if (exponent == 0) {
1126            return ONE;
1127        }
1128        if (numerator.signum() == 0) {
1129            return this;
1130        }
1131
1132        if (exponent < 0) {
1133            return new BigFraction(ArithmeticUtils.pow(denominator, -exponent),
1134                                   ArithmeticUtils.pow(numerator,   -exponent));
1135        }
1136        return new BigFraction(ArithmeticUtils.pow(numerator,   exponent),
1137                               ArithmeticUtils.pow(denominator, exponent));
1138    }
1139
1140    /**
1141     * <p>
1142     * Returns a <code>BigFraction</code> whose value is
1143     * \(\mathit{this}^{\mathit{exponent}}\), returning the result in reduced form.
1144     * </p>
1145     *
1146     * @param exponent
1147     *            exponent to which this <code>BigFraction</code> is to be raised.
1148     * @return \(\mathit{this}^{\mathit{exponent}}\) as a <code>BigFraction</code>.
1149     */
1150    public BigFraction pow(final BigInteger exponent) {
1151        if (exponent.signum() == 0) {
1152            return ONE;
1153        }
1154        if (numerator.signum() == 0) {
1155            return this;
1156        }
1157
1158        if (exponent.signum() == -1) {
1159            final BigInteger eNeg = exponent.negate();
1160            return new BigFraction(ArithmeticUtils.pow(denominator, eNeg),
1161                                   ArithmeticUtils.pow(numerator,   eNeg));
1162        }
1163        return new BigFraction(ArithmeticUtils.pow(numerator,   exponent),
1164                               ArithmeticUtils.pow(denominator, exponent));
1165    }
1166
1167    /**
1168     * <p>
1169     * Returns a <code>double</code> whose value is
1170     * \(\mathit{this}^{\mathit{exponent}}\), returning the result in reduced form.
1171     * </p>
1172     *
1173     * @param exponent
1174     *            exponent to which this <code>BigFraction</code> is to be raised.
1175     * @return \(\mathit{this}^{\mathit{exponent}}\).
1176     */
1177    public double pow(final double exponent) {
1178        return Math.pow(numerator.doubleValue(),   exponent) /
1179               Math.pow(denominator.doubleValue(), exponent);
1180    }
1181
1182    /**
1183     * <p>
1184     * Return the multiplicative inverse of this fraction.
1185     * </p>
1186     *
1187     * @return the reciprocal fraction.
1188     */
1189    @Override
1190    public BigFraction reciprocal() {
1191        return new BigFraction(denominator, numerator);
1192    }
1193
1194    /**
1195     * <p>
1196     * Subtracts the value of an {@link BigInteger} from the value of this
1197     * {@code BigFraction}, returning the result in reduced form.
1198     * </p>
1199     *
1200     * @param bg the {@link BigInteger} to subtract, cannot be {@code null}.
1201     * @return a {@code BigFraction} instance with the resulting values.
1202     */
1203    public BigFraction subtract(final BigInteger bg) {
1204        if (bg.signum() == 0) {
1205            return this;
1206        }
1207        if (numerator.signum() == 0) {
1208            return of(bg.negate());
1209        }
1210
1211        return new BigFraction(numerator.subtract(denominator.multiply(bg)), denominator);
1212    }
1213
1214    /**
1215     * <p>
1216     * Subtracts the value of an {@code integer} from the value of this
1217     * {@code BigFraction}, returning the result in reduced form.
1218     * </p>
1219     *
1220     * @param i the {@code integer} to subtract.
1221     * @return a {@code BigFraction} instance with the resulting values.
1222     */
1223    public BigFraction subtract(final int i) {
1224        return subtract(BigInteger.valueOf(i));
1225    }
1226
1227    /**
1228     * <p>
1229     * Subtracts the value of a {@code long} from the value of this
1230     * {@code BigFraction}, returning the result in reduced form.
1231     * </p>
1232     *
1233     * @param l the {@code long} to subtract.
1234     * @return a {@code BigFraction} instance with the resulting values.
1235     */
1236    public BigFraction subtract(final long l) {
1237        return subtract(BigInteger.valueOf(l));
1238    }
1239
1240    /**
1241     * <p>
1242     * Subtracts the value of another fraction from the value of this one,
1243     * returning the result in reduced form.
1244     * </p>
1245     *
1246     * @param fraction {@link BigFraction} to subtract, must not be {@code null}.
1247     * @return a {@link BigFraction} instance with the resulting values
1248     */
1249    @Override
1250    public BigFraction subtract(final BigFraction fraction) {
1251        if (fraction.numerator.signum() == 0) {
1252            return this;
1253        }
1254        if (numerator.signum() == 0) {
1255            return fraction.negate();
1256        }
1257
1258        final BigInteger num;
1259        final BigInteger den;
1260        if (denominator.equals(fraction.denominator)) {
1261            num = numerator.subtract(fraction.numerator);
1262            den = denominator;
1263        } else {
1264            num = (numerator.multiply(fraction.denominator)).subtract((fraction.numerator).multiply(denominator));
1265            den = denominator.multiply(fraction.denominator);
1266        }
1267        return new BigFraction(num, den);
1268    }
1269
1270    /**
1271     * <p>
1272     * Returns the <code>String</code> representing this fraction, ie
1273     * "num / dem" or just "num" if the denominator is one.
1274     * </p>
1275     *
1276     * @return a string representation of the fraction.
1277     * @see java.lang.Object#toString()
1278     */
1279    @Override
1280    public String toString() {
1281        final String str;
1282        if (BigInteger.ONE.equals(denominator)) {
1283            str = numerator.toString();
1284        } else if (BigInteger.ZERO.equals(numerator)) {
1285            str = "0";
1286        } else {
1287            str = numerator + " / " + denominator;
1288        }
1289        return str;
1290    }
1291
1292    /** {@inheritDoc} */
1293    @Override
1294    public BigFraction zero() {
1295        return ZERO;
1296    }
1297
1298    /** {@inheritDoc} */
1299    @Override
1300    public BigFraction one() {
1301        return ONE;
1302    }
1303
1304    /**
1305     * Parses a string that would be produced by {@link #toString()}
1306     * and instantiates the corresponding object.
1307     *
1308     * @param s String representation.
1309     * @return an instance.
1310     * @throws NumberFormatException if the string does not conform
1311     * to the specification.
1312     */
1313    public static BigFraction parse(String s) {
1314        s = s.replace(",", "");
1315        final int slashLoc = s.indexOf('/');
1316        // if no slash, parse as single number
1317        if (slashLoc == -1) {
1318            return BigFraction.of(new BigInteger(s.trim()));
1319        } else {
1320            final BigInteger num = new BigInteger(
1321                    s.substring(0, slashLoc).trim());
1322            final BigInteger denom = new BigInteger(s.substring(slashLoc + 1).trim());
1323            return of(num, denom);
1324        }
1325    }
1326}