com.rubecula.jquantity
Class Rational

java.lang.Object
  extended bycom.rubecula.util.Item
      extended bycom.rubecula.jquantity.BaseNumber
          extended bycom.rubecula.jquantity.MutableNumber
              extended bycom.rubecula.jquantity.DivisibleMutable
                  extended bycom.rubecula.jquantity.Rational
All Implemented Interfaces:
Arithmetical, Arithmutable, Auditable, java.lang.Cloneable, java.lang.Comparable, Divisible, Estimable, Fuzzy, FuzzyMutable, Identifiable, Millable, Mutable, Nameable, Normalizable, Presentable, java.io.Serializable, Trigonometrical
Direct Known Subclasses:
Value

public class Rational
extends DivisibleMutable
implements Estimable, FuzzyMutable, Trigonometrical, Normalizable

Public class to represent precise rational numbers. What's wrong with BigDecimal, you might ask? BigDecimal can only represent rational numbers where the denominator is a power of ten. Many numbers are just not like that.
Furthermore, both numerator and denominator can be either exact integers (i.e. Manifests or WholeNumbers) or fuzzy integers (i.e. FuzzInt) so that Rational can itself represent a complete range of potentially fuzzy numbers. Infinity is a legal Rational number.

Version:
$Revision: 1.62 $ // TODO Needs more conformance checking. // TODO There are really too many constructors for this class. // TODO The javadoc for other interface methods should be done like for Arithmutable.
Author:
Robin Hillyard
See Also:
Serialized Form

Nested Class Summary
private  class Rational.RationalException
           
 class Rational.RValueException
          Title: RValueException Description: Checked exception class for Rational.
 
Field Summary
protected  BaseNumber _Denominator
          _Denominator is the denominator of the rational quantity defined by this.
protected  double _Estimate
          _Estimate is the best estimate of the value (STRICTLY for debugging purposes only).
protected  BaseNumber _Numerator
          _Numerator is the numerator of the rational quantity defined by this.
(package private) static Rational $_c
          By definition, the velocity of light (in meter/second).
(package private) static Rational $_degF
          Degrees Fahrenheit/Celsius offset: 32.
static Rational $_degR
          Degrees Rankine/Kelvin conversion: 5/9.
(package private) static Rational $_g
          By definition, the standard (mean) gravity at the Earth's surface: 9.80665.
static Rational $_Log10_E
           
(package private) static Rational $_Pi_2
           
(package private) static Rational $_Pi_4
           
(package private) static Rational $_Tan15Deg
          2 - $Rt3.
(package private) static Rational $_Tan22_5Deg
          1 / (1 + Rt2).
(package private) static Rational $_Tan30Deg
          1/$Rt3.
static Rational $0
          $0 is the Rational representation of the exact value 0.
static Rational $1
          $1 is the Rational representation of the exact value 1.
static Rational $1_2
          $1_2 is the Rational representation of the exact value 1/2.
static Rational $10
          $10 is the Rational representation of the exact value 10.
(package private) static Rational $12
           
static Rational $2
          $2 is the Rational representation of the exact value 2.
static Rational $3
           
(package private) static Rational $6
           
static Rational $E
          Value of E as a Rational.
static Rational $Infinity
          $Infinity is the Rational representation of the (exact) value of infinity, i.e. 1/0.
(package private) static Rational $NaN
           
static Rational $Pi
          Value of Pi as a Rational.
(package private) static Rational $Rt2
          InitialValueOf($S_Rt2).
(package private) static Rational $Rt3
          InitialValueOf($S_Rt3).
(package private) static Rational $Rt5
          InitialValueOf($S_Rt5).
(package private) static java.lang.String $S_Rt2
          1.414213562373095048801688724209698078569671875377
(package private) static java.lang.String $S_Rt3
          1.732050807568877293527446341505872366942805253810
(package private) static java.lang.String $S_Rt5
          2.2360679774997896964091736687312762354406183596
private static int MAX_RATIO_BITS
           
private static double PRESENTATION_TOLERANCE
           
 
Fields inherited from class com.rubecula.jquantity.MutableNumber
$__1
 
Fields inherited from class com.rubecula.jquantity.BaseNumber
 
Fields inherited from class com.rubecula.util.Item
JQUANTITY_TEST
 
Fields inherited from interface com.rubecula.jquantity.Fuzzy
$DistGaussian, $DistInvalid, $DistNone, $DistUniform, $Names
 
Constructor Summary
  Rational()
          Empty constructor to make an undefined Rational object.
(package private) Rational(java.math.BigDecimal x)
           
protected Rational(java.math.BigDecimal x, java.lang.String identifier)
          Factory method to create a Rational from a BigDecimal value and an identifier.
  Rational(Integral value)
          Constructs a non-explicitly identified Rational representing the ratio of value divided by unity.
  Rational(Integral numerator, Integral denominator)
          Constructs a non-explicitly identified, normalized Rational representing the ratio of numerator divided by denominator.
protected Rational(Integral numerator, Integral denominator, boolean normalize)
          Constructs a non-explicitly identified Rational representing the ratio of numerator divided by denominator, with optional normalization.
protected Rational(Integral numerator, Integral denominator, boolean normalize, java.lang.String identifier)
          Constructs an identified Rational representing the ratio of numerator divided by denominator, with optional normalization.
  Rational(Integral numerator, Integral denominator, java.lang.String identifier)
          Constructs an identified Rational representing the ratio of numerator divided by denominator.
  Rational(Integral numerator, java.lang.String identifier)
          Constructs an identified Rational representing the ratio of numerator divided by denominator, with optional normalization.
  Rational(long numerator, long denominator)
          Convenience constructor for two longs.
protected Rational(Rational source)
          Constructor to make a copy of a Rational object.
  Rational(java.lang.String string)
          Secondary constructor to create a Rational from a String.
 
Method Summary
 Rational absRational()
          Method to yield the absolute (unsigned) value of this as a Rational.
 void add(BaseNumber that)
          MUTATING Instance method to add another Arithmetical into this object.
protected  void addAbsError(double absBound, int model)
          This method is used to add in an intrinsic error bound.
protected  void addTops(Rational other)
           
 Trigonometrical arctanX2()
          Method to evaluate the arctangent function.
 java.lang.String audit(java.lang.String label)
          Method to return a detailed string from an arithmetical object for debugging purposes.
private static Rational BigDecimalRational(java.math.BigInteger top, java.math.BigInteger bottom, double tolerance, int characteristic, java.lang.String id)
          Class method to yield an explicitly identified Rational which approximates top/bottom to within tolerance (to exponent characteristic).
private static java.math.BigInteger BigTenToPower(int x)
          Class method to yield a BigInteger whose value is 10 to the power of x.
 java.lang.Object clone()
          Creates and returns a deep copy of this object.
 int compareTo(Integral val)
          Compares this Rational with the specified Integral.
 int compareTo(Rational val)
          Compares this Rational with the specified Rational.
protected  int compareTo(Rational val, boolean absolute)
          Compares this Rational with the specified Rational.
 java.lang.String defaultIdentifier()
          Method to yield a default string to identify this object in the event that it has no explicitly defined identifier.
(package private)  Rational differenceRational(Rational subtrahend)
          Method to yield the difference of this less a BaseNumber (subtrahend).
 void divide(BaseNumber that)
          MUTATING method to replace this by the sum of this and that
private  java.math.BigInteger[] divideNumeratorAndRemainder(Integral divisor)
           
 double doubleValue()
          Returns the value of the specified number as a double.
private  void ensureDenominatorArithmutable()
          MUTATING method to ensure that the numerator is an Arithmutable object.
private  void ensureDenominatorFuzzy()
           
private  void ensureNumeratorArithmutable()
          MUTATING method to ensure that the numerator is an Arithmutable object.
private  void ensureNumeratorFuzzy()
           
 Trigonometrical exp()
          Method to evaluate the exponential function.
