sdr 0.7

net.cscott.sdr.util
Class Fraction

java.lang.Object
  extended by java.lang.Number
      extended by net.cscott.sdr.util.Fraction
All Implemented Interfaces:
Serializable, Comparable<Fraction>

public class Fraction
extends Number
implements Serializable, Comparable<Fraction>

Fraction is a Number which implements exact arithmetic on fractions. All computations which do not overflow can be done without any accumulated rounding errors.

The implementation of the Fraction class is based on the algorithms described in Donald E. Knuth's The Art of Computer Programming, volume 2, sections 4.5 through 4.5.2. In particular, fractions are represented as a pair of integers (n/d) where n and d are relatively prime to each other and d>0. The number zero is represented as (0/1). Fractions are always maintained in "simplest form" and numerically-equal fractions always return true from the equals() method.

(Note however that there is a "backwards-compatibility" mode enabled if you use the deprecated getFraction() constructor; in this case it will appear that unsimplified fractions are maintained, and !getFraction(1,2).equals(getFraction(2,4)). Use of getFraction() is not recommended.)

This class is immutable, and interoperable with most methods that accept a Number.

Since:
2.0
Version:
$Id: Fraction.java,v 1.9 2006-10-30 21:31:26 cananian Exp $
Author:
C. Scott Ananian, Travis Reeder, Stephen Colebourne, Tim O'Brien, Pete Gieser
See Also:
Serialized Form

Field Summary
static Fraction FIVE_EIGHTHS
          Fraction representation of 5/8.
static Fraction FOUR
          Fraction representation of 4.
static Fraction FOUR_FIFTHS
          Fraction representation of 4/5.
static Fraction mFOUR
          Fraction representation of -4.
static Fraction mONE
          Fraction representation of -1.
static Fraction mONE_HALF
          Fraction representation of -1/2.
static Fraction mONE_QUARTER
          Fraction representation of -1/4.
static Fraction mONE_THIRD
          Fraction representation of -1/3.
static Fraction mTHREE
          Fraction representation of -3.
static Fraction mTHREE_HALVES
          Fraction representation of -3/2.
static Fraction mTHREE_QUARTERS
          Fraction representation of -3/4.
static Fraction mTWO
          Fraction representation of -2.
static Fraction mTWO_THIRDS
          Fraction representation of -2/3.
static Fraction ONE
          Fraction representation of 1.
static Fraction ONE_EIGHTH
          Fraction representation of 1/8.
static Fraction ONE_FIFTH
          Fraction representation of 1/5.
static Fraction ONE_HALF
          Fraction representation of 1/2.
static Fraction ONE_QUARTER
          Fraction representation of 1/4.
static Fraction ONE_THIRD
          Fraction representation of 1/3.
static Fraction SEVEN_EIGHTHS
          Fraction representation of 7/8.
static Fraction THREE
          Fraction representation of 3.
static Fraction THREE_EIGHTHS
          Fraction representation of 3/8.
static Fraction THREE_FIFTHS
          Fraction representation of 3/5.
static Fraction THREE_HALVES
          Fraction representation of 3/2.
static Fraction THREE_QUARTERS
          Fraction representation of 3/4.
static Fraction TWO
          Fraction representation of 2.
static Fraction TWO_FIFTHS
          Fraction representation of 2/5.
static Fraction TWO_THIRDS
          Fraction representation of 2/3.
static Fraction ZERO
          Fraction representation of 0.
 
Method Summary
 Fraction abs()
          Gets a fraction that is the positive equivalent of this one.
 Fraction add(Fraction fraction)
          Adds the value of this fraction to another.
 int compareTo(Fraction other)
          Compares this object to another based on size.
 Fraction divide(Fraction fraction)
          Divide the value of this fraction by another.
 Fraction divideBy(Fraction fraction)
          Deprecated. Renamed to divide()
 double doubleValue()
          Gets the fraction as a double.
 boolean equals(Object obj)
          Compares this fraction to another object to test if they are equal.
 float floatValue()
          Gets the fraction as a float.
 int floor()
          Return the largest integer less than or equal to this fraction.
 int getDenominator()
          Gets the denominator part of the fraction.
static Fraction getFraction(double value)
          Deprecated. Renamed this method to valueOf() for consistency.
static Fraction getFraction(int numerator, int denominator)
          Deprecated. For reasons of backwards-compatibility, this method does not simplify fractions. The Fraction objects returned are thus subject to overflow. It should not be used in new code. Use valueOf() instead.
static Fraction getFraction(int whole, int numerator, int denominator)
          Deprecated. For reasons of backwards-compatibility, this method does not simplify fractions. The Fraction objects returned are thus subject to overflow. It should not be used in new code. Use valueOf() instead.
