Class Fraction
- java.lang.Object
-
- java.lang.Number
-
- org.apache.commons.numbers.fraction.Fraction
-
- All Implemented Interfaces:
java.io.Serializable,java.lang.Comparable<Fraction>,Addition<Fraction>,Multiplication<Fraction>,NativeOperators<Fraction>
public final class Fraction extends java.lang.Number implements java.lang.Comparable<Fraction>, NativeOperators<Fraction>, java.io.Serializable
Representation of a rational number.The number is expressed as the quotient
p/qof two 32-bit integers, a numeratorpand a non-zero denominatorq.This class is immutable. Rational number
- See Also:
- Serialized Form
-
-
Field Summary
Fields Modifier and Type Field Description private static doubleDEFAULT_EPSILONThe default epsilon used for convergence.private static intDEFAULT_MAX_ITERATIONSThe default iterations used for convergence.private intdenominatorThe denominator of this fraction reduced to lowest terms.private static java.lang.StringNOT_FINITEMessage for non-finite input double argument to factory constructors.private intnumeratorThe numerator of this fraction reduced to lowest terms.static FractionONEA fraction representing "1".private static longOVERFLOWThe overflow limit for conversion from a double (2^31).private static longserialVersionUIDSerializable version identifier.static FractionZEROA fraction representing "0".
-
Constructor Summary
Constructors Modifier Constructor Description privateFraction(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.privateFraction(int num)Private constructor: Instances are created using factory methods.privateFraction(int num, int den)Private constructor: Instances are created using factory methods.
-
Method Summary
All Methods Static Methods Instance Methods Concrete Methods Modifier and Type Method Description Fractionabs()Returns the absolute value of this fraction.Fractionadd(int value)Adds the specifiedvalueto this fraction, returning the result in reduced form.Fractionadd(Fraction value)Adds the specifiedvalueto this fraction, returning the result in reduced form.private FractionaddSub(Fraction value, boolean isAdd)Implements add and subtract using algorithm described in Knuth 4.5.1.intcompareTo(Fraction other)Compares this object with the specified object for order using the signed magnitude.Fractiondivide(int value)Divide this fraction by the passedvalue, returning the result in reduced form.Fractiondivide(Fraction value)Divide this fraction by the passedvalue, returning the result in reduced form.doubledoubleValue()Returns thedoublevalue closest to this fraction.booleanequals(java.lang.Object other)Test for equality with another object.floatfloatValue()Returns thefloatvalue closest to this fraction.static Fractionfrom(double value)Create a fraction given the double value.static Fractionfrom(double value, double epsilon, int maxIterations)Create a fraction given the double value and maximum error allowed.static Fractionfrom(double value, int maxDenominator)Create a fraction given the double value and maximum denominator.intgetDenominator()Access the denominator as anint.intgetNumerator()Access the numerator as anint.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.longlongValue()Returns the whole number part of the fraction.Fractionmultiply(int value)Multiply this fraction by the passedvalue, returning the result in reduced form.private Fractionmultiply(int num, int den)Multiply this fraction by the passed fraction decomposed into a numerator and denominator, returning the result in reduced form.Fractionmultiply(Fraction value)Multiply this fraction by the passedvalue, returning the result in reduced form.Fractionnegate()Additive inverse.static Fractionof(int num)Create a fraction given the numerator.static Fractionof(int num, int den)Create a fraction given the numerator and denominator.Fractionone()Identity element.static Fractionparse(java.lang.String s)Returns aFractioninstance representing the specified strings.Fractionpow(int exponent)Returns aFractionwhose value isthisexponent, returning the result in reduced form.Fractionreciprocal()Multiplicative inverse.intsignum()Retrieves the sign of this fraction.Fractionsubtract(int value)Subtracts the specifiedvaluefrom this fraction, returning the result in reduced form.Fractionsubtract(Fraction value)Subtracts the specifiedvaluefrom this fraction, returning the result in reduced form.java.lang.StringtoString()Returns theStringrepresenting this fraction.Fractionzero()Identity element.
-
-
-
Field Detail
-
ZERO
public static final Fraction ZERO
A fraction representing "0".
-
ONE
public static final Fraction ONE
A fraction representing "1".
-
serialVersionUID
private static final long serialVersionUID
Serializable version identifier.- See Also:
- Constant Field Values
-
DEFAULT_EPSILON
private static final double DEFAULT_EPSILON
The default epsilon used for convergence.- See Also:
- Constant Field Values
-
DEFAULT_MAX_ITERATIONS
private static final int DEFAULT_MAX_ITERATIONS
The default iterations used for convergence.- See Also:
- Constant Field Values
-
NOT_FINITE
private static final java.lang.String NOT_FINITE
Message for non-finite input double argument to factory constructors.- See Also:
- Constant Field Values
-
OVERFLOW
private static final long OVERFLOW
The overflow limit for conversion from a double (2^31).- See Also:
- Constant Field Values
-
numerator
private final int numerator
The numerator of this fraction reduced to lowest terms.
-
denominator
private final int denominator
The denominator of this fraction reduced to lowest terms.
-
-
Constructor Detail
-
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:
java.lang.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 withinepsilonofvalue, in absolute terms.maxDenominator- Maximum denominator value allowed.maxIterations- Maximum number of convergents.- Throws:
java.lang.IllegalArgumentException- if the givenvalueis NaN or infinite.java.lang.ArithmeticException- if the continued fraction failed to converge.
-
-
Method Detail
-
from
public static Fraction from(double value)
Create a fraction given the double value.- Parameters:
value- Value to convert to a fraction.- Returns:
- a new instance.
- Throws:
java.lang.IllegalArgumentException- if the givenvalueis NaN or infinite.java.lang.ArithmeticException- if the continued fraction failed to converge.
-
from
public static Fraction from(double value, double epsilon, int maxIterations)
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:
java.lang.IllegalArgumentException- if the givenvalueis NaN or infinite;epsilonis not positive; ormaxIterations < 1.java.lang.ArithmeticException- if the continued fraction failed to converge.
-
from
public static Fraction from(double value, int maxDenominator)
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:
java.lang.IllegalArgumentException- if the givenvalueis NaN or infinite ormaxDenominatoris zero.java.lang.ArithmeticException- if the continued fraction failed to converge.
-
of
public static Fraction of(int num)
Create a fraction given the numerator. The denominator is1.- Parameters:
num- Numerator.- Returns:
- a new instance.
-
of
public static Fraction of(int num, int den)
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:
java.lang.ArithmeticException- if the denominator iszero.
-
parse
public static Fraction parse(java.lang.String s)
Returns aFractioninstance representing the specified strings.If
sisnull, then aNullPointerExceptionis 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
Fractionare 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:
java.lang.NullPointerException- if the string is null.java.lang.NumberFormatException- if the string does not contain a parsable fraction.- See Also:
Integer.parseInt(String),toString()
-
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<Fraction>- Returns:
trueifthisis a neutral element of addition.- See Also:
Addition.zero()
-
one
public Fraction one()
Description copied from interface:MultiplicationIdentity element.- Specified by:
onein interfaceMultiplication<Fraction>- 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<Fraction>- Returns:
trueifthisis a neutral element of multiplication.- See Also:
Multiplication.one()
-
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
public Fraction abs()
Returns the absolute value of this fraction.- Returns:
- the absolute value.
-
reciprocal
public Fraction reciprocal()
Multiplicative inverse.Raises an exception if the fraction is equal to zero.
- Specified by:
reciprocalin interfaceMultiplication<Fraction>- Returns:
this-1.- Throws:
java.lang.ArithmeticException- if the current numerator iszero
-
doubleValue
public double doubleValue()
Returns thedoublevalue closest to this fraction. This calculates the fraction as numerator divided by denominator.- Specified by:
doubleValuein classjava.lang.Number- Returns:
- the fraction as a
double.
-
floatValue
public float floatValue()
Returns thefloatvalue closest to this fraction. This calculates the fraction as numerator divided by denominator.- Specified by:
floatValuein classjava.lang.Number- Returns:
- the fraction as a
float.
-
intValue
public int intValue()
Returns the whole number part of the fraction.- Specified by:
intValuein classjava.lang.Number- Returns:
- the largest
intvalue that is not larger than this fraction.
-
longValue
public long longValue()
Returns the whole number part of the fraction.- Specified by:
longValuein classjava.lang.Number- Returns:
- the largest
longvalue that is not larger than this fraction.
-
add
public Fraction add(int value)
Adds the specifiedvalueto this fraction, returning the result in reduced form.- Parameters:
value- Value to add.- Returns:
this + value.- Throws:
java.lang.ArithmeticException- if the resulting numerator cannot be represented in anint.
-
add
public Fraction add(Fraction value)
Adds the specifiedvalueto this fraction, returning the result in reduced form.
-
subtract
public Fraction subtract(int value)
Subtracts the specifiedvaluefrom this fraction, returning the result in reduced form.- Parameters:
value- Value to subtract.- Returns:
this - value.- Throws:
java.lang.ArithmeticException- if the resulting numerator cannot be represented in anint.
-
subtract
public Fraction subtract(Fraction value)
Subtracts the specifiedvaluefrom this fraction, returning the result in reduced form.- Specified by:
subtractin interfaceNativeOperators<Fraction>- Parameters:
value- Value to subtract.- Returns:
this - value.- Throws:
java.lang.ArithmeticException- if the resulting numerator or denominator cannot be represented in anint.
-
addSub
private Fraction addSub(Fraction value, boolean isAdd)
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:
java.lang.ArithmeticException- if the resulting numerator or denominator cannot be represented in anint.
-
multiply
public Fraction multiply(int value)
Multiply this fraction by the passedvalue, returning the result in reduced form.- Specified by:
multiplyin interfaceNativeOperators<Fraction>- Parameters:
value- Value to multiply by.- Returns:
this * value.- Throws:
java.lang.ArithmeticException- if the resulting numerator cannot be represented in anint.
-
multiply
public Fraction multiply(Fraction value)
Multiply this fraction by the passedvalue, returning the result in reduced form.- Specified by:
multiplyin interfaceMultiplication<Fraction>- Parameters:
value- Value to multiply by.- Returns:
this * value.- Throws:
java.lang.ArithmeticException- if the resulting numerator or denominator cannot be represented in anint.
-
multiply
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.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:
java.lang.ArithmeticException- if the resulting numerator or denominator cannot be represented in anint.
-
divide
public Fraction divide(int value)
Divide this fraction by the passedvalue, returning the result in reduced form.- Parameters:
value- Value to divide by- Returns:
this / value.- Throws:
java.lang.ArithmeticException- if the value to divide by is zero or if the resulting numerator or denominator cannot be represented by anint.
-
divide
public Fraction divide(Fraction value)
Divide this fraction by the passedvalue, returning the result in reduced form.- Specified by:
dividein interfaceNativeOperators<Fraction>- Parameters:
value- Value to divide by- Returns:
this / value.- Throws:
java.lang.ArithmeticException- if the value to divide by is zero or if the resulting numerator or denominator cannot be represented by anint.
-
pow
public Fraction pow(int exponent)
Returns aFractionwhose value isthisexponent, returning the result in reduced form.- Specified by:
powin interfaceNativeOperators<Fraction>- Parameters:
exponent- exponent to which thisFractionis to be raised.- Returns:
thisexponent.- Throws:
java.lang.ArithmeticException- if the intermediate result would overflow.
-
toString
public java.lang.String toString()
Returns theStringrepresenting this fraction. Uses:"0"ifnumeratoris zero."numerator"ifdenominatoris one."numerator / denominator"for all other cases.
- Overrides:
toStringin classjava.lang.Object- Returns:
- a string representation of the fraction.
-
compareTo
public int compareTo(Fraction other)
Compares this object with the specified object for order using the signed magnitude.- Specified by:
compareToin interfacejava.lang.Comparable<Fraction>- Parameters:
other-- Returns:
-
equals
public boolean equals(java.lang.Object other)
Test for equality with another object. If the other object is aFractionthen a comparison is made of the sign and magnitude; otherwisefalseis returned.- Overrides:
equalsin classjava.lang.Object- Parameters:
other-- Returns:
-
hashCode
public int hashCode()
- Overrides:
hashCodein classjava.lang.Object
-
-