protected  void factor(Integral divisor)
          MUTATING METHOD: Replaces value with (this / divisor).
 Divisible factored(double factor)
          Method to yield the quotient of this divided by factor, and return it as the result.
 float floatValue()
          Returns the value of the specified number as a float.
(package private)  Rational fold(Rational range)
          Method to force this into a specific range.
private  void forceFuzzy()
          MUTATING method to ensure that this Rational is (potentially) fuzzy, that is to say its Numerator must be FuzzyMutable.
private  java.math.BigInteger gcd(boolean strict)
           
private static java.math.BigInteger GetBigInteger(Integral x, boolean strict)
           
 long getBottom()
          Method to yield the denominator as a long.
 double getBound()
          Method to get the relative bound of this Rational.
private static double GetBound(double x, boolean exact)
          Get the bounds for a number in double format which is either exact or accurate only to the number of decimal places given.
 double getBoundAbs()
          Method to get the absolute bound of non-fuzzy value.
protected  BaseNumber getDenominator()
          Method to access the denominator of this Rational object.
protected  Integral getDenominatorAsIntegral()
          Method to access the denominator of this Rational object.
 double getEstimate()
          Method to get the current estimate of an arithmetical value.
 int getModel()
          Method to get the error distribution model of this non-fuzzy object.
protected  BaseNumber getNumerator()
          Method to access the numerator of this Rational object.
protected  Integral getNumeratorAsIntegral()
          Method to access the numerator of this Rational object.
 long getTop()
          Method to yield the numerator as a long.
 Rational half()
          Method to yield half the value of this.
 int hashCode()
          Method to determine a hash code for this object. // TODO Surely this isn't a good hash code for Rational objects.
static Rational InitialValueOf(java.lang.String string)
          Create a constant value of a Rational from a string.
private static Rational InitParse(Presentation presentation, java.lang.String id)
           
private static java.math.BigInteger IntVal(java.math.BigDecimal x)
           
 int intValue()
          Method to yield the equivalent integer value for this object.
 Divisible inverse()
          Method to yield the reciprocal of this and return it as the result.
 Rational inverseRational()
           
 void invert()
          MUTATING Instance method to invert this (i.e. replace this by its reciprocal)
 boolean isExact()
          Method to determine if the quantity represented is non-fuzzy;
 boolean isInfinite()
          Method to determine if an arithmetical object is infinite.
 boolean isInteger()
          Method determines if it is safe and appropriate to convert this arithmetical object into BigInteger.
(package private)  boolean isIntFuzzy()
          This method is used to determine if the numerical value of this is convertible to a int, without regard to the precision.
(package private)  boolean isNaN()
          Method to determine if this Rational is "not a number".
 boolean isNormal()
          Method to determine if this instance is already normalized.
 boolean isUnity()
          Method to determine if this arithmetical object has the exact value of 1.
 Trigonometrical log()
          Method to evaluate the natural log function.
 long longValue()
          Method to yield the equivalent integer value for this object.
(package private)  long longValue(double tolerance)
          Method to yield the long value of this object.
(package private)  double magnitude()
          Method to yield the magnitude of this Rational as a double.
static void main(java.lang.String[] args)
          Main method for testing this class.
 Presentable makePresentableInstance(Presentation presentation)
          Instance method to convert a Presentation into a Presentable.
protected  BaseNumber minus()
          Method to yield a copy of this but with the sign changed.
 Rational minusRational()
          Method to yield a copy of this but with the sign changed.
(package private)  Rational modulo(long x)
          Method to return the value of this modulo x
 void multiply(BaseNumber that)
          MUTATING Instance method to multiply another Arithmetical into this object.
protected  void multiplyTopAndBottom(BaseNumber factor)
          MUTATING method to multiply the top and bottom of a rational equally.
 void negate()
          MUTATING Instance method to negate this.
 void normalize()
          MUTATING instance method to remove any common factors from top and bottom.
(package private)  Rational normalizeToBigDecimal(double tolerance)
          Normalize this such that the denominator is a power of ten AND the value of the result differs from the value of this by not more than the tolerance.
(package private)  Rational normalizeToInt(double tolerance)
          Normalize this Rational so that the result: a) has a denominator unity and b) approximates this in value, to within tolerance.
static Rational Parse(NumberPresentation presentation, java.lang.String identifier)
          Translates the NumberPresentation representation into a new Rational.
static Presentable Parse(Presentation presentation)
          Create a Rational from a Presentation and return it as a Presentable.
protected  BaseNumber pow(double power)
          Method to yield this raised to a double-precision power.
protected  BaseNumber pow(int power)
          Method to raise this to the power power return the result.
 Rational pow(Rational power)
           
 Presentation present(AttrMap attributes)
          Convert this Presentable object into a Presentation, according to the set of attributes provided.
private  Presentation present(AttrMap attributes, double tolerance)
          Method to convert this Rational into an equivalent Presentation.
private  Presentation present(AttrMap attributes, double tolerance, boolean notRatio)
          Method to convert this Rational into an equivalent Presentation.
private  Presentation present(double tolerance)
          Method to convert this Rational into an equivalent Presentation.
private  Presentation presentRatio()
          Method to convert this Rational into the appropriate NumberPresentation as a ratio rather than as a decimal.
 Rational productRational(Rational multiplicand)
          Method to multiply multiplicand to this and return their product as the result.
 Divisible quotient(BaseNumber divisor)
          Method to divide this by multiplicand and return the quotient as the result.
(package private)  Rational quotientRational(Rational that)
           
 void raiseToPower(int power)
          MUTATING Instance method to raise this to power x.
(package private)  Rational root(int p)
          method root: to yield an exact (integer) Rational for the root of a positive integral Rational.
private static BaseNumber SafeReference(BaseNumber x)
          This method yields a reference to a BaseNumber (the numerator or denominator) for the purpose of cloning/copying a Rational object safely.
 void scale(double factor)
          MUTATING Instance method to multiply this by a (double) scale factor
 void scale(long factor)
          MUTATING Instance method to multiply this by a scale factor.
protected  BaseNumber scaled(long multiplicand)
          Method to multiply multiplicand by this and return their product as the result.
 void setBound(double bound)
          MUTATING Method to set the relative bound of fuzzy value.
protected  void setBoundAbs(double bound)
          MUTATING Method to set the absolute bound of fuzzy value. // TODO Move this down with the protected methods (not defined by FuzzyMutable).
private  void setDenominator(BaseNumber denominator)
          MUTATING method to set the value of the denominator.
private  void setDenominator(Integral denominator)
          MUTATING method to set the value of the denominator.
private  void setExact()
           
 void setModel(int model)
          MUTATING Method to set the error distribution model.
private  void setNumerator(BaseNumber numerator)
          MUTATING method to set the value of the numerator.
private  void setNumerator(Integral numerator)
          MUTATING method to set the value of the numerator.
 int signum()
          Method to find the sign of the magnitude of this arithmetical object.
(package private)  Rational squareRational()
          Method to return the Rational formed my multiplying this by itself.
 void subtract(Rational that)
          MUTATING method to replace this by the difference of this and that
 Rational sumRational(Rational addend)
          Method to add addend to this and return their sum as the result.
 Trigonometrical tan_theta_2()
          Method to evaluate the tangent function.
(package private)  void timesTenToPower(int power)
          Package-protected MUTATING method to multiply this by a power of ten.
(package private)  Approximation toApproximation(double tolerance)
          Method to convert this Rational into the appropriate Approximation.
private  java.math.BigDecimal toBigDecimal()
          Method to yield a BigDecimal instance which approximates this.
private  java.math.BigDecimal toBigDecimal(double tolerance)
          Method to yield a BigDecimal instance which approximates this.
