Class Fraction
- java.lang.Object
-
- java.lang.Number
-
- org.apache.commons.lang3.math.Fraction
-
- All Implemented Interfaces:
java.io.Serializable,java.lang.Comparable<Fraction>
public final class Fraction extends java.lang.Number implements java.lang.Comparable<Fraction>
Fractionis aNumberimplementation 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:
- Serialized Form
-
-
Field Summary
Fields Modifier and Type Field Description private intdenominatorThe denominator number part of the fraction (the seven in three sevenths).static FractionFOUR_FIFTHSFractionrepresentation of 4/5.private inthashCodeCached output hashCode (class is immutable).private intnumeratorThe numerator number part of the fraction (the three in three sevenths).static FractionONEFractionrepresentation of 1.static FractionONE_FIFTHFractionrepresentation of 1/5.static FractionONE_HALFFractionrepresentation of 1/2.static FractionONE_QUARTERFractionrepresentation of 1/4.static FractionONE_THIRDFractionrepresentation of 1/3.private static longserialVersionUIDRequired for serialization support.static FractionTHREE_FIFTHSFractionrepresentation of 3/5.static FractionTHREE_QUARTERSFractionrepresentation of 3/4.private java.lang.StringtoProperStringCached output toProperString (class is immutable).private java.lang.StringtoStringCached output toString (class is immutable).static FractionTWO_FIFTHSFractionrepresentation of 2/5.static FractionTWO_QUARTERSFractionrepresentation of 2/4.static FractionTWO_THIRDSFractionrepresentation of 2/3.static FractionZEROFractionrepresentation of 0.
-
Constructor Summary
Constructors Modifier Constructor Description privateFraction(int numerator, int denominator)Constructs aFractioninstance with the 2 parts of a fraction Y/Z.
-
Method Summary
All Methods Static Methods Instance Methods Concrete Methods Modifier and Type Method Description Fractionabs()Gets a fraction that is the positive equivalent of this one.Fractionadd(Fraction fraction)Adds the value of this fraction to another, returning the result in reduced form.private static intaddAndCheck(int x, int y)Add two integers, checking for overflow.private FractionaddSub(Fraction fraction, boolean isAdd)Implement add and subtract using algorithm described in Knuth 4.5.1.intcompareTo(Fraction other)Compares this object to another based on size.FractiondivideBy(Fraction fraction)Divide the value of this fraction by another.doubledoubleValue()Gets the fraction as adouble.booleanequals(java.lang.Object obj)Compares this fraction to another object to test if they are equal.floatfloatValue()Gets the fraction as afloat.intgetDenominator()Gets the denominator part of the fraction.static FractiongetFraction(double value)Creates aFractioninstance from adoublevalue.static FractiongetFraction(int numerator, int denominator)Creates aFractioninstance with the 2 parts of a fraction Y/Z.static FractiongetFraction(int whole, int numerator, int denominator)Creates aFractioninstance with the 3 parts of a fraction X Y/Z.static FractiongetFraction(java.lang.String str)Creates a Fraction from aString.intgetNumerator()Gets the numerator part of the fraction.intgetProperNumerator()Gets the proper numerator, always positive.intgetProperWhole()Gets the proper whole part of the fraction.static FractiongetReducedFraction(int numerator, int denominator)Creates 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.inthashCode()Gets a hashCode for the fraction.intintValue()Gets the fraction as anint.Fractioninvert()Gets a fraction that is the inverse (1/fraction) of this one.longlongValue()Gets the fraction as along.private static intmulAndCheck(int x, int y)Multiply two integers, checking for overflow.private static intmulPosAndCheck(int x, int y)Multiply two non-negative integers, checking for overflow.FractionmultiplyBy(Fraction fraction)Multiplies the value of this fraction by another, returning the result in reduced form.Fractionnegate()Gets a fraction that is the negative (-fraction) of this one.Fractionpow(int power)Gets a fraction that is raised to the passed in power.Fractionreduce()Reduce the fraction to the smallest values for the numerator and denominator, returning the result.private static intsubAndCheck(int x, int y)Subtract two integers, checking for overflow.Fractionsubtract(Fraction fraction)Subtracts the value of another fraction from the value of this one, returning the result in reduced form.java.lang.StringtoProperString()Gets the fraction as a properStringin the format X Y/Z.java.lang.StringtoString()Gets the fraction as aString.
-
-
-
Field Detail
-
serialVersionUID
private static final long serialVersionUID
Required for serialization support. Lang version 2.0.- See Also:
Serializable, Constant Field Values
-
ZERO
public static final Fraction ZERO
Fractionrepresentation of 0.
-
ONE
public static final Fraction ONE
Fractionrepresentation of 1.
-
ONE_HALF
public static final Fraction ONE_HALF
Fractionrepresentation of 1/2.
-
ONE_THIRD
public static final Fraction ONE_THIRD
Fractionrepresentation of 1/3.
-
TWO_THIRDS
public static final Fraction TWO_THIRDS
Fractionrepresentation of 2/3.
-
ONE_QUARTER
public static final Fraction ONE_QUARTER
Fractionrepresentation of 1/4.
-
TWO_QUARTERS
public static final Fraction TWO_QUARTERS
Fractionrepresentation of 2/4.
-
THREE_QUARTERS
public static final Fraction THREE_QUARTERS
Fractionrepresentation of 3/4.
-
ONE_FIFTH
public static final Fraction ONE_FIFTH
Fractionrepresentation of 1/5.
-
TWO_FIFTHS
public static final Fraction TWO_FIFTHS
Fractionrepresentation of 2/5.
-
THREE_FIFTHS
public static final Fraction THREE_FIFTHS
Fractionrepresentation of 3/5.
-
FOUR_FIFTHS
public static final Fraction FOUR_FIFTHS
Fractionrepresentation of 4/5.
-
numerator
private final int numerator
The numerator number part of the fraction (the three in three sevenths).
-
denominator
private final int denominator
The denominator number part of the fraction (the seven in three sevenths).
-
hashCode
private transient int hashCode
Cached output hashCode (class is immutable).
-
toString
private transient java.lang.String toString
Cached output toString (class is immutable).
-
toProperString
private transient java.lang.String toProperString
Cached output toProperString (class is immutable).
-
-
Method Detail
-
getFraction
public static Fraction getFraction(int numerator, int denominator)
Creates a
Fractioninstance 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:
java.lang.ArithmeticException- if the denominator iszeroor the denominator isnegativeand the numerator isInteger#MIN_VALUE
-
getFraction
public static Fraction getFraction(int whole, int numerator, int denominator)
Creates a
Fractioninstance 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:
java.lang.ArithmeticException- if the denominator iszerojava.lang.ArithmeticException- if the denominator is negativejava.lang.ArithmeticException- if the numerator is negativejava.lang.ArithmeticException- if the resulting numerator exceedsInteger.MAX_VALUE
-
getReducedFraction
public static Fraction getReducedFraction(int numerator, int denominator)
Creates a reduced
Fractioninstance 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:
java.lang.ArithmeticException- if the denominator iszero
-
getFraction
public static Fraction getFraction(double value)
Creates a
Fractioninstance 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:
java.lang.ArithmeticException- if|value| > Integer.MAX_VALUEorvalue = NaNjava.lang.ArithmeticException- if the calculated denominator iszerojava.lang.ArithmeticException- if the algorithm does not converge
-
getFraction
public static Fraction getFraction(java.lang.String str)
Creates a Fraction from a
String.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:
java.lang.NullPointerException- if the string isnulljava.lang.NumberFormatException- if the number format is invalid
-
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
-
getDenominator
public int getDenominator()
Gets the denominator part of the fraction.
- Returns:
- the denominator 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
-
intValue
public int intValue()
Gets the fraction as an
int. This returns the whole number part of the fraction.- Specified by:
intValuein classjava.lang.Number- Returns:
- the whole number fraction part
-
longValue
public long longValue()
Gets the fraction as a
long. This returns the whole number part of the fraction.- Specified by:
longValuein classjava.lang.Number- Returns:
- the whole number fraction part
-
floatValue
public float floatValue()
Gets the fraction as a
float. This calculates the fraction as the numerator divided by denominator.- Specified by:
floatValuein classjava.lang.Number- Returns:
- the fraction as a
float
-
doubleValue
public double doubleValue()
Gets the fraction as a
double. This calculates the fraction as the numerator divided by denominator.- Specified by:
doubleValuein classjava.lang.Number- Returns:
- the fraction as a
double
-
reduce
public Fraction 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
-
invert
public 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:
java.lang.ArithmeticException- if the fraction represents zero.
-
negate
public Fraction 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
-
abs
public Fraction 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
-
pow
public Fraction pow(int power)
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:
java.lang.ArithmeticException- if the resulting numerator or denominator exceedsInteger.MAX_VALUE
-
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
-
mulAndCheck
private static int mulAndCheck(int x, int y)Multiply two integers, checking for overflow.- Parameters:
x- a factory- a factor- Returns:
- the product
x*y - Throws:
java.lang.ArithmeticException- if the result can not be represented as an int
-
mulPosAndCheck
private static int mulPosAndCheck(int x, int y)Multiply two non-negative integers, checking for overflow.- Parameters:
x- a non-negative factory- a non-negative factor- Returns:
- the product
x*y - Throws:
java.lang.ArithmeticException- if the result can not be represented as an int
-
addAndCheck
private static int addAndCheck(int x, int y)Add two integers, checking for overflow.- Parameters:
x- an addendy- an addend- Returns:
- the sum
x+y - Throws:
java.lang.ArithmeticException- if the result can not be represented as an int
-
subAndCheck
private static int subAndCheck(int x, int y)Subtract two integers, checking for overflow.- Parameters:
x- the minuendy- the subtrahend- Returns:
- the difference
x-y - Throws:
java.lang.ArithmeticException- if the result can not be represented as an int
-
add
public Fraction add(Fraction fraction)
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:
java.lang.IllegalArgumentException- if the fraction isnulljava.lang.ArithmeticException- if the resulting numerator or denominator exceedsInteger.MAX_VALUE
-
subtract
public Fraction subtract(Fraction fraction)
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:
java.lang.IllegalArgumentException- if the fraction isnulljava.lang.ArithmeticException- if the resulting numerator or denominator cannot be represented in anint.
-
addSub
private Fraction addSub(Fraction fraction, boolean isAdd)
Implement add and subtract using algorithm described in Knuth 4.5.1.- Parameters:
fraction- the fraction to subtract, must not benullisAdd- true to add, false to subtract- Returns:
- a
Fractioninstance with the resulting values - Throws:
java.lang.IllegalArgumentException- if the fraction isnulljava.lang.ArithmeticException- if the resulting numerator or denominator cannot be represented in anint.
-
multiplyBy
public Fraction multiplyBy(Fraction fraction)
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:
java.lang.NullPointerException- if the fraction isnulljava.lang.ArithmeticException- if the resulting numerator or denominator exceedsInteger.MAX_VALUE
-
divideBy
public Fraction divideBy(Fraction fraction)
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:
java.lang.NullPointerException- if the fraction isnulljava.lang.ArithmeticException- if the fraction to divide by is zerojava.lang.ArithmeticException- if the resulting numerator or denominator exceedsInteger.MAX_VALUE
-
equals
public boolean equals(java.lang.Object obj)
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.
- Overrides:
equalsin classjava.lang.Object- Parameters:
obj- the reference object with which to compare- Returns:
trueif this object is equal
-
hashCode
public int hashCode()
Gets a hashCode for the fraction.
- Overrides:
hashCodein classjava.lang.Object- Returns:
- a hash code value for this object
-
compareTo
public int compareTo(Fraction other)
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 interfacejava.lang.Comparable<Fraction>- Parameters:
other- the object to compare to- Returns:
- -1 if this is less, 0 if equal, +1 if greater
- Throws:
java.lang.ClassCastException- if the object is not aFractionjava.lang.NullPointerException- if the object isnull
-
toString
public java.lang.String toString()
Gets the fraction as a
String.The format used is 'numerator/denominator' always.
- Overrides:
toStringin classjava.lang.Object- Returns:
- a
Stringform of the fraction
-
toProperString
public java.lang.String toProperString()
Gets the fraction as a proper
Stringin 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
-
-