fraction.java
来自「JAVA 文章管理系统源码」· Java 代码 · 共 795 行 · 第 1/2 页
JAVA
795 行
/* ====================================================================
* The Apache Software License, Version 1.1
*
* Copyright (c) 2002-2003 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowledgement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgement may appear in the software itself,
* if and wherever such third-party acknowledgements normally appear.
*
* 4. The names "The Jakarta Project", "Commons", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.commons.lang.math;
import java.io.Serializable;
/**
* <p><code>Fraction</code> is a <code>Number</code> implementation that
* stores fractions accurately.</p>
*
* <p>This class is immutable, and interoperable with most methods that accept
* a <code>Number</code>.</p>
*
* @author Travis Reeder
* @author Stephen Colebourne
* @author Tim O'Brien
* @author Pete Gieser
* @since 2.0
* @version $Id: Fraction.java,v 1.11 2003/08/18 02:22:24 bayard Exp $
*/
public final class Fraction extends Number implements Serializable, Comparable {
/** Serialization lock, Lang version 2.0 */
private static final long serialVersionUID = 65382027393090L;
/**
* <code>Fraction</code> representation of 0.
*/
public static final Fraction ZERO = new Fraction(0, 1);
/**
* <code>Fraction</code> representation of 1.
*/
public static final Fraction ONE = new Fraction(1, 1);
/**
* <code>Fraction</code> representation of 1/2.
*/
public static final Fraction ONE_HALF = new Fraction(1, 2);
/**
* <code>Fraction</code> representation of 1/3.
*/
public static final Fraction ONE_THIRD = new Fraction(1, 3);
/**
* <code>Fraction</code> representation of 2/3.
*/
public static final Fraction TWO_THIRDS = new Fraction(2, 3);
/**
* <code>Fraction</code> representation of 1/4.
*/
public static final Fraction ONE_QUARTER = new Fraction(1, 4);
/**
* <code>Fraction</code> representation of 2/4.
*/
public static final Fraction TWO_QUARTERS = new Fraction(2, 4);
/**
* <code>Fraction</code> representation of 3/4.
*/
public static final Fraction THREE_QUARTERS = new Fraction(3, 4);
/**
* <code>Fraction</code> representation of 1/5.
*/
public static final Fraction ONE_FIFTH = new Fraction(1, 5);
/**
* <code>Fraction</code> representation of 2/5.
*/
public static final Fraction TWO_FIFTHS = new Fraction(2, 5);
/**
* <code>Fraction</code> representation of 3/5.
*/
public static final Fraction THREE_FIFTHS = new Fraction(3, 5);
/**
* <code>Fraction</code> representation of 4/5.
*/
public static final Fraction FOUR_FIFTHS = new Fraction(4, 5);
/**
* The numerator number part of the fraction (the three in three sevenths).
*/
private final int numerator;
/**
* The denominator number part of the fraction (the seven in three sevenths).
*/
private final int denominator;
/**
* Cached output hashCode (class is immutable).
*/
private transient int hashCode = 0;
/**
* Cached output toString (class is immutable).
*/
private transient String toString = null;
/**
* Cached output toProperString (class is immutable).
*/
private transient String toProperString = null;
/**
* <p>Constructs a <code>Fraction</code> instance with the 2 parts
* of a fraction Y/Z.</p>
*
* @param numerator the numerator, for example the three in 'three sevenths'
* @param denominator the denominator, for example the seven in 'three sevenths'
*/
private Fraction(int numerator, int denominator) {
super();
this.numerator = numerator;
this.denominator = denominator;
}
/**
* <p>Creates a <code>Fraction</code> instance with the 2 parts
* of a fraction Y/Z.</p>
*
* <p>Any negative signs are resolved to be on the numerator.</p>
*
* @param numerator the numerator, for example the three in 'three sevenths'
* @param denominator the denominator, for example the seven in 'three sevenths'
* @return a new fraction instance
* @throws ArithmeticException if the denomiator is <code>zero</code>
*/
public static Fraction getFraction(int numerator, int denominator) {
if (denominator == 0) {
throw new ArithmeticException("The denominator must not be zero");
}
if (denominator < 0) {
numerator = -numerator;
denominator = -denominator;
}
return new Fraction(numerator, denominator);
}
/**
* <p>Creates a <code>Fraction</code> instance with the 3 parts
* of a fraction X Y/Z.</p>
*
* <p>The negative sign must be passed in on the whole number part.</p>
*
* @param whole the whole number, for example the one in 'one and three sevenths'
* @param numerator the numerator, for example the three in 'one and three sevenths'
* @param denominator the denominator, for example the seven in 'one and three sevenths'
* @return a new fraction instance
* @throws ArithmeticException if the denomiator is <code>zero</code>
* @throws ArithmeticException if the denomiator is negative
* @throws ArithmeticException if the numerator is negative
* @throws ArithmeticException if the resulting numerator exceeds
* <code>Integer.MAX_VALUE</code>
*/
public static Fraction getFraction(int whole, int numerator, int denominator) {
if (denominator == 0) {
throw new ArithmeticException("The denominator must not be zero");
}
if (denominator < 0) {
throw new ArithmeticException("The denominator must not be negative");
}
if (numerator < 0) {
throw new ArithmeticException("The numerator must not be negative");
}
double numeratorValue = 0;
if (whole < 0) {
numeratorValue = (double) whole * denominator - numerator;
} else {
numeratorValue = (double) whole * denominator + numerator;
}
if (Math.abs(numeratorValue) > Integer.MAX_VALUE) {
throw new ArithmeticException("Numerator too large to represent as an Integer.");
}
return new Fraction((int) numeratorValue, denominator);
}
/**
* <p>Creates a <code>Fraction</code> instance with the 2 parts
* of a fraction Y/Z.</p>
*
* <p>Any negative signs are resolved to be on the numerator.</p>
*
* @param numerator the numerator, for example the three in 'three sevenths'
* @param denominator the denominator, for example the seven in 'three sevenths'
* @return a new fraction instance, with the numerator and denominator reduced
* @throws ArithmeticException if the denomiator is <code>zero</code>
*/
public static Fraction getReducedFraction(int numerator, int denominator) {
if (denominator == 0) {
throw new ArithmeticException("The denominator must not be zero");
}
if (denominator < 0) {
numerator = -numerator;
denominator = -denominator;
}
int gcd = greatestCommonDivisor(Math.abs(numerator), denominator);
return new Fraction(numerator / gcd, denominator / gcd);
}
/**
* <p>Creates a <code>Fraction</code> instance from a <code>double</code> value.</p>
*
* <p>This method uses the <a href="http://archives.math.utk.edu/articles/atuyl/confrac/">
* continued fraction algorithm</a>, computing a maximum of
* 25 convergents and bounding the denominator by 10,000.</p>
*
* @param value the double value to convert
* @return a new fraction instance that is close to the value
* @throws ArithmeticException if <code>|value| > Integer.MAX_VALUE</code>
* or <code>value = NaN</code>
* @throws ArithmeticException if the calculated denomiator is <code>zero</code>
* @throws ArithmeticException if the the algorithm does not converge
*/
public static Fraction getFraction(double value) {
int sign = (value < 0 ? -1 : 1);
value = Math.abs(value);
if (value > Integer.MAX_VALUE || Double.isNaN(value)) {
throw new ArithmeticException
("The value must not be greater than Integer.MAX_VALUE or NaN");
}
int wholeNumber = (int) value;
value -= wholeNumber;
int numer0 = 0; // the pre-previous
int denom0 = 1; // the pre-previous
int numer1 = 1; // the previous
int denom1 = 0; // the previous
int numer2 = 0; // the current, setup in calculation
int denom2 = 0; // the current, setup in calculation
int a1 = (int) value;
int a2 = 0;
double x1 = 1;
double x2 = 0;
double y1 = value - a1;
double y2 = 0;
double delta1, delta2 = Double.MAX_VALUE;
double fraction;
int i = 1;
// System.out.println("---");
do {
delta1 = delta2;
a2 = (int) (x1 / y1);
x2 = y1;
y2 = x1 - a2 * y1;
numer2 = a1 * numer1 + numer0;
denom2 = a1 * denom1 + denom0;
fraction = (double) numer2 / (double) denom2;
delta2 = Math.abs(value - fraction);
// System.out.println(numer2 + " " + denom2 + " " + fraction + " " + delta2 + " " + y1);
a1 = a2;
x1 = x2;
y1 = y2;
numer0 = numer1;
denom0 = denom1;
numer1 = numer2;
denom1 = denom2;
i++;
// System.out.println(">>" + delta1 +" "+ delta2+" "+(delta1 > delta2)+" "+i+" "+denom2);
} while ((delta1 > delta2) && (denom2 <= 10000) && (denom2 > 0) && (i < 25));
if (i == 25) {
throw new ArithmeticException("Unable to convert double to fraction");
}
return getReducedFraction((numer0 + wholeNumber * denom0) * sign, denom0);
}
/**
* <p>Creates a Fraction from a <code>String</code>.</p>
*
* <p>The formats accepted are:</p>
*
* <p>
* <ol>
* <li><code>double</code> String containing a dot</li>
* <li>'X Y/Z'</li>
* <li>'Y/Z'</li>
* </ol>
* and a .</p>
*
* @param str the string to parse, must not be <code>null</code>
* @return the new <code>Fraction</code> instance
* @throws IllegalArgumentException if the string is <code>null</code>
* @throws NumberFormatException if the number format is invalid
*/
public static Fraction getFraction(String str) {
if (str == null) {
throw new IllegalArgumentException("The string must not be null");
}
// parse double format
int pos = str.indexOf('.');
if (pos >= 0) {
return getFraction(Double.parseDouble(str));
}
// parse X Y/Z format
pos = str.indexOf(' ');
if (pos > 0) {
int whole = Integer.parseInt(str.substring(0, pos));
str = str.substring(pos + 1);
pos = str.indexOf('/');
if (pos < 0) {
throw new NumberFormatException("The fraction could not be parsed as the format X Y/Z");
} else {
int denom = Integer.parseInt(str.substring(pos + 1));
return getFraction(
Integer.parseInt(str.substring(0, pos)) + whole * denom,
denom
);
}
}
// parse Y/Z format
pos = str.indexOf('/');
if (pos < 0) {
// simple whole number
return getFraction(Integer.parseInt(str), 1);
} else {
return getFraction(
Integer.parseInt(str.substring(0, pos)),
Integer.parseInt(str.substring(pos + 1))
);
}
}
// Accessors
//-------------------------------------------------------------------
/**
* <p>Gets the numerator part of the fraction.</p>
*
* <p>This method may return a value greater than the denominator, an
* improper fraction, such as the seven in 7/4.</p>
*
* @return the numerator fraction part
*/
public int getNumerator() {
return numerator;
}
/**
* <p>Gets the denominator part of the fraction.</p>
*
* @return the denominator fraction part
*/
public int getDenominator() {
return denominator;
}
/**
* <p>Gets the proper numerator, always positive.</p>
*
* <p>An improper fraction 7/4 can be resolved into a proper one, 1 3/4.
* This method returns the 3 from the proper fraction.</p>
*
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?