Class BigFraction
- All Implemented Interfaces:
Serializable,Comparable<BigFraction>,Addition<BigFraction>,Multiplication<BigFraction>,NativeOperators<BigFraction>
The number is expressed as the quotient p/q of two BigIntegers,
a numerator p and a non-zero denominator q.
This class is immutable. Rational number
- See Also:
-
Field Summary
FieldsModifier and TypeFieldDescriptionprivate static final intThe default iterations used for convergence.private final BigIntegerThe denominator of this fraction reduced to lowest terms.private static final StringMessage for non-finite input double argument to factory constructors.private final BigIntegerThe numerator of this fraction reduced to lowest terms.static final BigFractionA fraction representing "1".private static final longThe overflow limit for conversion from a double (2^31).private static final longSerializable version identifier.static final BigFractionA fraction representing "0". -
Constructor Summary
ConstructorsModifierConstructorDescriptionprivateBigFraction(BigInteger num) Private constructor: Instances are created using factory methods.privateBigFraction(BigInteger num, BigInteger 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 specifiedvalueto this fraction, returning the result in reduced form.add(long value) Adds the specifiedvalueto this fraction, returning the result in reduced form.add(BigInteger value) Adds the specifiedvalueto this fraction, returning the result in reduced form.add(BigFraction value) Adds the specifiedvalueto this fraction, returning the result in reduced form.Returns theBigDecimalrepresentation of this fraction.bigDecimalValue(int scale, RoundingMode roundingMode) Returns theBigDecimalrepresentation of this fraction.bigDecimalValue(RoundingMode roundingMode) Returns theBigDecimalrepresentation of this fraction.intcompareTo(BigFraction other) 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(long value) Divide this fraction by the passedvalue, returning the result in reduced form.divide(BigInteger value) Divide this fraction by the passedvalue, returning the result in reduced form.divide(BigFraction value) Divide this fraction by the passedvalue, returning the result in reduced form.doubleReturns thedoublevalue closest to this fraction.booleanTest for equality with another object.floatReturns thefloatvalue closest to this fraction.static BigFractionfrom(double value) Create a fraction given the double value.static BigFractionfrom(double value, double epsilon, int maxIterations) Create a fraction given the double value and maximum error allowed.private static BigFractionfrom(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.static BigFractionfrom(double value, int maxDenominator) Create a fraction given the double value and maximum denominator.Access the denominator as aBigInteger.intAccess the denominator as anint.longAccess the denominator as along.Access the numerator as aBigInteger.intAccess the numerator as anint.longAccess the numerator as along.inthashCode()intintValue()Returns the whole number part of the fraction.booleanisOne()Check if this is a neutral element of multiplication, i.e.booleanisZero()Check if this is a neutral element of addition, i.e.longReturns the whole number part of the fraction.multiply(int value) Multiply this fraction by the passedvalue, returning the result in reduced form.multiply(long value) Multiply this fraction by the passedvalue, returning the result in reduced form.multiply(BigInteger value) Multiply this fraction by the passedvalue, returning the result in reduced form.multiply(BigFraction value) Multiply this fraction by the passedvalue, returning the result in reduced form.negate()Additive inverse.static BigFractionof(int num) Create a fraction given the numerator.static BigFractionof(int num, int den) Create a fraction given the numerator and denominator.static BigFractionof(long num) Create a fraction given the numerator.static BigFractionof(long num, long den) Create a fraction given the numerator and denominator.static BigFractionof(BigInteger num) Create a fraction given the numerator.static BigFractionof(BigInteger num, BigInteger den) Create a fraction given the numerator and denominator.one()Identity element.static BigFractionReturns aBigFractioninstance representing the specified strings.pow(int exponent) Returns aBigFractionwhose value isthisexponent, returning the result in reduced form.Multiplicative inverse.private static BigIntegerroundAndRightShift(BigInteger value, int bits, boolean hasFractionalBits) Rounds an integer to the specified power of two (i.e.intsignum()Retrieves the sign of this fraction.subtract(int value) Subtracts the specifiedvaluefrom this fraction, returning the result in reduced form.subtract(long value) Subtracts the specifiedvaluefrom this fraction, returning the result in reduced form.subtract(BigInteger value) Subtracts the specifiedvaluefrom this fraction, returning the result in reduced form.subtract(BigFraction value) Subtracts the specifiedvaluefrom this fraction, returning the result in reduced form.private longtoFloatingPointBits(int exponentLength, int significandLength) Calculates the sign bit, the biased exponent and the significand for a binary floating-point representation of thisBigFractionaccording to the IEEE 754 standard, and encodes these values into alongvariable.toString()Returns theStringrepresenting 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_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
The numerator of this fraction reduced to lowest terms. -
denominator
The denominator of this fraction reduced to lowest terms.
-
-
Constructor Details
-
BigFraction
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, must not benull.den- Denominator, must not benull.- Throws:
ArithmeticException- if the denominator is zero.
-
BigFraction
Private constructor: Instances are created using factory methods.This sets the denominator to 1.
- Parameters:
num- Numerator (must not be null).
-
-
Method Details
-
from
private static BigFraction from(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 method 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
- Parameters:
value- Value to convert to a fraction.epsilon- Maximum error allowed. The resulting fraction is withinepsilonofvalue, in absolute terms.maxDenominator- Maximum denominator value allowed.maxIterations- Maximum number of convergents.- Returns:
- a new instance.
- Throws:
IllegalArgumentException- if the givenvalueis NaN or infinite.ArithmeticException- if the continued fraction failed to converge.
-
from
Create a fraction given the double value.This factory method behaves differently to the method
from(double, double, int). It converts the double value exactly, considering its internal bits representation. This works for all values except NaN and infinities and does not requires any loop or convergence threshold.Since this conversion is exact and since double numbers are sometimes approximated, the fraction created may seem strange in some cases. For example, calling
from(1.0 / 3.0)does not create the fraction \( \frac{1}{3} \), but the fraction \( \frac{6004799503160661}{18014398509481984} \) because the double number passed to the method is not exactly \( \frac{1}{3} \) (which cannot be represented exactly in IEEE754).- Parameters:
value- Value to convert to a fraction.- Returns:
- a new instance.
- Throws:
IllegalArgumentException- if the givenvalueis NaN or infinite.- See Also:
-
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 withinepsilonofvalue, in absolute terms.maxIterations- Maximum number of convergents.- Returns:
- a new instance.
- Throws:
IllegalArgumentException- if the givenvalueis NaN or infinite;epsilonis 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
maxDenominatoris used allowing use ofInteger.MIN_VALUEfor 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 givenvalueis NaN or infinite ormaxDenominatoris zero.ArithmeticException- if the continued fraction failed to converge.
-
of
Create a fraction given the numerator. The denominator is1.- Parameters:
num- the numerator.- Returns:
- a new instance.
-
of
Create a fraction given the numerator. The denominator is1.- Parameters:
num- Numerator.- Returns:
- a new instance.
-
of
Create a fraction given the numerator. The denominator is1.- Parameters:
num- Numerator.- Returns:
- a new instance.
- Throws:
NullPointerException- if numerator is null.
-
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- ifdenis zero.
-
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- ifdenis zero.
-
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:
NullPointerException- if numerator or denominator are null.ArithmeticException- if the denominator is zero.
-
parse
Returns aBigFractioninstance representing the specified strings.If
sisnull, then aNullPointerExceptionis thrown.The string must be in a format compatible with that produced by
BigFraction.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 usingBigInteger(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
BigFractionare shown below:"0" = BigFraction.of(0) "42" = BigFraction.of(42) "0 / 1" = BigFraction.of(0, 1) "1 / 3" = BigFraction.of(1, 3) "-4 / 13" = BigFraction.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
BigFraction.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:AdditionIdentity element.- Specified by:
zeroin interfaceAddition<BigFraction>- Returns:
- the field element such that for all
a,zero().add(a).equals(a)istrue.
-
isZero
public boolean isZero()Check if this is a neutral element of addition, i.e.this.add(a)returnsaor an element representing the same value asa.The default implementation calls
equals(zero()). Implementations may want to employ more a efficient method. This may even be required if an implementation has multiple representations ofzeroand itsequalsmethod differentiates between them.- Specified by:
isZeroin interfaceAddition<BigFraction>- Returns:
trueifthisis a neutral element of addition.- See Also:
-
one
Description copied from interface:MultiplicationIdentity element.- Specified by:
onein interfaceMultiplication<BigFraction>- Returns:
- the field element such that for all
a,one().multiply(a).equals(a)istrue.
-
isOne
public boolean isOne()Check if this is a neutral element of multiplication, i.e.this.multiply(a)returnsaor an element representing the same value asa.The default implementation calls
equals(one()). Implementations may want to employ more a efficient method. This may even be required if an implementation has multiple representations ofoneand itsequalsmethod differentiates between them.- Specified by:
isOnein interfaceMultiplication<BigFraction>- Returns:
trueifthisis a neutral element of multiplication.- See Also:
-
getNumerator
Access the numerator as aBigInteger.- Returns:
- the numerator as a
BigInteger.
-
getNumeratorAsInt
public int getNumeratorAsInt()Access the numerator as anint.- Returns:
- the numerator as an
int.
-
getNumeratorAsLong
public long getNumeratorAsLong()Access the numerator as along.- Returns:
- the numerator as a
long.
-
getDenominator
Access the denominator as aBigInteger.- Returns:
- the denominator as a
BigInteger.
-
getDenominatorAsInt
public int getDenominatorAsInt()Access the denominator as anint.- Returns:
- the denominator as an
int.
-
getDenominatorAsLong
public long getDenominatorAsLong()Access the denominator as along.- Returns:
- the denominator as a
long.
-
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:AdditionAdditive inverse.- Specified by:
negatein interfaceAddition<BigFraction>- Returns:
-this.
-
reciprocal
Multiplicative inverse.Raises an exception if the fraction is equal to zero.
- Specified by:
reciprocalin interfaceMultiplication<BigFraction>- Returns:
this-1.- Throws:
ArithmeticException- if the current numerator iszero
-
doubleValue
public double doubleValue()Returns thedoublevalue closest to this fraction.- Specified by:
doubleValuein classNumber- Returns:
- the fraction as a
double.
-
floatValue
public float floatValue()Returns thefloatvalue closest to this fraction.- Specified by:
floatValuein classNumber- Returns:
- the fraction as a
double.
-
intValue
public int intValue()Returns the whole number part of the fraction. -
longValue
public long longValue()Returns the whole number part of the fraction. -
bigDecimalValue
Returns theBigDecimalrepresentation of this fraction. This calculates the fraction as numerator divided by denominator.- Returns:
- the fraction as a
BigDecimal. - Throws:
ArithmeticException- if the exact quotient does not have a terminating decimal expansion.- See Also:
-
bigDecimalValue
Returns theBigDecimalrepresentation of this fraction. This calculates the fraction as numerator divided by denominator following the passed rounding mode.- Parameters:
roundingMode- Rounding mode to apply.- Returns:
- the fraction as a
BigDecimal. - See Also:
-
bigDecimalValue
Returns theBigDecimalrepresentation of this fraction. This calculates the fraction as numerator divided by denominator following the passed scale and rounding mode.- Parameters:
scale- scale of theBigDecimalquotient to be returned. seeBigDecimalfor more information.roundingMode- Rounding mode to apply.- Returns:
- the fraction as a
BigDecimal. - Throws:
ArithmeticException- ifroundingMode==RoundingMode.UNNECESSARYand the specified scale is insufficient to represent the result of the division exactly.- See Also:
-
add
Adds the specifiedvalueto this fraction, returning the result in reduced form.- Parameters:
value- Value to add.- Returns:
this + value.
-
add
Adds the specifiedvalueto this fraction, returning the result in reduced form.- Parameters:
value- Value to add.- Returns:
this + value.
-
add
Adds the specifiedvalueto this fraction, returning the result in reduced form.- Parameters:
value- Value to add.- Returns:
this + value.
-
add
Adds the specifiedvalueto this fraction, returning the result in reduced form.- Specified by:
addin interfaceAddition<BigFraction>- Parameters:
value- Value to add.- Returns:
this + value.
-
subtract
Subtracts the specifiedvaluefrom this fraction, returning the result in reduced form.- Parameters:
value- Value to subtract.- Returns:
this - value.
-
subtract
Subtracts the specifiedvaluefrom this fraction, returning the result in reduced form.- Parameters:
value- Value to subtract.- Returns:
this - value.
-
subtract
Subtracts the specifiedvaluefrom this fraction, returning the result in reduced form.- Parameters:
value- Value to subtract.- Returns:
this - value.
-
subtract
Subtracts the specifiedvaluefrom this fraction, returning the result in reduced form.- Specified by:
subtractin interfaceNativeOperators<BigFraction>- Parameters:
value- Value to subtract.- Returns:
this - value.
-
multiply
Multiply this fraction by the passedvalue, returning the result in reduced form.- Specified by:
multiplyin interfaceNativeOperators<BigFraction>- Parameters:
value- Value to multiply by.- Returns:
this * value.
-
multiply
Multiply this fraction by the passedvalue, returning the result in reduced form.- Parameters:
value- Value to multiply by.- Returns:
this * value.
-
multiply
Multiply this fraction by the passedvalue, returning the result in reduced form.- Parameters:
value- Value to multiply by.- Returns:
this * value.
-
multiply
Multiply this fraction by the passedvalue, returning the result in reduced form.- Specified by:
multiplyin interfaceMultiplication<BigFraction>- Parameters:
value- Value to multiply by.- Returns:
this * value.
-
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
-
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
-
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
-
divide
Divide this fraction by the passedvalue, returning the result in reduced form.- Specified by:
dividein interfaceNativeOperators<BigFraction>- Parameters:
value- Value to divide by- Returns:
this / value.- Throws:
ArithmeticException- if the value to divide by is zero
-
pow
Returns aBigFractionwhose value isthisexponent, returning the result in reduced form.- Specified by:
powin interfaceNativeOperators<BigFraction>- Parameters:
exponent- exponent to which thisBigFractionis to be raised.- Returns:
thisexponent.- Throws:
ArithmeticException- if the intermediate result would overflow.
-
toString
Returns theStringrepresenting this fraction. Uses:"0"ifnumeratoris zero."numerator"ifdenominatoris one."numerator / denominator"for all other cases.
-
compareTo
Compares this object with the specified object for order using the signed magnitude.- Specified by:
compareToin interfaceComparable<BigFraction>- Parameters:
other-- Returns:
-
equals
Test for equality with another object. If the other object is aFractionthen a comparison is made of the sign and magnitude; otherwisefalseis returned. -
hashCode
public int hashCode() -
toFloatingPointBits
private long toFloatingPointBits(int exponentLength, int significandLength) Calculates the sign bit, the biased exponent and the significand for a binary floating-point representation of thisBigFractionaccording to the IEEE 754 standard, and encodes these values into alongvariable. The representative bits are arranged adjacent to each other and placed at the low-order end of the returnedlongvalue, with the least significant bits used for the significand, the next more significant bits for the exponent, and next more significant bit for the sign.Warning: The arguments are not validated.
- Parameters:
exponentLength- the number of bits allowed for the exponent; must be between 1 and 32 (inclusive), and must not be greater than63 - significandLengthsignificandLength- the number of bits allowed for the significand (excluding the implicit leading 1-bit in normalized numbers, e.g. 52 for a double-precision floating-point number); must be between 1 and63 - exponentLength(inclusive)- Returns:
- the bits of an IEEE 754 binary floating-point representation of
this fraction encoded in a
long, as described above.
-
roundAndRightShift
Rounds an integer to the specified power of two (i.e. the minimum number of low-order bits that must be zero) and performs a right-shift by this amount. The rounding mode applied is round to nearest, with ties rounding to even (meaning the prospective least significant bit must be zero). The number can optionally be treated as though it contained at least one 0-bit and one 1-bit in its fractional part, to influence the result in cases that would otherwise be a tie.- Parameters:
value- the number to round and right-shiftbits- the power of two to which to round; must be positivehasFractionalBits- whether the number should be treated as though it contained a non-zero fractional part- Returns:
- a
BigIntegeras described above
-