Class Fraction
- All Implemented Interfaces:
Serializable
,Comparable<Fraction>
,Addition<Fraction>
,Multiplication<Fraction>
,NativeOperators<Fraction>
The number is expressed as the quotient p/q
of two 32-bit integers,
a numerator p
and a non-zero denominator q
.
This class is immutable. Rational number
- See Also:
-
Field Summary
FieldsModifier and TypeFieldDescriptionprivate static final double
The default epsilon used for convergence.private static final int
The default iterations used for convergence.private final int
The denominator of this fraction reduced to lowest terms.private static final String
Message for non-finite input double argument to factory constructors.private final int
The numerator of this fraction reduced to lowest terms.static final Fraction
A fraction representing "1".private static final long
The overflow limit for conversion from a double (2^31).private static final long
Serializable version identifier.static final Fraction
A fraction representing "0". -
Constructor Summary
ConstructorsModifierConstructorDescriptionprivate
Fraction
(double value, double epsilon, int maxDenominator, int maxIterations) Create a fraction given the double value and either the maximum error allowed or the maximum number of denominator digits.private
Fraction
(int num) Private constructor: Instances are created using factory methods.private
Fraction
(int num, int den) Private constructor: Instances are created using factory methods. -
Method Summary
Modifier and TypeMethodDescriptionabs()
Returns the absolute value of this fraction.add
(int value) Adds the specifiedvalue
to this fraction, returning the result in reduced form.Adds the specifiedvalue
to this fraction, returning the result in reduced form.private Fraction
Implements add and subtract using algorithm described in Knuth 4.5.1.int
Compares this object with the specified object for order using the signed magnitude.divide
(int value) Divide this fraction by the passedvalue
, returning the result in reduced form.Divide this fraction by the passedvalue
, returning the result in reduced form.double
Returns thedouble
value closest to this fraction.boolean
Test for equality with another object.float
Returns thefloat
value closest to this fraction.static Fraction
from
(double value) Create a fraction given the double value.static Fraction
from
(double value, double epsilon, int maxIterations) Create a fraction given the double value and maximum error allowed.static Fraction
from
(double value, int maxDenominator) Create a fraction given the double value and maximum denominator.int
Access the denominator as anint
.int
Access the numerator as anint
.int
hashCode()
int
intValue()
Returns the whole number part of the fraction.private boolean
isZero()
Returns true if this fraction is zero.long
Returns the whole number part of the fraction.multiply
(int value) Multiply this fraction by the passedvalue
, returning the result in reduced form.private Fraction
multiply
(int num, int den) Multiply this fraction by the passed fraction decomposed into a numerator and denominator, returning the result in reduced form.Multiply this fraction by the passedvalue
, returning the result in reduced form.negate()
Additive inverse.static Fraction
of
(int num) Create a fraction given the numerator.static Fraction
of
(int num, int den) Create a fraction given the numerator and denominator.one()
Identity element.static Fraction
Returns aFraction
instance representing the specified strings
.pow
(int exponent) Returns aFraction
whose value isthisexponent
, returning the result in reduced form.Multiplicative inverse.int
signum()
Retrieves the sign of this fraction.subtract
(int value) Subtracts the specifiedvalue
from this fraction, returning the result in reduced form.Subtracts the specifiedvalue
from this fraction, returning the result in reduced form.toString()
Returns theString
representing this fraction.zero()
Identity element.Methods inherited from class java.lang.Number
byteValue, shortValue
-
Field Details
-
ZERO
A fraction representing "0". -
ONE
A fraction representing "1". -
serialVersionUID
private static final long serialVersionUIDSerializable version identifier.- See Also:
-
DEFAULT_EPSILON
private static final double DEFAULT_EPSILONThe default epsilon used for convergence.- See Also:
-
DEFAULT_MAX_ITERATIONS
private static final int DEFAULT_MAX_ITERATIONSThe default iterations used for convergence.- See Also:
-
NOT_FINITE
Message for non-finite input double argument to factory constructors.- See Also:
-
OVERFLOW
private static final long OVERFLOWThe overflow limit for conversion from a double (2^31).- See Also:
-
numerator
private final int numeratorThe numerator of this fraction reduced to lowest terms. -
denominator
private final int denominatorThe denominator of this fraction reduced to lowest terms.
-
-
Constructor Details
-
Fraction
private Fraction(int num, int den) Private constructor: Instances are created using factory methods.This constructor should only be invoked when the fraction is known to be non-zero; otherwise use
ZERO
. This avoids creating the zero representation0 / -1
.- Parameters:
num
- Numerator.den
- Denominator.- Throws:
ArithmeticException
- if the denominator iszero
.
-
Fraction
private Fraction(int num) Private constructor: Instances are created using factory methods.This sets the denominator to 1.
- Parameters:
num
- Numerator.
-
Fraction
private Fraction(double value, double epsilon, int maxDenominator, int maxIterations) Create a fraction given the double value and either the maximum error allowed or the maximum number of denominator digits.NOTE: This constructor is called with:
- EITHER a valid epsilon value and the maxDenominator set to Integer.MAX_VALUE (that way the maxDenominator has no effect)
- OR a valid maxDenominator value and the epsilon value set to zero (that way epsilon only has effect if there is an exact match before the maxDenominator value is reached).
It has been done this way so that the same code can be reused for both scenarios. However this could be confusing to users if it were part of the public API and this method should therefore remain PRIVATE.
See JIRA issue ticket MATH-181 for more details: https://issues.apache.org/jira/browse/MATH-181
Warning: This conversion assumes the value is not zero.
- Parameters:
value
- Value to convert to a fraction. Must not be zero.epsilon
- Maximum error allowed. The resulting fraction is withinepsilon
ofvalue
, in absolute terms.maxDenominator
- Maximum denominator value allowed.maxIterations
- Maximum number of convergents.- Throws:
IllegalArgumentException
- if the givenvalue
is NaN or infinite.ArithmeticException
- if the continued fraction failed to converge.
-
-
Method Details
-
from
Create a fraction given the double value.- Parameters:
value
- Value to convert to a fraction.- Returns:
- a new instance.
- Throws:
IllegalArgumentException
- if the givenvalue
is NaN or infinite.ArithmeticException
- if the continued fraction failed to converge.
-
from
Create a fraction given the double value and maximum error allowed.References:
- Continued Fraction equations (11) and (22)-(26)
- Parameters:
value
- Value to convert to a fraction.epsilon
- Maximum error allowed. The resulting fraction is withinepsilon
ofvalue
, in absolute terms.maxIterations
- Maximum number of convergents.- Returns:
- a new instance.
- Throws:
IllegalArgumentException
- if the givenvalue
is NaN or infinite;epsilon
is not positive; ormaxIterations < 1
.ArithmeticException
- if the continued fraction failed to converge.
-
from
Create a fraction given the double value and maximum denominator.References:
- Continued Fraction equations (11) and (22)-(26)
Note: The magnitude of the
maxDenominator
is used allowing use ofInteger.MIN_VALUE
for a supported maximum denominator of 231.- Parameters:
value
- Value to convert to a fraction.maxDenominator
- Maximum allowed value for denominator.- Returns:
- a new instance.
- Throws:
IllegalArgumentException
- if the givenvalue
is NaN or infinite ormaxDenominator
is zero.ArithmeticException
- if the continued fraction failed to converge.
-
of
Create a fraction given the numerator. The denominator is1
.- Parameters:
num
- Numerator.- Returns:
- a new instance.
-
of
Create a fraction given the numerator and denominator. The fraction is reduced to lowest terms.- Parameters:
num
- Numerator.den
- Denominator.- Returns:
- a new instance.
- Throws:
ArithmeticException
- if the denominator iszero
.
-
parse
Returns aFraction
instance representing the specified strings
.If
s
isnull
, then aNullPointerException
is thrown.The string must be in a format compatible with that produced by
Fraction.toString()
. The format expects an integer optionally followed by a'/'
character and and second integer. Leading and trailing spaces are allowed around each numeric part. Each numeric part is parsed usingInteger.parseInt(String)
. The parts are interpreted as the numerator and optional denominator of the fraction. If absent the denominator is assumed to be "1".Examples of valid strings and the equivalent
Fraction
are shown below:"0" = Fraction.of(0) "42" = Fraction.of(42) "0 / 1" = Fraction.of(0, 1) "1 / 3" = Fraction.of(1, 3) "-4 / 13" = Fraction.of(-4, 13)
Note: The fraction is returned in reduced form and the numerator and denominator may not match the values in the input string. For this reason the result of
Fraction.parse(s).toString().equals(s)
may not betrue
.- Parameters:
s
- String representation.- Returns:
- an instance.
- Throws:
NullPointerException
- if the string is null.NumberFormatException
- if the string does not contain a parsable fraction.- See Also:
-
zero
Description copied from interface:Addition
Identity element. -
one
Description copied from interface:Multiplication
Identity element.- Specified by:
one
in interfaceMultiplication<Fraction>
- Returns:
- the field element such that for all
a
,one().multiply(a).equals(a)
istrue
.
-
getNumerator
public int getNumerator()Access the numerator as anint
.- Returns:
- the numerator as an
int
.
-
getDenominator
public int getDenominator()Access the denominator as anint
.- Returns:
- the denominator as an
int
.
-
signum
public int signum()Retrieves the sign of this fraction.- Returns:
- -1 if the value is strictly negative, 1 if it is strictly positive, 0 if it is 0.
-
abs
Returns the absolute value of this fraction.- Returns:
- the absolute value.
-
negate
Description copied from interface:Addition
Additive inverse. -
reciprocal
Multiplicative inverse.Raises an exception if the fraction is equal to zero.
- Specified by:
reciprocal
in interfaceMultiplication<Fraction>
- Returns:
this-1
.- Throws:
ArithmeticException
- if the current numerator iszero
-
doubleValue
public double doubleValue()Returns thedouble
value closest to this fraction. This calculates the fraction as numerator divided by denominator.- Specified by:
doubleValue
in classNumber
- Returns:
- the fraction as a
double
.
-
floatValue
public float floatValue()Returns thefloat
value closest to this fraction. This calculates the fraction as numerator divided by denominator.- Specified by:
floatValue
in classNumber
- Returns:
- the fraction as a
float
.
-
intValue
public int intValue()Returns the whole number part of the fraction. -
longValue
public long longValue()Returns the whole number part of the fraction. -
add
Adds the specifiedvalue
to this fraction, returning the result in reduced form.- Parameters:
value
- Value to add.- Returns:
this + value
.- Throws:
ArithmeticException
- if the resulting numerator cannot be represented in anint
.
-
add
Adds the specifiedvalue
to this fraction, returning the result in reduced form.- Specified by:
add
in interfaceAddition<Fraction>
- Parameters:
value
- Value to add.- Returns:
this + value
.- Throws:
ArithmeticException
- if the resulting numerator or denominator cannot be represented in anint
.
-
subtract
Subtracts the specifiedvalue
from this fraction, returning the result in reduced form.- Parameters:
value
- Value to subtract.- Returns:
this - value
.- Throws:
ArithmeticException
- if the resulting numerator cannot be represented in anint
.
-
subtract
Subtracts the specifiedvalue
from this fraction, returning the result in reduced form.- Specified by:
subtract
in interfaceNativeOperators<Fraction>
- Parameters:
value
- Value to subtract.- Returns:
this - value
.- Throws:
ArithmeticException
- if the resulting numerator or denominator cannot be represented in anint
.
-
addSub
Implements add and subtract using algorithm described in Knuth 4.5.1.- Parameters:
value
- Fraction to add or subtract.isAdd
- Whether the operation is "add" or "subtract".- Returns:
- a new instance.
- Throws:
ArithmeticException
- if the resulting numerator or denominator cannot be represented in anint
.
-
multiply
Multiply this fraction by the passedvalue
, returning the result in reduced form.- Specified by:
multiply
in interfaceNativeOperators<Fraction>
- Parameters:
value
- Value to multiply by.- Returns:
this * value
.- Throws:
ArithmeticException
- if the resulting numerator cannot be represented in anint
.
-
multiply
Multiply this fraction by the passedvalue
, returning the result in reduced form.- Specified by:
multiply
in interfaceMultiplication<Fraction>
- Parameters:
value
- Value to multiply by.- Returns:
this * value
.- Throws:
ArithmeticException
- if the resulting numerator or denominator cannot be represented in anint
.
-
multiply
Multiply this fraction by the passed fraction decomposed into a numerator and denominator, returning the result in reduced form.This is a utility method to be used by multiply and divide. The decomposed fraction arguments and this fraction are not checked for zero.
- Parameters:
num
- Fraction numerator.den
- Fraction denominator.- Returns:
this * num / den
.- Throws:
ArithmeticException
- if the resulting numerator or denominator cannot be represented in anint
.
-
divide
Divide this fraction by the passedvalue
, returning the result in reduced form.- Parameters:
value
- Value to divide by- Returns:
this / value
.- Throws:
ArithmeticException
- if the value to divide by is zero or if the resulting numerator or denominator cannot be represented by anint
.
-
divide
Divide this fraction by the passedvalue
, returning the result in reduced form.- Specified by:
divide
in interfaceNativeOperators<Fraction>
- Parameters:
value
- Value to divide by- Returns:
this / value
.- Throws:
ArithmeticException
- if the value to divide by is zero or if the resulting numerator or denominator cannot be represented by anint
.
-
pow
Returns aFraction
whose value isthisexponent
, returning the result in reduced form.- Specified by:
pow
in interfaceNativeOperators<Fraction>
- Parameters:
exponent
- exponent to which thisFraction
is to be raised.- Returns:
thisexponent
.- Throws:
ArithmeticException
- if the intermediate result would overflow.
-
toString
Returns theString
representing this fraction. Uses:"0"
ifnumerator
is zero."numerator"
ifdenominator
is one."numerator / denominator"
for all other cases.
-
compareTo
Compares this object with the specified object for order using the signed magnitude.- Specified by:
compareTo
in interfaceComparable<Fraction>
- Parameters:
other
-- Returns:
-
equals
Test for equality with another object. If the other object is aFraction
then a comparison is made of the sign and magnitude; otherwisefalse
is returned. -
hashCode
public int hashCode() -
isZero
private boolean isZero()Returns true if this fraction is zero.- Returns:
- true if zero
-