static Fraction getFraction(String str)
          Deprecated. For reasons of backwards-compatibility, this method does not simplify fractions. The Fraction objects returned are thus subject to overflow. It should not be used in new code. Use valueOf() instead.
 int getNumerator()
          Gets the numerator part of the fraction.
 int getProperNumerator()
          Gets the proper numerator, always positive.
 int getProperWhole()
          Deprecated. Returns unexpected values for numbers between -1 and 0
static Fraction getReducedFraction(int numerator, int denominator)
          Deprecated. All fractions are now stored as reduced fractions; use the valueOf() method instead.
 int hashCode()
          Gets a hashCode for the fraction.
 int intValue()
          Gets the fraction as an int.
 Fraction invert()
          Gets a fraction that is the inverse (1/fraction) of this one.
 long longValue()
          Gets the fraction as a long.
 Fraction multiply(Fraction fraction)
          Multiplies the value of this fraction by another.
 Fraction multiplyBy(Fraction fraction)
          Deprecated. Renamed to multiply()
 Fraction negate()
          Gets a fraction that is the negative (-fraction) of this one.
 Fraction pow(int power)
          Gets a fraction that is raised to the passed in power.
 Fraction quantize(int nDenom)
          Quantize the given fraction to the nearest x/nDenom.
 Fraction reduce()
          Deprecated. Unless you are using deprecated methods this operation is a no-op.
 String repr()
          Returns an executable representation of this Fraction.
 Fraction subtract(Fraction fraction)
          Subtracts the value of another fraction from the value of this one.
 String toProperString()
          Gets the fraction as a proper String in the format X Y/Z.
 String toString()
          Gets the fraction as a String.
static Fraction valueOf(double value)
          Creates a Fraction instance from a double value.
static Fraction valueOf(int value)
          Creates a Fraction instance from a int value.
static Fraction valueOf(int numerator, int denominator)
          Creates a Fraction instance with the 2 parts of a fraction Y/Z.
static Fraction valueOf(int whole, int numerator, int denominator)
          Creates a Fraction instance with the 3 parts of a fraction X Y/Z.
static Fraction valueOf(String str)
          Creates a Fraction from a String.
 
Methods inherited from class java.lang.Number
byteValue, shortValue
 
Methods inherited from class java.lang.Object
clone, finalize, getClass, notify, notifyAll, wait, wait, wait
 

Field Detail

ZERO

public static final Fraction ZERO
Fraction representation of 0.


mONE

public static final Fraction mONE
Fraction representation of -1.


ONE

public static final Fraction ONE
Fraction representation of 1.


mTWO

public static final Fraction mTWO
Fraction representation of -2.


TWO

public static final Fraction TWO
Fraction representation of 2.


mTHREE

public static final Fraction mTHREE
Fraction representation of -3.


THREE

public static final Fraction THREE
Fraction representation of 3.


mFOUR

public static final Fraction mFOUR
Fraction representation of -4.


FOUR

public static final Fraction FOUR
Fraction representation of 4.


mONE_HALF

public static final Fraction mONE_HALF
Fraction representation of -1/2.


ONE_HALF

public static final Fraction ONE_HALF
Fraction representation of 1/2.


mTHREE_HALVES

public static final Fraction mTHREE_HALVES
Fraction representation of -3/2.


THREE_HALVES

public static final Fraction THREE_HALVES
Fraction representation of 3/2.


mONE_THIRD

public static final Fraction mONE_THIRD
Fraction representation of -1/3.


ONE_THIRD

public static final Fraction ONE_THIRD
Fraction representation of 1/3.


mTWO_THIRDS

public static final Fraction mTWO_THIRDS
Fraction representation of -2/3.


TWO_THIRDS

public static final Fraction TWO_THIRDS
Fraction representation of 2/3.


mONE_QUARTER

public static final Fraction mONE_QUARTER
Fraction representation of -1/4.


ONE_QUARTER

public static final Fraction ONE_QUARTER
Fraction representation of 1/4.


mTHREE_QUARTERS

public static final Fraction mTHREE_QUARTERS
Fraction representation of -3/4.


THREE_QUARTERS

public static final Fraction THREE_QUARTERS
Fraction representation of 3/4.


ONE_FIFTH

public static final Fraction ONE_FIFTH
Fraction representation of 1/5.


TWO_FIFTHS

public static final Fraction TWO_FIFTHS
Fraction representation of 2/5.


THREE_FIFTHS

public static final Fraction THREE_FIFTHS
Fraction representation of 3/5.


FOUR_FIFTHS