private  java.math.BigDecimal toBigDecimal(int halfPlaces)
          Method to yield a BigDecimal instance which approximates this.
 Integral toIntegral()
          Method to present a Rational as an Integral number.
 java.lang.String toString()
          Method to yield a string representing this Rational exactly.
(package private)  java.lang.String toString(double tolerance)
          Method to determine a suitable string to represent this Rational, such that the resulting string is precise within tolerance.
 void updateEstimate()
          MUTATING method to update the current estimate.
static Rational valueOf(BaseNumber number)
          Factory method to create a Rational from a BaseNumber or, if number is Rational, then to make a copy.
(package private) static Rational valueOf(java.math.BigInteger integer, java.math.BigInteger fraction, int places)
          Factory method to create a (decimal) Rational from two (big) integers.
static Rational valueOf(double value)
          Factory method to create a Rational from an exact double value.
static Rational valueOf(double value, boolean exact)
          Factory method to create a Rational from a double value, that may or not be "exact".
static Rational valueOf(double value, double bound, int model)
          Factory method to create a Rational from a double value, given an indication of precision.
static Rational valueOf(double value, double bound, int model, java.lang.String identifier)
          Factory method to create a Rational from a double value, given an indication of precision.
static Rational valueOf(double value, int precision, java.lang.String identifier)
          Factory method to create a Rational from a double value, given an indication of precision.
static Rational valueOf(double value, java.lang.String identifier)
          Factory method to create a Rational from a double value, using standard double precision and with an explicit identifier.
static Rational valueOf(float value)
          Factory method to create a Rational from a float value, given an explicit identifier.
static Rational valueOf(float value, java.lang.String identifier)
          Factory method to create a Rational from a float value without an explicit identifier.
static Rational valueOf(Presentation presentation)
          Convert Presentation presentation into a Rational.
static BaseNumber valueOf(java.lang.String string)
          Convenience factory method to create a new Rational instance from a value string and an implicit identifier (the value string itself).
static BaseNumber valueOf(java.lang.String string, java.lang.String id)
          Convenience factory method to create a new Rational instance from a value string and an explicit identifier.
(package private) static Rational valueOfExponent(int exponent)
          Factory method to create a Rational which is equal to 10^exponent.
(package private) static Rational valueOfExponent(int exponent, int radix)
          Factory method to create a Rational which is equal to radix^exponent.
(package private) static Rational valueOfExponent(java.lang.String exponentStr, int radix)
          Factory method to create a Rational which is equal to the multiplier represented by an exponent string.
private static BaseNumber WidenIntegral(BaseNumber number)
          Method to convert an Integral object into an Arithmutable object if necessary.
 
Methods inherited from class com.rubecula.jquantity.MutableNumber
assertMutable, factored, forcePositive, getIdentifier, getIdentifier, isLong, isMutable, product, setConstant, setIdentifier, setIdentifierPost, setIdentifierPre, setIdentifierPrePost, sum, test
 
Methods inherited from class com.rubecula.jquantity.BaseNumber
abs, bestModel, BestModel, byteValue, characteristic, Characteristic, difference, impartFuzziness, isEqual, isUncertain, isZero, shortValue, valueOfLog10
 
Methods inherited from class com.rubecula.util.Item
audit, audit, compareTo, Debug, getClassNameShort, getType, IsDebug, present, SetDebug, test, test, Wrap
 
Methods inherited from class java.lang.Object
equals, finalize, getClass, notify, notifyAll, wait, wait, wait
 
Methods inherited from interface com.rubecula.jquantity.Mutable
isMutable, setConstant
 
Methods inherited from interface com.rubecula.util.Auditable
audit, audit
 

Field Detail

$1

public static final Rational $1
$1 is the Rational representation of the exact value 1.


$0

public static final Rational $0
$0 is the Rational representation of the exact value 0.


$10

public static final Rational $10
$10 is the Rational representation of the exact value 10.


$2

public static final Rational $2
$2 is the Rational representation of the exact value 2.


$1_2

public static final Rational $1_2
$1_2 is the Rational representation of the exact value 1/2.


$Infinity

public static final Rational $Infinity
$Infinity is the Rational representation of the (exact) value of infinity, i.e. 1/0.


$E

public static final Rational $E
Value of E as a Rational. Note that if you want an exact value, then use Value.$E


$Pi

public static final Rational $Pi
Value of Pi as a Rational. Note that if you want an exact value, then use Value.PI


_Numerator

protected BaseNumber _Numerator
_Numerator is the numerator of the rational quantity defined by this. In practice, the numerator is always an Integral number, by virtue of the available constructors and mutators.


_Denominator

protected BaseNumber _Denominator
_Denominator is the denominator of the rational quantity defined by this. In practice, the denominator is always an Integral number, by virtue of the available constructors and mutators.


_Estimate

protected double _Estimate
_Estimate is the best estimate of the value (STRICTLY for debugging purposes only).


$3

public static final Rational $3

$6

static final Rational $6

$12

static final Rational $12

$NaN

static final Rational $NaN

$_Pi_2

static final Rational $_Pi_2

$_Pi_4

static final Rational $_Pi_4

$_Log10_E

public static final Rational $_Log10_E

$S_Rt2

static final java.lang.String $S_Rt2
1.414213562373095048801688724209698078569671875377

See Also:
Constant Field Values

$S_Rt3

static final java.lang.String $S_Rt3
1.732050807568877293527446341505872366942805253810

See Also:
Constant Field Values

$S_Rt5

static final java.lang.String $S_Rt5
2.2360679774997896964091736687312762354406183596

See Also:
Constant Field Values

$Rt2

static final Rational $Rt2
InitialValueOf($S_Rt2).


$Rt3

static final Rational $Rt3
InitialValueOf($S_Rt3).


$Rt5

static final Rational $Rt5
InitialValueOf($S_Rt5).


$_Tan15Deg

static final Rational $_Tan15Deg
2 - $Rt3.


$_Tan22_5Deg

static final Rational $_Tan22_5Deg
1 / (1 + Rt2).


$_Tan30Deg

static final Rational $_Tan30Deg
1/$Rt3.


$_c

static final Rational $_c
By definition, the velocity of light (in meter/second). Value: Manifest.$_c This value is exact. See c,c0.


$_g

static final Rational $_g
By definition, the standard (mean) gravity at the Earth's surface: 9.80665.


$_degR

public static final Rational $_degR
Degrees Rankine/Kelvin conversion: 5/9.


$_degF

static final Rational $_degF
Degrees Fahrenheit/Celsius offset: 32.


MAX_RATIO_BITS

private static final int MAX_RATIO_BITS
See Also:
Constant Field Values

PRESENTATION_TOLERANCE

private static final double PRESENTATION_TOLERANCE
See Also:
Constant Field Values
Constructor Detail

Rational

public Rational()
Empty constructor to make an undefined Rational object. The purpose of this is for an instance to be created on which to call the class method Parse(Presentation).


Rational

public Rational(java.lang.String string)
         throws PresentationException
Secondary constructor to create a Rational from a String.

Parameters:
string - the String from which to create a Rationa.
Throws:
PresentationException - if the string cannot be parsed as a Rational object.

Rational

public Rational(Integral numerator,
                Integral denominator,
                java.lang.String identifier)
Constructs an identified Rational representing the ratio of numerator divided by denominator.

Parameters:
numerator - the numerator (top) of the ratio.
denominator - the denominator (bottom) of the ratio.
identifier - the identifier to be used to identify this object.

Rational

public Rational(Integral numerator,
                Integral denominator)
Constructs a non-explicitly identified, normalized Rational representing the ratio of numerator divided by denominator.

Parameters:
numerator - Integral which is the numerator (top) of the ratio
denominator - Integral which is the denominator (bottom) of the ratio

Rational

public Rational(Integral numerator,
                java.lang.String identifier)
Constructs an identified Rational representing the ratio of numerator divided by denominator, with optional normalization.

Parameters:
numerator - the numerator (top) of the ratio
identifier - the identifier to be used to identify this object.

