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 int
The denominator number part of the fraction (the seven in three sevenths).static final Fraction
Fraction
representation of 4/5.private int
Cached output hashCode (class is immutable).private final int
The numerator number part of the fraction (the three in three sevenths).static final Fraction
Fraction
representation of 1.static final Fraction
Fraction
representation of 1/5.static final Fraction
Fraction
representation of 1/2.static final Fraction
Fraction
representation of 1/4.static final Fraction
Fraction
representation of 1/3.private static final long
Required for serialization support.static final Fraction
Fraction
representation of 3/5.static final Fraction
Fraction
representation of 3/4.private String
Cached output toProperString (class is immutable).private String
Cached output toString (class is immutable).static final Fraction
Fraction
representation of 2/5.static final Fraction
Fraction
representation of 2/4.static final Fraction
Fraction
representation of 2/3.static final Fraction
Fraction
representation 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 static int
addAndCheck
(int x, int y) Add two integers, checking for overflow.private Fraction
Implement add and subtract using algorithm described in Knuth 4.5.1.int
Compares this object to another based on size.Divide the value of this fraction by another.double
Gets the fraction as adouble
.boolean
Compares this fraction to another object to test if they are equal.float
Gets the fraction as afloat
.int
Gets the denominator part of the fraction.static Fraction
getFraction
(double value) Creates aFraction
instance from adouble
value.static Fraction
getFraction
(int numerator, int denominator) Creates aFraction
instance with the 2 parts of a fraction Y/Z.static Fraction
getFraction
(int whole, int numerator, int denominator) Creates aFraction
instance with the 3 parts of a fraction X Y/Z.static Fraction
getFraction
(String str) Creates a Fraction from aString
.int
Gets the numerator part of the fraction.int
Gets the proper numerator, always positive.int
Gets the proper whole part of the fraction.static Fraction
getReducedFraction
(int numerator, int denominator) Creates a reducedFraction
instance with the 2 parts of a fraction Y/Z.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.int
hashCode()
Gets a hashCode for the fraction.int
intValue()
Gets the fraction as anint
.invert()
Gets a fraction that is the inverse (1/fraction) of this one.long
Gets the fraction as along
.private static int
mulAndCheck
(int x, int y) Multiply two integers, checking for overflow.private static int
mulPosAndCheck
(int x, int y) Multiply 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.reduce()
Reduce the fraction to the smallest values for the numerator and denominator, returning the result.private static int
subAndCheck
(int x, int y) Subtract two integers, checking for overflow.Subtracts the value of another fraction from the value of this one, returning the result in reduced form.Gets the fraction as a properString
in 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
Fraction
representation of 0. -
ONE
Fraction
representation of 1. -
ONE_HALF
Fraction
representation of 1/2. -
ONE_THIRD
Fraction
representation of 1/3. -
TWO_THIRDS
Fraction
representation of 2/3. -
ONE_QUARTER
Fraction
representation of 1/4. -
TWO_QUARTERS
Fraction
representation of 2/4. -
THREE_QUARTERS
Fraction
representation of 3/4. -
ONE_FIFTH
Fraction
representation of 1/5. -
TWO_FIFTHS
Fraction
representation of 2/5. -
THREE_FIFTHS
Fraction
representation of 3/5. -
FOUR_FIFTHS
Fraction
representation 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 transient 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 aFraction
instance 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
-
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:
ArithmeticException
- if the result can not be represented as an int
-
getFraction
Creates aFraction
instance from adouble
value.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
- if|value| > Integer.MAX_VALUE
orvalue = NaN
ArithmeticException
- if the calculated denominator iszero
ArithmeticException
- if the algorithm does not converge
-
getFraction
Creates aFraction
instance 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
- if the denominator iszero
or the denominator isnegative
and the numerator isInteger#MIN_VALUE
-
getFraction
Creates aFraction
instance 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
- if the denominator iszero
ArithmeticException
- if the denominator is negativeArithmeticException
- if the numerator is negativeArithmeticException
- if the resulting numerator exceedsInteger.MAX_VALUE
-
getFraction
Creates a Fraction from aString
.The formats accepted are:
double
String 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
Fraction
instance - Throws:
NullPointerException
- if the string isnull
NumberFormatException
- if the number format is invalid
-
getReducedFraction
Creates a reducedFraction
instance 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
- if the denominator iszero
-
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:
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:
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:
ArithmeticException
- if the result can not be represented as an int
-
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:
this
if 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
Fraction
instance with the resulting values - Throws:
NullPointerException
- if the fraction isnull
ArithmeticException
- if the resulting numerator or denominator exceedsInteger.MAX_VALUE
-
addSub
Implement add and subtract using algorithm described in Knuth 4.5.1.- Parameters:
fraction
- the fraction to subtract, must not benull
isAdd
- true to add, false to subtract- Returns:
- a
Fraction
instance with the resulting values - Throws:
IllegalArgumentException
- if the fraction isnull
ArithmeticException
- 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:
compareTo
in interfaceComparable<Fraction>
- Parameters:
other
- the object to compare to- Returns:
- -1 if this is less, 0 if equal, +1 if greater
- Throws:
ClassCastException
- if the object is not aFraction
NullPointerException
- 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
Fraction
instance with the resulting values - Throws:
NullPointerException
- if the fraction isnull
ArithmeticException
- if the fraction to divide by is zeroArithmeticException
- 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:
doubleValue
in 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:
floatValue
in 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
- 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
Fraction
instance with the resulting values - Throws:
NullPointerException
- if the fraction isnull
ArithmeticException
- 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:
this
if the power is one,ONE
if the power is zero (even if the fraction equals ZERO) or a new fraction instance raised to the appropriate power- Throws:
ArithmeticException
- if the resulting numerator or denominator exceedsInteger.MAX_VALUE
-
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
Fraction
instance with the resulting values - Throws:
NullPointerException
- if the fraction isnull
ArithmeticException
- if the resulting numerator or denominator cannot be represented in anint
.
-
toProperString
Gets the fraction as a properString
in 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
String
form of the fraction
-
toString
Gets the fraction as aString
.The format used is 'numerator/denominator' always.
-