public static final Fraction FOUR_FIFTHS
Fraction representation of 4/5.


ONE_EIGHTH

public static final Fraction ONE_EIGHTH
Fraction representation of 1/8.


THREE_EIGHTHS

public static final Fraction THREE_EIGHTHS
Fraction representation of 3/8.


FIVE_EIGHTHS

public static final Fraction FIVE_EIGHTHS
Fraction representation of 5/8.


SEVEN_EIGHTHS

public static final Fraction SEVEN_EIGHTHS
Fraction representation of 7/8.

Method Detail

getFraction

public static Fraction getFraction(int numerator,
                                   int denominator)
Deprecated. For reasons of backwards-compatibility, this method does not simplify fractions. The Fraction objects returned are thus subject to overflow. It should not be used in new code. Use valueOf() instead.

Creates a Fraction instance with the 2 parts of a fraction Y/Z.

Any negative signs are resolved to be on the numerator. Creates UNREDUCED fractions for backwards-compatibility.

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 is zero

valueOf

public static Fraction valueOf(int numerator,
                               int denominator)

Creates a Fraction instance with the 2 parts of a fraction Y/Z.

Any negative signs are resolved to be on the numerator, zeros are normalized to (0/1), and all fractions are simplified.

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 is zero

valueOf

public static Fraction valueOf(int value)

Creates a Fraction instance from a int value.

Parameters:
value - the integer value to convert
Returns:
a new fraction instance that is equal to the value

getFraction

public static Fraction getFraction(int whole,
                                   int numerator,
                                   int denominator)
Deprecated. For reasons of backwards-compatibility, this method does not simplify fractions. The Fraction objects returned are thus subject to overflow. It should not be used in new code. Use valueOf() instead.

Creates a Fraction instance with the 3 parts of a fraction X Y/Z. Creates UNREDUCED fractions for backwards-compatibility.

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 is zero
ArithmeticException - if the denominator is negative
ArithmeticException - if the numerator is negative
ArithmeticException - if the resulting numerator exceeds Integer.MAX_VALUE

valueOf

public static Fraction valueOf(int whole,
                               int numerator,
                               int denominator)

Creates a Fraction 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 is zero
ArithmeticException - if the denominator is negative
ArithmeticException - if the numerator is negative
ArithmeticException - if the resulting numerator exceeds Integer.MAX_VALUE

getReducedFraction

public static Fraction getReducedFraction(int numerator,
                                          int denominator)
Deprecated. All fractions are now stored as reduced fractions; use the valueOf() method instead.

Creates a Fraction 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, with the numerator and denominator reduced
Throws:
ArithmeticException - if the denominator is zero

getFraction

public static Fraction getFraction(double value)
Deprecated. Renamed this method to valueOf() for consistency.

Creates a Fraction instance from a double 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 or value = NaN
ArithmeticException - if the calculated denominator is zero
ArithmeticException - if the the algorithm does not converge

valueOf

public static Fraction valueOf(double value)

Creates a Fraction instance from a double 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 or value = NaN
ArithmeticException - if the calculated denominator is zero
ArithmeticException - if the the algorithm does not converge

valueOf

public static Fraction valueOf(String str)

Creates a Fraction from a String.

The formats accepted are:

  1. double String containing a dot
  2. 'X Y/Z'
  3. 'Y/Z'
  4. 'X' (a simple whole number)

Parameters:
str - the string to parse, must not be null
Returns:
the new Fraction instance
Throws:
IllegalArgumentException - if the string is null
NumberFormatException - if the number format is invalid

getFraction

public static Fraction getFraction(String str)
Deprecated. For reasons of backwards-compatibility, this method does not simplify fractions. The Fraction objects returned are thus subject to overflow. It should not be used in new code. Use valueOf() instead.

Creates a Fraction from a String. Creates UNREDUCED fractions for backwards-compatibility.

The formats accepted are:

  1. double String containing a dot
  2. 'X Y/Z'
  3. 'Y/Z'
  4. 'X' (a simple whole number)

Parameters:
str - the string to parse, must not be null
Returns:
the new Fraction instance
Throws:
IllegalArgumentException - if the string is null
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.

The numerator and denominator will always be relatively prime unless deprecated methods are used.

Returns:
the numerator fraction part

getDenominator

public int getDenominator()

Gets the denominator part of the fraction.

The numerator and denominator will always be relatively prime unless deprecated methods are used. The denominator will always be greater than zero.

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.

The proper numerator will always be relatively prime to the denominator, unless deprecated methods are used.

Returns:
the numerator fraction part of a proper fraction, always positive

getProperWhole