Rational

public Rational(Integral value)
Constructs a non-explicitly identified Rational representing the ratio of value divided by unity.

Parameters:
value - the numerator (top) of the ratio.

Rational

public Rational(long numerator,
                long denominator)
Convenience constructor for two longs.

Parameters:
numerator - the top of the ratio
denominator - the bottom of the ratio

Rational

protected Rational(java.math.BigDecimal x,
                   java.lang.String identifier)
Factory method to create a Rational from a BigDecimal value and an identifier. Constructs a new instance of Rational with same value as x and with bounds determined from the scale of x and uniform error distribution.

Parameters:
x - a BigDecimal number which is to be widened into a Rationa.
identifier - the identifier for the new instance.

Rational

protected Rational(Integral numerator,
                   Integral denominator,
                   boolean normalize,
                   java.lang.String identifier)
Constructs an identified Rational representing the ratio of numerator divided by denominator, with optional normalization. This is protected because non-extenders should not be able to determine if the number be normalized.

Parameters:
numerator - the numerator (top) of the ratio, which must be an instance of either Manifest or WholeNumber.
denominator - the denominator (bottom) of the ratio, which must be an instance of either Manifest or WholeNumber.
normalize - normally true (only set to false if you really know what you're doing).
identifier - the identifier to be used to identify this object (or null).
Throws:
Rational.RationalException - if either numerator or denominator is not an instance of either Manifest or WholeNumber.

Rational

protected Rational(Integral numerator,
                   Integral denominator,
                   boolean normalize)
Constructs a non-explicitly identified Rational representing the ratio of numerator divided by denominator, with optional normalization.

Parameters:
numerator - the numerator (top) of the ratio.
denominator - the denominator (bottom) of the ratio.
normalize - normally true (only set to false if you really know what you're doing)

Rational

Rational(java.math.BigDecimal x)

Rational

protected Rational(Rational source)
Constructor to make a copy of a Rational object.
This is an alternative to the clone() method and private to the class and its subclasses. This method behaves similarly to clone with regard to the referenced objects.

Parameters:
source - the object to copy. // TODO is their any real reason for having this constructor? // TODO should this simply call clone()? Surely that would be more consistent?
Method Detail

Parse

public static Rational Parse(NumberPresentation presentation,
                             java.lang.String identifier)
                      throws PresentationException
Translates the NumberPresentation representation into a new Rational. The result is not a constant.

Parameters:
presentation - NumberPresentation.
identifier - A string with which to identify this Rational.
Returns:
a new mutable instance of Rational, widened from the presentation.
Throws:
PresentationException - if the presentation cannot be parsed as a Rational object.

valueOf

public static Rational valueOf(BaseNumber number)
Factory method to create a Rational from a BaseNumber or, if number is Rational, then to make a copy. The result is marked as a constant.

Parameters:
number - the value to be widened into a Rational.
Returns:
a new immutable instance of Rational, widened from number.

valueOf

public static BaseNumber valueOf(java.lang.String string,
                                 java.lang.String id)
                          throws PresentationException
Convenience factory method to create a new Rational instance from a value string and an explicit identifier.

Parameters:
string - a representation of a NumberPresentation.
id - Identifier for new Rational.
Returns:
a new mutable instance of Rational.
Throws:
PresentationException - if the string cannot be parsed as a Rational object.
See Also:
NumberPresentation.NumberPresentation(String), Parse(NumberPresentation, String)

valueOf

public static BaseNumber valueOf(java.lang.String string)
                          throws PresentationException
Convenience factory method to create a new Rational instance from a value string and an implicit identifier (the value string itself).

Parameters:
string - a representation of a NumberPresentation.
Returns:
a new mutable instance of Rational.
Throws:
PresentationException - if the string cannot be parsed as a Rational object.
See Also:
valueOf(String,String)

makePresentableInstance

public Presentable makePresentableInstance(Presentation presentation)
                                    throws PresentationException
Instance method to convert a Presentation into a Presentable. Ideally, this would be a class method, but such a method cannot be defined in an interface. Nor can it be defined in an abstract class with the intention of overriding it in a subclass. Polymorphism just doesn't work that way.
Therefore, the present value (as in fields) of the instance is essentially ignored - only the methods are important.

Specified by:
makePresentableInstance in interface Presentable
Parameters:
presentation - of a number to be converted into a Presentable number.
Returns:
a number in the form of a Presentable.
Throws:
PresentationException - if presentation cannot be parsed appropriately.

Parse

public static Presentable Parse(Presentation presentation)
                         throws PresentationException
Create a Rational from a Presentation and return it as a Presentable.

Parameters:
presentation - A presentation which should be parsed to form a Presentable.
Returns:
A Rational which corresponds to the presentation.
Throws:
PresentationException - if the presentation cannot be parsed as a Presentable object.

clone

public java.lang.Object clone()
Creates and returns a deep copy of this object.

Overrides:
clone in class MutableNumber
Returns:
a clone of this instance.
Throws:
Rational.RationalException - : Rational not Cloneable (should be impossible)
See Also:
Cloneable

getBoundAbs

public double getBoundAbs()
Method to get the absolute bound of non-fuzzy value.

Overrides:
getBoundAbs in class BaseNumber
Returns:
the absolute bound of this. // TODO if infinite then bound should be zero (infinity is an exact number).
See Also:
BaseNumber.getBound(), BaseNumber.doubleValue(), Math.abs(double)

getBound

public double getBound()
Method to get the relative bound of this Rational.

Specified by:
getBound in interface Fuzzy
Overrides:
getBound in class BaseNumber
Returns:
rel. bound of numerator less rel. bound of denominator.

getModel

public int getModel()
Method to get the error distribution model of this non-fuzzy object.

Specified by:
getModel in interface Fuzzy
Overrides:
getModel in class BaseNumber
Returns:
Fuzzy.$DistNone int: non-fuzzy distribution.

isExact

public boolean isExact()
Method to determine if the quantity represented is non-fuzzy;

Specified by:
isExact in interface Fuzzy
Overrides:
isExact in class BaseNumber
Returns:
true boolean: always

intValue

public int intValue()
Method to yield the equivalent integer value for this object. Objects which are infinite or non=integral throw exceptions.

Specified by:
intValue in class BaseNumber
Returns:
int : the integer value of this.

longValue

public long longValue()
Method to yield the equivalent integer value for this object. Objects which are infinite or non-integral throw exceptions.

Specified by:
longValue in class BaseNumber
Returns:
int : the integer value of this.

floatValue

public float floatValue()
Returns the value of the specified number as a float. This may involve rounding.

Specified by:
floatValue in class BaseNumber
Returns:
the numeric value represented by this object after conversion to type float.

doubleValue

public double doubleValue()
Returns the value of the specified number as a double. This may involve rounding.

Specified by:
doubleValue in class BaseNumber
Returns:
the numeric value represented by this object after conversion to type double.

signum

public int signum()
Method to find the sign of the magnitude of this arithmetical object.

Specified by:
signum in interface Arithmetical
Returns:
0 if value is 0; 1 if value is positive; -1 if value is negative.

isInteger

public boolean isInteger()
Method determines if it is safe and appropriate to convert this arithmetical object into BigInteger.

Specified by:
isInteger in interface Arithmetical
Returns:
true if isExact() and denominator is equal to 1.

isUnity

public boolean isUnity()
Method to determine if this arithmetical object has the exact value of 1.

Specified by:
isUnity in interface Arithmetical
Returns:
true if value is 1 and isExact().

isInfinite

public boolean isInfinite()
Method to determine if an arithmetical object is infinite.

Specified by:
isInfinite in interface Arithmetical
Returns:
true if object is infinite in value.

raiseToPower

public void raiseToPower(int power)
Description copied from interface: Arithmutable
MUTATING Instance method to raise this to power x.

Specified by:
raiseToPower in interface Arithmutable
Parameters:
power - the number of times this should be multiplied by itself.

scale

public void scale(long factor)
Description copied from interface: Arithmutable
MUTATING Instance method to multiply this by a scale factor. Note that under this operation, the scaling (multiplication) is always directly on the stored value in this regardless of values of other fields. Furthermore, only the stored value will change, no other field values, such as factoring schemes, etc.

Specified by:
scale in interface Arithmutable
Parameters:
factor - the scale factor.

negate

public void negate()
Description copied from interface: Arithmutable
MUTATING Instance method to negate this.

Specified by:
negate in interface Arithmutable

add

public void add(BaseNumber that)
Description copied from interface: Arithmutable
MUTATING Instance method to add another Arithmetical into this object.

Specified by:
add in interface Arithmutable
Parameters:
that - the number to add to this.

multiply

public void multiply(BaseNumber that)
              throws InvalidOperandException
Description copied from interface: Arithmutable
MUTATING Instance method to multiply another Arithmetical into this object.

Specified by:
multiply in interface Arithmutable
Parameters:
that - the number by which this is to be multiplied.
Throws:
InvalidOperandException - operands are not compatible for the multiply operation.

ensureDenominatorFuzzy

private void ensureDenominatorFuzzy()

ensureNumeratorFuzzy

private void ensureNumeratorFuzzy()

scale

public void scale(double factor)
MUTATING Instance method to multiply this by a (double) scale factor

Specified by:
scale in class DivisibleMutable
Parameters:
factor - double the scale factor

invert

public void invert()
MUTATING Instance method to invert this (i.e. replace this by its reciprocal)

Specified by:
invert in class DivisibleMutable

divide

public void divide(BaseNumber that)
            throws InvalidOperandException
MUTATING method to replace this by the sum of this and that

Specified by:
divide in class DivisibleMutable
Parameters:
that - the value to be divided into this
Throws:
InvalidOperandException - if that is not compatible with the multiply operation.

inverse

public Divisible inverse()
Method to yield the reciprocal of this and return it as the result.
NOTE: it is a requirement of this method that the class of the result is the same as the class of this so that the result can be safely cast to the original class.

Specified by:
inverse in interface Divisible
Returns:
the reciprocal of this.

quotient

public Divisible quotient(BaseNumber divisor)
                   throws InvalidOperandException
Method to divide this by multiplicand and return the quotient as the result.
NOTE: it is a requirement of this method that the class of the result is the same as the class of this so that the result can be safely cast to the original class.

Specified by:
quotient in interface Divisible
Parameters:
divisor - the number to multiply by this.
Returns:
the quotient of this divided by divisor.
Throws:
InvalidOperandException - if that is not compatible with the multiply operation.

factored

public Divisible factored(double factor)
Method to yield the quotient of this divided by factor, and return it as the result.
NOTE: it is a requirement of this method that the class of the result is the same as the class of this so that the result can be safely cast to the original class.

Specified by:
factored in interface Divisible
Parameters:
factor - the scale factor.
Returns:
the quotient of this divided by factor.

exp

public Trigonometrical exp()
Method to evaluate the exponential function. This method is the inverse of log().

Specified by:
exp in interface Trigonometrical
Returns:
e(this) in the form of a Rational. // TODO would be nice to combine the logic of this method and the Transcendtal class for Exp in Value.

log

public Trigonometrical log()
Method to evaluate the natural log function. This method is the inverse of exp().

Specified by:
log in interface Trigonometrical
Returns:
log(this) in the form of a Rational or an Approximation.

arctanX2

public Trigonometrical arctanX2()
Method to evaluate the arctangent function. This method is the inverse of tan_theta_2().

Specified by:
arctanX2 in interface Trigonometrical
Returns:
2 * atan(this) in the form of a Rational.

tan_theta_2

public Trigonometrical tan_theta_2()
Method to evaluate the tangent function. This method is the inverse of arctanX2().

Specified by:
tan_theta_2 in interface Trigonometrical
Returns:
tan(this/2) in the form of a Rational.

setBoundAbs

protected void setBoundAbs(double bound)
MUTATING Method to set the absolute bound of fuzzy value. // TODO Move this down with the protected methods (not defined by FuzzyMutable).

Parameters:
bound - the absolute bound

setBound

public void setBound(double bound)
MUTATING Method to set the relative bound of fuzzy value.

Specified by:
setBound in interface FuzzyMutable
Parameters:
bound - the relative bound

setModel

public void setModel(int model)
MUTATING Method to set the error distribution model.

Specified by:
setModel in interface FuzzyMutable
Parameters:
model - the distribution model: $DistNone, $DistUniform or $DistGaussian

updateEstimate

public void updateEstimate()
MUTATING method to update the current estimate.
Note that it is possible for the estimate to be NaN even though the value of the Rational is a well-formed number. This is because one or both of the numerator/denominator can be too large to be represented as a double. // TODO Ensure that estimate is always reasonable, for example if the estimate isNaN while this is not, then divide top/bottom by 10 until the estimate is good.

Specified by:
updateEstimate in interface Estimable

getEstimate

public double getEstimate()
Method to get the current estimate of an arithmetical value.

Specified by:
getEstimate in interface Estimable
Returns:
double: the current estimate.

toIntegral

public Integral toIntegral()
Method to present a Rational as an Integral number. If this is already of class Integral then just return this, else return the value of the superclass method.

Overrides:
toIntegral in class MutableNumber
Returns:
an instance of Integral with value equivalent to this.

minusRational

public final Rational minusRational()
Method to yield a copy of this but with the sign changed.

Returns:
negative version of this.

sumRational

public final Rational sumRational(Rational addend)
Method to add addend to this and return their sum as the result.

Parameters:
addend - the number to add to this.
Returns:
the sum of this and addend.

differenceRational

final Rational differenceRational(Rational subtrahend)
Method to yield the difference of this less a BaseNumber (subtrahend).

Parameters:
subtrahend - the number to subtract from this.
Returns:
the difference of this less subtrahend.

productRational

public final Rational productRational(Rational multiplicand)
Method to multiply multiplicand to this and return their product as the result.

Parameters:
multiplicand - the number to add to this.
Returns:
the product of this and multiplicand.

quotientRational

final Rational quotientRational(Rational that)

inverseRational

public final Rational inverseRational()

getDenominator

protected final BaseNumber getDenominator()
Method to access the denominator of this Rational object.

Returns:
the value of field _Denominator.

getNumerator

protected final BaseNumber getNumerator()
Method to access the numerator of this Rational object.

Returns:
the value of field _Numerator.

getDenominatorAsIntegral

protected final Integral getDenominatorAsIntegral()
Method to access the denominator of this Rational object.

Returns:
the value of field _Denominator cast as an Integral.

getNumeratorAsIntegral

protected final Integral getNumeratorAsIntegral()
Method to access the numerator of this Rational object.

Returns:
the value of field _Numerator cast as an Integral.

minus

protected BaseNumber minus()
Method to yield a copy of this but with the sign changed.
NOTE: it is a requirement of this method that the class of the result is the same as the class of this so that the result can be safely cast to the original class.

Specified by:
minus in class BaseNumber
Returns:
negative version of this.

scaled

protected BaseNumber scaled(long multiplicand)
Method to multiply multiplicand by this and return their product as the result.
NOTE: it is a requirement of this method that the class of the result is the same as the class of this so that the result can be safely cast to the original class.

Specified by:
scaled in class BaseNumber
Parameters:
multiplicand - the number to multiply this by.
Returns:
the product of this and multiplicand.

pow

protected BaseNumber pow(int power)
Method to raise this to the power power return the result.
NOTE: it is a requirement of this method that the class of the result is the same as the class of this so that the result can be safely cast to the original class.

Specified by:
pow in class BaseNumber
Parameters:
power - the exponent for this.
Returns:
the value of this rraised to the power power.

factor

protected void factor(Integral divisor)
MUTATING METHOD: Replaces value with (this / divisor).
This method allows for division by a non-Divisible divisor. Since a Rational object can represent all rational numbers, no exception will be thrown if the quotient cannot be expressed as a pure integer.

Specified by:
factor in class MutableNumber
Parameters:
divisor - value by which this WholeNumber is to be divided.
See Also:
MutableNumber.assertMutable(), _Denominator, getDenominator(), BaseNumber.product(BaseNumber), BaseNumber.scaled(long), updateEstimate()

valueOfExponent

static Rational valueOfExponent(int exponent,
                                int radix)
Factory method to create a Rational which is equal to radix^exponent.

Parameters:
exponent - the power to which radix is to be raised.
radix - the base of the number system.
Returns:
radix^exponent.

valueOfExponent

static Rational valueOfExponent(int exponent)
Factory method to create a Rational which is equal to 10^exponent.

Parameters:
exponent - the power to which radix is to be raised.
Returns:
10^exponent.

valueOfExponent

static Rational valueOfExponent(java.lang.String exponentStr,
                                int radix)
Factory method to create a Rational which is equal to the multiplier represented by an exponent string.

Parameters:
exponentStr - the power to which radix is to be raised, as a string.
radix - the base of the number system in which exponentStr is to be interpreted and also the number to be raised by the appropriate power.
Returns:
exponentStr as a multiplier.

valueOf

public static Rational valueOf(double value,
                               int precision,
                               java.lang.String identifier)
Factory method to create a Rational from a double value, given an indication of precision. The result of this factory method is NOT marked "constant".

Parameters:
value - double: the value to convert to Rational.
precision - int: the number of significant figures (approx.).
identifier - String: the identifier to be used to identify this object (or null).
Returns:
a mutable instance of Rational whose doubleValue() should be very close to value.

valueOf

public static Rational valueOf(double value,
                               double bound,
                               int model,
                               java.lang.String identifier)
Factory method to create a Rational from a double value, given an indication of precision. Note that the result will NOT be marked constant.

Parameters:
value - the value to convert to Rational.
bound - an explicit value for the relative error bound.
model - the error bound model to be used.
identifier - String: the identifier to be used to identify this object (or null).
Returns:
a mutable instance of Rational whose doubleValue() should be very close to value.
See Also:
valueOf(double,int,String)

valueOf

public static Rational valueOf(double value,
                               double bound,
                               int model)
Factory method to create a Rational from a double value, given an indication of precision. Note that the result will NOT be marked constant.

Parameters:
value - the value to convert to Rational.
bound - an explicit value for the relative error bound.
model - the error bound model to be used.
Returns:
a mutable instance of Rational whose doubleValue() should be very close to value.
See Also:
valueOf(double,double,int)

valueOf

public static Rational valueOf(double value,
                               java.lang.String identifier)
Factory method to create a Rational from a double value, using standard double precision and with an explicit identifier. Note that the result will NOT be marked constant.

Parameters:
value - the value to convert to Rational.
identifier - the explicit identifier for this value.
Returns:
a mutable instance of Rational whose doubleValue() should be very close to value.
See Also:
valueOf(double,double,int)

valueOf

public static Rational valueOf(double value,
                               boolean exact)
Factory method to create a Rational from a double value, that may or not be "exact". The result of this factory method is NOT marked "constant".

Parameters:
value - double: the value to convert to Rational.
exact - an indication of whether the result should be be considered exact.
Returns:
a mutable instance of Rational whose doubleValue() should be very close to value.
See Also:
valueOf(double,int,String)

valueOf

public static Rational valueOf(double value)
Factory method to create a Rational from an exact double value. The result will be marked constant.

Parameters:
value - the value as a double.
Returns:
a non-mutable Rational whose doubleValue() is close to value.
See Also:
valueOf(double,boolean)

valueOf

public static Rational valueOf(float value,
                               java.lang.String identifier)
Factory method to create a Rational from a float value without an explicit identifier. The result of this factory method is NOT marked "constant".

Parameters:
value - the value to convert to Rational.
identifier - String: the identifier to be used to identify this object (or null).
Returns:
a mutable instance of Rational whose floatValue() should be very close to value.
See Also:
valueOf(double,int,String)

valueOf

public static Rational valueOf(float value)
Factory method to create a Rational from a float value, given an explicit identifier. The result of this factory method is NOT marked "constant".

Parameters:
value - the value to convert to Rational.
Returns:
a mutable instance of Rational whose floatValue() should be very close to value.
See Also:
valueOf(float,String)

IntVal

private static java.math.BigInteger IntVal(java.math.BigDecimal x)

valueOf

static Rational valueOf(java.math.BigInteger integer,
                        java.math.BigInteger fraction,
                        int places)
Factory method to create a (decimal) Rational from two (big) integers. The result is NOT marked as a constant.

Parameters:
integer - BigInteger : the integer part.
fraction - BigInteger : the fractional part.
places - int : the number of decimal places for fractional part.
Returns:
a mutable Rational with value: integer + fraction/10**places.

multiplyTopAndBottom

protected void multiplyTopAndBottom(BaseNumber factor)
MUTATING method to multiply the top and bottom of a rational equally. Clearly this does not change the effective value of the Rational, but the individual numerator and denominator values do change.

Parameters:
factor - the number by which top and bottom will be multiplied.

addTops

protected void addTops(Rational other)

subtract

public void subtract(Rational that)
MUTATING method to replace this by the difference of this and that

Parameters:
that - Rational the value to be subtracted from this

absRational

public Rational absRational()
Method to yield the absolute (unsigned) value of this as a Rational.

Returns:
BaseNumber.abs()

defaultIdentifier

public java.lang.String defaultIdentifier()
Method to yield a default string to identify this object in the event that it has no explicitly defined identifier.

Overrides:
defaultIdentifier in class MutableNumber
Returns:
numerator / denominator (or just numerator if appropriate)

audit

public java.lang.String audit(java.lang.String label)
Method to return a detailed string from an arithmetical object for debugging purposes.

Specified by:
audit in interface Auditable
Parameters:
label - String: the label to associate with the data
Returns:
the detailed string.

half

public Rational half()
Method to yield half the value of this. Equivalent to factor(2)

Returns:
half of this.

modulo

Rational modulo(long x)
Method to return the value of this modulo x

Parameters:
x - the divisor for the modulo operation.
Returns:
a new Rational object with the remainder of numerator/x on the top and denominator on the bottom.

fold

Rational fold(Rational range)
Method to force this into a specific range. This can therefore be in radians, angles, right-angles, whatever.

Parameters:
range - defines the range (-limit < magnitude <= +limit).
Returns:
a copy of this, incremented appropriately so that magnitude is in range.

getTop

public long getTop()
Method to yield the numerator as a long. WARNING!! This function is to be used rarely and only when the value is expected to be in the "long" range. For example, when using some other form for rational numbers, such as in the Dimension class It is possible for narrowing to cause inaccuracies here!

Returns:
numerator as a long

getBottom

public final long getBottom()
Method to yield the denominator as a long. WARNING!! This function is to be used rarely and only when the value is expected to be in the "long" range. For example, when using some other form for rational numbers, such as in the Dimension class It is possible for narrowing to cause inaccuracies here!

Returns:
denominator as a long

hashCode

public int hashCode()
Method to determine a hash code for this object. // TODO Surely this isn't a good hash code for Rational objects.

Returns:
the hash code of the equivalent BigDecimal (tolerance 10^-10)

isNaN

boolean isNaN()
Method to determine if this Rational is "not a number".

Returns:
true if this has zero for numerator and denominator.

normalizeToInt

Rational normalizeToInt(double tolerance)
                  throws Rational.RationalException
Normalize this Rational so that the result: a) has a denominator unity and b) approximates this in value, to within tolerance.

