Class Fraction
- All Implemented Interfaces:
Serializable,Comparable<Fraction>
Fraction is a Number implementation that stores fractions accurately.
This class is immutable, and interoperable with most methods that accept a Number.
Note that this class is intended for common use cases, it is int based and thus suffers from various overflow issues. For a BigInteger based equivalent, please see the Commons Math BigFraction class.
- Since:
- 2.0
- See Also:
-
Field Summary
FieldsModifier and TypeFieldDescriptionprivate final intThe denominator number part of the fraction (the seven in three sevenths).static final FractionFractionrepresentation of 4/5.private final intCached output hashCode (class is immutable).private final intThe numerator number part of the fraction (the three in three sevenths).static final FractionFractionrepresentation of 1.static final FractionFractionrepresentation of 1/5.static final FractionFractionrepresentation of 1/2.static final FractionFractionrepresentation of 1/4.static final FractionFractionrepresentation of 1/3.private static final longRequired for serialization support.static final FractionFractionrepresentation of 3/5.static final FractionFractionrepresentation of 3/4.private StringCached output toProperString (class is immutable).private StringCached output toString (class is immutable).static final FractionFractionrepresentation of 2/5.static final FractionFractionrepresentation of 2/4.static final FractionFractionrepresentation of 2/3.static final FractionFractionrepresentation of 0. -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionabs()Gets a fraction that is the positive equivalent of this one.Adds the value of this fraction to another, returning the result in reduced form.private FractionImplements add and subtract using the algorithm described in The Art of Computer Programming (TAOCP) 4.5.1 by Donald Knuth.private static voidcheckDenominator(int denominator) Checks that a denominator is not zero.intCompares this object to another based on size.Divide the value of this fraction by another.doubleGets the fraction as adouble.booleanCompares this fraction to another object to test if they are equal.floatGets the fraction as afloat.intGets the denominator part of the fraction.static FractiongetFraction(double value) Gets aFractioninstance from adoublevalue.static FractiongetFraction(int numerator, int denominator) Gets aFractioninstance with the 2 parts of a fraction Y/Z.static FractiongetFraction(int whole, int numerator, int denominator) Gets aFractioninstance with the 3 parts of a fraction X Y/Z.static FractiongetFraction(String str) Gets a Fraction from aString.intGets the numerator part of the fraction.intGets the proper numerator, always positive.intGets the proper whole part of the fraction.static FractiongetReducedFraction(int numerator, int denominator) Gets a reducedFractioninstance with the 2 parts of a fraction Y/Z.private static intgreatestCommonDivisor(int u, int v) Gets the greatest common divisor of the absolute value of two numbers, using the "binary gcd" method which avoids division and modulo operations.private static inthash(int value1, int value2) inthashCode()Gets a hashCode for the fraction.intintValue()Gets the fraction as anint.invert()Gets a fraction that is the inverse (1/fraction) of this one.longGets the fraction as along.private static intmulAndCheck(int x, int y) Multiplies two integers, checking for overflow.private static intmulPosAndCheck(int x, int y) Multiplies two non-negative integers, checking for overflow.multiplyBy(Fraction fraction) Multiplies the value of this fraction by another, returning the result in reduced form.negate()Gets a fraction that is the negative (-fraction) of this one.pow(int power) Gets a fraction that is raised to the passed in power.private voidValidates the cached hashCode after deserialization.reduce()Reduce the fraction to the smallest values for the numerator and denominator, returning the result.Subtracts the value of another fraction from the value of this one, returning the result in reduced form.private static NumberFormatExceptiontoNumberFormatException(String str, ArithmeticException cause) Converts anArithmeticExceptionraised while parsing a string into theNumberFormatExceptionthatgetFraction(String)documents, preserving the original exception as the cause.Gets the fraction as a properStringin the format X Y/Z.toString()Gets the fraction as aString.Methods inherited from class java.lang.Number
byteValue, shortValue
-
Field Details
-
serialVersionUID
private static final long serialVersionUIDRequired for serialization support. Lang version 2.0.- See Also:
-
ZERO
Fractionrepresentation of 0. -
ONE
Fractionrepresentation of 1. -
ONE_HALF
Fractionrepresentation of 1/2. -
ONE_THIRD
Fractionrepresentation of 1/3. -
TWO_THIRDS
Fractionrepresentation of 2/3. -
ONE_QUARTER
Fractionrepresentation of 1/4. -
TWO_QUARTERS
Fractionrepresentation of 2/4. -
THREE_QUARTERS
Fractionrepresentation of 3/4. -
ONE_FIFTH
Fractionrepresentation of 1/5. -
TWO_FIFTHS
Fractionrepresentation of 2/5. -
THREE_FIFTHS
Fractionrepresentation of 3/5. -
FOUR_FIFTHS
Fractionrepresentation of 4/5. -
numerator
private final int numeratorThe numerator number part of the fraction (the three in three sevenths). -
denominator
private final int denominatorThe denominator number part of the fraction (the seven in three sevenths). -
hashCode
private final int hashCodeCached output hashCode (class is immutable). -
toString
Cached output toString (class is immutable). -
toProperString
Cached output toProperString (class is immutable).
-
-
Constructor Details
-
Fraction
private Fraction(int numerator, int denominator) Constructs aFractioninstance with the 2 parts of a fraction Y/Z.- Parameters:
numerator- The numerator, for example the three in 'three sevenths'denominator- The denominator, for example the seven in 'three sevenths'
-
-
Method Details
-
checkDenominator
private static void checkDenominator(int denominator) Checks that a denominator is not zero.- Parameters:
denominator- The denominator to check- Throws:
ArithmeticException- Thrown if the denominator is zero.
-
getFraction
Gets aFractioninstance from adoublevalue.This method uses the continued fraction algorithm, computing a maximum of 25 convergents and bounding the denominator by 10,000.
- Parameters:
value- The double value to convert- Returns:
- A new fraction instance that is close to the value
- Throws:
ArithmeticException- Thrown if|value| > Integer.MAX_VALUEorvalue = NaN.ArithmeticException- Thrown if the calculated denominator iszero.ArithmeticException- Thrown if the algorithm does not converge.
-
getFraction
Gets aFractioninstance with the 2 parts of a fraction Y/Z.Any negative signs are resolved to be on the numerator.
- Parameters:
numerator- The numerator, for example the three in 'three sevenths'denominator- The denominator, for example the seven in 'three sevenths'- Returns:
- A new fraction instance
- Throws:
ArithmeticException- Thrown if the denominator iszeroor the denominator isnegativeand the numerator isInteger#MIN_VALUE.
-
getFraction
Gets aFractioninstance with the 3 parts of a fraction X Y/Z.The negative sign must be passed in on the whole number part.
- Parameters:
whole- The whole number, for example the one in 'one and three sevenths'numerator- The numerator, for example the three in 'one and three sevenths'denominator- The denominator, for example the seven in 'one and three sevenths'- Returns:
- A new fraction instance
- Throws:
ArithmeticException- Thrown if the denominator iszero.ArithmeticException- Thrown if the denominator is negative.ArithmeticException- Thrown if the numerator is negative.ArithmeticException- Thrown if the resulting numerator exceedsInteger.MAX_VALUE.
-
getFraction
Gets a Fraction from aString.The formats accepted are:
doubleString containing a dot"X Y/Z""Y/Z""X"(a simple whole number)
and a
.- Parameters:
str- The string to parse, must not benull- Returns:
- The new
Fractioninstance - Throws:
NullPointerException- Thrown if the string isnullNumberFormatException- Thrown if the number format is invalid, or if the string is well-formed but its value cannot be represented as aFraction: a zero denominator such as"1/0", a value outside the range of anintsuch as"9999999999.5", or a mixed number whose combined numerator overflows. For those unrepresentable values, the causalArithmeticExceptionis preserved as thecause.
-
getReducedFraction
Gets a reducedFractioninstance with the 2 parts of a fraction Y/Z.For example, if the input parameters represent 2/4, then the created fraction will be 1/2.
Any negative signs are resolved to be on the numerator.
- Parameters:
numerator- The numerator, for example the three in 'three sevenths'denominator- The denominator, for example the seven in 'three sevenths'- Returns:
- A new fraction instance, with the numerator and denominator reduced
- Throws:
ArithmeticException- Thrown if the denominator iszero, or the reduced numerator or positive denominator cannot be represented as anint.
-
greatestCommonDivisor
private static int greatestCommonDivisor(int u, int v) Gets the greatest common divisor of the absolute value of two numbers, using the "binary gcd" method which avoids division and modulo operations. See Knuth 4.5.2 algorithm B. This algorithm is due to Josef Stein (1961).- Parameters:
u- A non-zero numberv- A non-zero number- Returns:
- The greatest common divisor, never zero
-
hash
private static int hash(int value1, int value2) -
mulAndCheck
private static int mulAndCheck(int x, int y) Multiplies two integers, checking for overflow.- Parameters:
x- A factory- A factor- Returns:
- The product
x*y - Throws:
ArithmeticException- Thrown if the result cannot be represented as an int.
-
mulPosAndCheck
private static int mulPosAndCheck(int x, int y) Multiplies two non-negative integers, checking for overflow.- Parameters:
x- A non-negative factory- A non-negative factor- Returns:
- The product
x*y - Throws:
ArithmeticException- Thrown if the result cannot be represented as an int.
-
toNumberFormatException
Converts anArithmeticExceptionraised while parsing a string into theNumberFormatExceptionthatgetFraction(String)documents, preserving the original exception as the cause.- Parameters:
str- The string being parsed.cause- The arithmetic failure: a zero denominator or a value outside the range of anint.- Returns:
- The exception for the caller to throw, never
null.
-
abs
Gets a fraction that is the positive equivalent of this one.More precisely:
(fraction >= 0 ? this : -fraction)The returned fraction is not reduced.
- Returns:
thisif it is positive, or a new positive fraction instance with the opposite signed numerator
-
add
Adds the value of this fraction to another, returning the result in reduced form. The algorithm follows Knuth, 4.5.1.- Parameters:
fraction- The fraction to add, must not benull- Returns:
- A
Fractioninstance with the resulting values - Throws:
NullPointerException- Thrown if the fraction isnull.ArithmeticException- Thrown if the resulting numerator or denominator exceedsInteger.MAX_VALUE.
-
addSub
Implements add and subtract using the algorithm described in The Art of Computer Programming (TAOCP) 4.5.1 by Donald Knuth.- Parameters:
fraction- The fraction to subtract, must not benullisAdd- true to add, false to subtract- Returns:
- A
Fractioninstance with the resulting values - Throws:
IllegalArgumentException- Thrown if the fraction isnull.ArithmeticException- Thrown if the resulting numerator or denominator cannot be represented in anint.
-
compareTo
Compares this object to another based on size.Note: this class has a natural ordering that is inconsistent with equals, because, for example, equals treats 1/2 and 2/4 as different, whereas compareTo treats them as equal.
- Specified by:
compareToin interfaceComparable<Fraction>- Parameters:
other- The object to compare to- Returns:
- -1 if this is less, 0 if equal, +1 if greater
- Throws:
ClassCastException- Thrown if the object is not aFraction.NullPointerException- Thrown if the object isnull.
-
divideBy
Divide the value of this fraction by another.- Parameters:
fraction- The fraction to divide by, must not benull- Returns:
- A
Fractioninstance with the resulting values - Throws:
NullPointerException- Thrown if the fraction isnull.ArithmeticException- Thrown if the fraction to divide by is zero.ArithmeticException- Thrown if the resulting numerator or denominator exceedsInteger.MAX_VALUE.
-
doubleValue
public double doubleValue()Gets the fraction as adouble. This calculates the fraction as the numerator divided by denominator.- Specified by:
doubleValuein classNumber- Returns:
- The fraction as a
double
-
equals
Compares this fraction to another object to test if they are equal.To be equal, both values must be equal. Thus 2/4 is not equal to 1/2.
-
floatValue
public float floatValue()Gets the fraction as afloat. This calculates the fraction as the numerator divided by denominator.- Specified by:
floatValuein classNumber- Returns:
- The fraction as a
float
-
getDenominator
public int getDenominator()Gets the denominator part of the fraction.- Returns:
- The denominator fraction part
-
getNumerator
public int getNumerator()Gets the numerator part of the fraction.This method may return a value greater than the denominator, an improper fraction, such as the seven in 7/4.
- Returns:
- The numerator fraction part
-
getProperNumerator
public int getProperNumerator()Gets the proper numerator, always positive.An improper fraction 7/4 can be resolved into a proper one, 1 3/4. This method returns the 3 from the proper fraction.
If the fraction is negative such as -7/4, it can be resolved into -1 3/4, so this method returns the positive proper numerator, 3.
- Returns:
- The numerator fraction part of a proper fraction, always positive
-
getProperWhole
public int getProperWhole()Gets the proper whole part of the fraction.An improper fraction 7/4 can be resolved into a proper one, 1 3/4. This method returns the 1 from the proper fraction.
If the fraction is negative such as -7/4, it can be resolved into -1 3/4, so this method returns the positive whole part -1.
- Returns:
- The whole fraction part of a proper fraction, that includes the sign
-
hashCode
public int hashCode()Gets a hashCode for the fraction. -
intValue
public int intValue()Gets the fraction as anint. This returns the whole number part of the fraction. -
invert
Gets a fraction that is the inverse (1/fraction) of this one.The returned fraction is not reduced.
- Returns:
- A new fraction instance with the numerator and denominator inverted.
- Throws:
ArithmeticException- Thrown if the fraction represents zero.
-
longValue
public long longValue()Gets the fraction as along. This returns the whole number part of the fraction. -
multiplyBy
Multiplies the value of this fraction by another, returning the result in reduced form.- Parameters:
fraction- The fraction to multiply by, must not benull- Returns:
- A
Fractioninstance with the resulting values - Throws:
NullPointerException- Thrown if the fraction isnull.ArithmeticException- Thrown if the resulting numerator or denominator exceedsInteger.MAX_VALUE.
-
negate
Gets a fraction that is the negative (-fraction) of this one.The returned fraction is not reduced.
- Returns:
- A new fraction instance with the opposite signed numerator
-
pow
Gets a fraction that is raised to the passed in power.The returned fraction is in reduced form.
- Parameters:
power- The power to raise the fraction to- Returns:
thisif the power is one,ONEif the power is zero (even if the fraction equals ZERO) or a new fraction instance raised to the appropriate power- Throws:
ArithmeticException- Thrown if the resulting numerator or denominator exceedsInteger.MAX_VALUE.
-
readObject
Validates the cached hashCode after deserialization. Throws aInvalidObjectExceptionwhen the stored hashCode does not match the canonical hash of the deserialized numerator/denominator.- Parameters:
in- SeeSerializable.- Throws:
IOException- Thrown as described inSerializable.ClassNotFoundException- Thrown as described inSerializable.InvalidObjectException- Thrown if the hashCode doesn't match the denominator and numerator.
-
reduce
Reduce the fraction to the smallest values for the numerator and denominator, returning the result.For example, if this fraction represents 2/4, then the result will be 1/2.
- Returns:
- A new reduced fraction instance, or this if no simplification possible
-
subtract
Subtracts the value of another fraction from the value of this one, returning the result in reduced form.- Parameters:
fraction- The fraction to subtract, must not benull- Returns:
- A
Fractioninstance with the resulting values - Throws:
NullPointerException- Thrown if the fraction isnull.ArithmeticException- Thrown if the resulting numerator or denominator cannot be represented in anint.
-
toProperString
Gets the fraction as a properStringin the format X Y/Z.The format used in 'wholeNumber numerator/denominator'. If the whole number is zero it will be omitted. If the numerator is zero, only the whole number is returned.
- Returns:
- A
Stringform of the fraction
-
toString
Gets the fraction as aString.The format used is 'numerator/denominator' always.
-