@Deprecated
public int getProperWhole()
Deprecated. Returns unexpected values for numbers between -1 and 0

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

floor

public int floor()
Return the largest integer less than or equal to this fraction.


quantize

public Fraction quantize(int nDenom)
Quantize the given fraction to the nearest x/nDenom.


intValue

public int intValue()

Gets the fraction as an int. This returns the whole number part of the fraction.

Specified by:
intValue in class 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:
longValue in class 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:
floatValue in class 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:
doubleValue in class Number
Returns:
the fraction as a double

reduce

public Fraction reduce()
Deprecated. Unless you are using deprecated methods this operation is a no-op.

Reduce the fraction to the smallest values for the numerator and denominator, returning the result.

Returns:
a new reduce fraction instance, or this if no simplification possible

invert

public Fraction invert()

Gets a fraction that is the inverse (1/fraction) of this one.

Returns:
a new fraction instance with the numerator and denominator inverted.
Throws:
ArithmeticException - if the fraction represents zero.

negate

public Fraction negate()

Gets a fraction that is the negative (-fraction) of this one.

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)

Returns:
this if 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.

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 exceeds Integer.MAX_VALUE

add

public Fraction add(Fraction fraction)

Adds the value of this fraction to another. The algorithm follows Knuth, 4.5.1.

Parameters:
fraction - the fraction to add, must not be null
Returns:
a Fraction instance with the resulting values
Throws:
IllegalArgumentException - if the fraction is null
ArithmeticException - if the resulting numerator or denominator exceeds Integer.MAX_VALUE

subtract

public Fraction subtract(Fraction fraction)

Subtracts the value of another fraction from the value of this one.

Parameters:
fraction - the fraction to subtract, must not be null
Returns:
a Fraction instance with the resulting values
Throws:
IllegalArgumentException - if the fraction is null
ArithmeticException - if the resulting numerator or denominator cannot be represented in an int.

multiplyBy

public Fraction multiplyBy(Fraction fraction)
Deprecated. Renamed to multiply()

Multiplies the value of this fraction by another.

Parameters:
fraction - the fraction to multiply by, must not be null
Returns:
a Fraction instance with the resulting values
Throws:
IllegalArgumentException - if the fraction is null
ArithmeticException - if the resulting numerator or denominator exceeds Integer.MAX_VALUE

multiply

public Fraction multiply(Fraction fraction)

Multiplies the value of this fraction by another.

Parameters:
fraction - the fraction to multiply by, must not be null
Returns:
a Fraction instance with the resulting values
Throws:
IllegalArgumentException - if the fraction is null
ArithmeticException - if the resulting numerator or denominator exceeds Integer.MAX_VALUE

divideBy

public Fraction divideBy(Fraction fraction)
Deprecated. Renamed to divide()

Divide the value of this fraction by another.

Parameters:
fraction - the fraction to divide by, must not be null
Returns:
a Fraction instance with the resulting values
Throws:
IllegalArgumentException - if the fraction is null
ArithmeticException - if the fraction to divide by is zero
ArithmeticException - if the resulting numerator or denominator exceeds Integer.MAX_VALUE

divide

public Fraction divide(Fraction fraction)

Divide the value of this fraction by another.

Parameters:
fraction - the fraction to divide by, must not be null
Returns:
a Fraction instance with the resulting values
Throws:
IllegalArgumentException - if the fraction is null
ArithmeticException - if the fraction to divide by is zero
ArithmeticException - if the resulting numerator or denominator exceeds Integer.MAX_VALUE

equals

public boolean equals(Object obj)

Compares this fraction to another object to test if they are equal.

.

Note that 2/4 is equal to 1/2 (unless you are using deprecated methods).

Overrides:
equals in class Object
Parameters:
obj - the reference object with which to compare
Returns:
true if this object is equal

hashCode

public int hashCode()

Gets a hashCode for the fraction.

Overrides:
hashCode in class Object
Returns:
a hash code value for this object

compareTo

public int compareTo(Fraction other)

Compares this object to another based on size.

Specified by:
compareTo in interface Comparable<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 a Fraction
NullPointerException - if the object is null

toString

public String toString()

Gets the fraction as a String.

The format used is 'numerator/denominator' always.

Overrides:
toString in class Object
Returns:
a String form of the fraction

toProperString

public String toProperString()

Gets the fraction as a proper String in the format X Y/Z.

The format used in 'wholeNumber numerator/denominator'. If the whole number is zero it will be ommitted. If the numerator is zero, only the whole number is returned.

Returns:
a String form of the fraction

repr

public String repr()
Returns an executable representation of this Fraction.


sdr 0.7

Copyright © 2006-2009 C. Scott Ananian