Parameters:
tolerance - the acceptable error in value of the result.
Returns:
a Rational which approximates this but has a denominator of 1
Throws:
Rational.RationalException - if no acceptable result can be found.

normalizeToBigDecimal

Rational normalizeToBigDecimal(double tolerance)
                         throws Rational.RationalException
Normalize this such that the denominator is a power of ten AND the value of the result differs from the value of this by not more than the tolerance.

Parameters:
tolerance - the acceptable discrepancy in values (may be zero).
Returns:
the "equivalent" Rational, or this.
Throws:
Rational.RationalException - An "equivalent" instance cannot be created.

BigDecimalRational

private static Rational BigDecimalRational(java.math.BigInteger top,
                                           java.math.BigInteger bottom,
                                           double tolerance,
                                           int characteristic,
                                           java.lang.String id)
Class method to yield an explicitly identified Rational which approximates top/bottom to within tolerance (to exponent characteristic).

Parameters:
top - a BigInteger representing the numerator of the the value to be approximated.
bottom - a BigInteger representing the denominator of the value to be approximated.
tolerance - the starting value of tolerance.
characteristic - the characteristic of the original tolerance.
id - identifier to be used for the result
Returns:
either a Rational or null (if the value couldn't be approximated within tolerance).

normalize

public void normalize()
MUTATING instance method to remove any common factors from top and bottom. Also ensures that denominator is not negative. Furthermore, it updates the value of the estimate. Repeated applications of this method on an object should have no effect. The effective value of this object before and after normalization must be the same.

Specified by:
normalize in interface Normalizable

isNormal

public boolean isNormal()
Method to determine if this instance is already normalized. In the case of Rational, it is too complicated to determine if the instance is already normalized. So we just say it isn't.

Specified by:
isNormal in interface Normalizable
Returns:
false // TODO Implement isNormal more properly.

pow

protected BaseNumber pow(double power)
Method to yield this raised to a double-precision power.

Parameters:
power - the power with which to raise this.
Returns:
either Rational (possibly this) or an Approximation.

root

Rational root(int p)
        throws Rational.RationalException
method root: to yield an exact (integer) Rational for the root of a positive integral Rational. Throws an exception if this is not a positive integer or cannot otherwise yield an exact result.

Parameters:
p - the inverse of the power to which this will be raised.
Returns:
the pth root of this.
Throws:
Rational.RationalException

squareRational

Rational squareRational()
Method to return the Rational formed my multiplying this by itself.

Returns:
the square of this Rational.

toString

public java.lang.String toString()
Method to yield a string representing this Rational exactly.

Overrides:
toString in class Item
Returns:
a string representing this exactly.
See Also:
toString(double)

toString

final java.lang.String toString(double tolerance)
Method to determine a suitable string to represent this Rational, such that the resulting string is precise within tolerance.

Parameters:
tolerance - the maximum discrepancy between the value represented by the result and this.
Returns:
a string which approximates this closely (within tolerance) OR, if an exception is thrown, "Rational.toString: cannot form string for...."
See Also:
present(double)

presentRatio

private Presentation presentRatio()
                           throws PresentationException
Method to convert this Rational into the appropriate NumberPresentation as a ratio rather than as a decimal. However, if the denominator has more bits than the MAX_RATIO_BITS threshhold, then this is presented simply as a decimal.

Returns:
a NumberPresentation which is exactly equivalent to this.
Throws:
PresentationException - if this object cannot be presented in ratio form.

present

private Presentation present(AttrMap attributes,
                             double tolerance,
                             boolean notRatio)
                      throws PresentationException
Method to convert this Rational into an equivalent Presentation. If possible (i.e. if the tolerance is sufficiently wide), a NumberPresentation is returned (which may or may not have empty fuzz). Otherwise, a NumberPresentation is returned. // TODO should use the present(AttrMap) instead.

Parameters:
attributes - the Attributes map.
tolerance - the acceptable error in the result (normally tolerance is equal to the absolute bound).
notRatio - a boolean which, if true, prevents this being presented as a ratio.
Returns:
a NumberPresentation which is, within the tolerance, equivalent value-wise to this
Throws:
PresentationException - if this object cannot be presented with this value of tolerance.

present

private Presentation present(AttrMap attributes,
                             double tolerance)
                      throws PresentationException
Method to convert this Rational into an equivalent Presentation. If possible (i.e. if the tolerance is sufficiently wide), a NumberPresentation is returned (which may or may not have empty fuzz). Otherwise, a NumberPresentation is returned. // TODO should use the present(AttrMap) instead.

Parameters:
tolerance - the acceptable error in the result (normally tolerance is equal to the absolute bound).
Returns:
a NumberPresentation which is, within the tolerance, equivalent value-wise to this
Throws:
PresentationException - if this object cannot be presented with this value of tolerance.

present

private Presentation present(double tolerance)
                      throws PresentationException
Method to convert this Rational into an equivalent Presentation. If possible (i.e. if the tolerance is sufficiently wide), a NumberPresentation is returned (which may or may not have empty fuzz). Otherwise, a NumberPresentation is returned. // TODO should use the present(AttrMap) instead.

Parameters:
tolerance - the acceptable error in the result (normally tolerance is equal to the absolute bound).
Returns:
a NumberPresentation which is, within the tolerance, equivalent value-wise to this
Throws:
PresentationException - if this object cannot be presented with this value of tolerance.

present

public Presentation present(AttrMap attributes)
                     throws PresentationException
Convert this Presentable object into a Presentation, according to the set of attributes provided.

Specified by:
present in interface Presentable
Parameters:
attributes - a map of the required attributes for the presentation. Supported attributes include:
Normalize
String On / Off*;
Tolerance
Double/String value (def: 0);
NYI: Places
Integer/String the number of decimal places to show
NYI: Round
String On * / Off
NYI: Radix
Integer/String the value of the radix
NYI: Zero
String On * / Off where to show 0.x or just .x
NYI: Decimal
String "." or ","
Returns:
an appropriate instance of Presentation.
Throws:
PresentationException - if this object cannot be presented with the given attributes.

valueOf

public static Rational valueOf(Presentation presentation)
                        throws PresentationException
Convert Presentation presentation into a Rational. Note the result is NOT marked constant.

Parameters:
presentation - a Presentation.
Returns:
a new mutable instance of Rational.
Throws:
PresentationException - if presentation presentation cannot be parsed as a Rational object.

toApproximation

Approximation toApproximation(double tolerance)
Method to convert this Rational into the appropriate Approximation. Note that precision will generally be lost in this operation.

Parameters:
tolerance - a non-negative representation of the maximum error being introduced by this type conversion.
Returns:
a Approximation which is exactly equivalent to this.

pow

public Rational pow(Rational power)

longValue

long longValue(double tolerance)
         throws Rational.RationalException
Method to yield the long value of this object.

Parameters:
tolerance - The tolerance within which we don't mind losing precision as we perform this conversion.
Returns:
a long which is equal to doubleValue(), within tolerance.
Throws:
Rational.RationalException

timesTenToPower

void timesTenToPower(int power)
Package-protected MUTATING method to multiply this by a power of ten.

Parameters:
power - the power of ten by which to multiply this.

magnitude

double magnitude()
Method to yield the magnitude of this Rational as a double.

Returns:
the (absolute) double value of this (or infinity if appropriate).
See Also:
doubleValue()

isIntFuzzy

boolean isIntFuzzy()
This method is used to determine if the numerical value of this is convertible to a int, without regard to the precision. Compare with isInt which requires that this is exact.

Returns:
denominator==1 AND numerator

toBigDecimal

private java.math.BigDecimal toBigDecimal(double tolerance)
                                   throws Rational.RationalException
Method to yield a BigDecimal instance which approximates this. The closeness of the approximation is governed by tolerance: if a BigDecimal can be found whose value differs from the value of this by not more than tolerance, it is returned, otherwise an exception is thrown.

Parameters:
tolerance - the degree to which the result may differ in value from this.
Returns:
the equivalent to this, within the given tolerance.
Throws:
Rational.RationalException - a suitable BigDecimal equivalent could not be found.

toBigDecimal

private java.math.BigDecimal toBigDecimal(int halfPlaces)
                                   throws Rational.RationalException
Method to yield a BigDecimal instance which approximates this. The tolerance of the approximation equal to the maximum of the intrinsic error in the number of half places and the error bound of this: if a BigDecimal can be found whose value differs from the value of this by not more than the tolerance, it is returned, otherwise an exception is thrown.

Parameters:
halfPlaces - the number of halfPlaces we want the big decimal to be accurate to.
Returns:
the equivalent to this.
Throws:
Rational.RationalException - a suitable BigDecimal equivalent could not be found.
See Also:
toBigDecimal(double)

toBigDecimal

private java.math.BigDecimal toBigDecimal()
                                   throws Rational.RationalException
Method to yield a BigDecimal instance which approximates this. The closeness of the approximation is governed by the error bound of this: if a BigDecimal can be found whose value differs from the value of this by not more than the error bound, it is returned, otherwise an exception is thrown.

Returns:
the equivalent to this.
Throws:
Rational.RationalException - a suitable BigDecimal equivalent could not be found.
See Also:
toBigDecimal(double)

InitialValueOf

public static Rational InitialValueOf(java.lang.String string)
Create a constant value of a Rational from a string. Used during initialization because it does not throw checked exceptions. If a PresentationException is thrown, it will be reported on the error output.

Parameters:
string - the string from which to create and identify the new object.
Returns:
an immutable Rational whose value corresponds to string.
See Also:
valueOf(String), MutableNumber.setConstant()

BigTenToPower

private static java.math.BigInteger BigTenToPower(int x)
Class method to yield a BigInteger whose value is 10 to the power of x.
Note: this is only valid for positive x - else an exception will be thrown

Parameters:
x - the power of 10 required.
Returns:
a BigInteger with value 10^x

forceFuzzy

private void forceFuzzy()
MUTATING method to ensure that this Rational is (potentially) fuzzy, that is to say its Numerator must be FuzzyMutable.


addAbsError

protected void addAbsError(double absBound,
                           int model)
This method is used to add in an intrinsic error bound. Since there is no actual addition taking place, the normal addition methods cannot achieve the goal. Neither can we add in zero with its own bound, since all bounds are considered relative.

Parameters:
absBound - the (intrinsic) error bound which should be added in to any existing error bound of this.
model - the model of the intrinsic error.

GetBound

private static double GetBound(double x,
                               boolean exact)
Get the bounds for a number in double format which is either exact or accurate only to the number of decimal places given.

Parameters:
x - the value itself.
exact - true if the value is intended to be exact (it can't be more exact than a double can be); false if only the digits given are known.
Returns:
the value of the absolute bound on x.

compareTo

protected int compareTo(Rational val,
                        boolean absolute)
Compares this Rational with the specified Rational. This method is provided in preference to individual methods for each of the six boolean comparison operators (<, ==, >, >=, !=, <=). The suggested idiom for performing these comparisons is: (x.compareTo(y) <op> 0), where <op> is one of the six comparison operators.

Parameters:
val - Rational to which this Rational is to be compared.
absolute - Whether to take the difference (if true) or the quotient (if false) when comparing the values.
Returns:
-1, 0 or 1 as this Rational is numerically less than, equal to, or greater than val.

compareTo

public int compareTo(Rational val)
Compares this Rational with the specified Rational. This method is provided in preference to individual methods for each of the six boolean comparison operators (<, ==, >, >=, !=, <=). The suggested idiom for performing these comparisons is: (x.compareTo(y) <op> 0), where <op> is one of the six comparison operators.

Parameters:
val - Rational to which this Rational is to be compared.
Returns:
-1, 0 or 1 as this Rational is numerically less than, equal to, or greater than val.

compareTo

public int compareTo(Integral val)
Compares this Rational with the specified Integral. This method is provided in preference to individual methods for each of the six boolean comparison operators (<, ==, >, >=, !=, <=). The suggested idiom for performing these comparisons is: (x.compareTo(y) <op> 0), where <op> is one of the six comparison operators.

Parameters:
val - Rational to which this Rational is to be compared.
Returns:
-1, 0 or 1 as this Rational is numerically less than, equal to, or greater than val.

InitParse

private static Rational InitParse(Presentation presentation,
                                  java.lang.String id)

WidenIntegral

private static BaseNumber WidenIntegral(BaseNumber number)
Method to convert an Integral object into an Arithmutable object if necessary.

Parameters:
number - the number as an Integral.
Returns:
either the original number or a new WholeNumber which is equivalent and still can be cast to Integral. // TODO There is a significant danger still that number itself should not be returned here. It may be shared by some other Rational (or other object) and should therefore not be modified (even if it is not a "constant"). However, is there any way we can tell so that we don't needlessly clone?

ensureNumeratorArithmutable

private void ensureNumeratorArithmutable()
MUTATING method to ensure that the numerator is an Arithmutable object.


ensureDenominatorArithmutable

private void ensureDenominatorArithmutable()
MUTATING method to ensure that the numerator is an Arithmutable object.


setNumerator

private void setNumerator(BaseNumber numerator)
MUTATING method to set the value of the numerator.
Note: although impossible to enforce programmaticaly, this method (and its twin) must be the only place where we see the construction: _Numerator =

Parameters:
numerator - the numerator (top) of the ratio, which must be an instance of either Manifest or WholeNumber.
Throws:
Rational.RationalException - if either numerator or denominator is not an instance of either Manifest or WholeNumber.

setDenominator

private void setDenominator(BaseNumber denominator)
MUTATING method to set the value of the denominator.
Note: although impossible to enforce programmaticaly, Note: although impossible to enforce programmaticaly, this method (and its twin) must be the only place where we see the construction: _Denominator =

Parameters:
denominator - the denominator (bottom) of the ratio, which must be an instance of either Manifest or WholeNumber.
Throws:
Rational.RationalException - if either numerator or denominator is not an instance of either Manifest or WholeNumber.

setNumerator

private void setNumerator(Integral numerator)
MUTATING method to set the value of the numerator.
Note: although impossible to enforce programmaticaly, this method (and its twin) must be the only place where we see the construction: _Numerator =

Parameters:
numerator - the numerator (top) of the ratio, which must be an instance of either Manifest or WholeNumber.
Throws:
Rational.RationalException - if either numerator or denominator is not an instance of either Manifest or WholeNumber.

setDenominator

private void setDenominator(Integral denominator)
MUTATING method to set the value of the denominator.
Note: although impossible to enforce programmaticaly, Note: although impossible to enforce programmaticaly, this method (and its twin) must be the only place where we see the construction: _Denominator =

Parameters:
denominator - the denominator (bottom) of the ratio, which must be an instance of either Manifest or WholeNumber.
Throws:
Rational.RationalException - if either numerator or denominator is not an instance of either Manifest or WholeNumber.

SafeReference

private static BaseNumber SafeReference(BaseNumber x)
This method yields a reference to a BaseNumber (the numerator or denominator) for the purpose of cloning/copying a Rational object safely. If x is constant, either by class or by property, it will be returned as is. Otherwise, it will be cloned.

Parameters:
x - the number to be copied
Returns:
either x or the clone of x.

setExact

private void setExact()

divideNumeratorAndRemainder

private java.math.BigInteger[] divideNumeratorAndRemainder(Integral divisor)

gcd

private java.math.BigInteger gcd(boolean strict)

GetBigInteger

private static java.math.BigInteger GetBigInteger(Integral x,
                                                  boolean strict)

main

public static void main(java.lang.String[] args)
Main method for testing this class.

Parameters:
args - String[] : the command line options.