Class Rational
java.lang.Object
java.lang.Number
Jcg.geometry.Rational
- All Implemented Interfaces:
Serializable
Authors: Copyright © 2000–2022, Robert Sedgewick and Kevin Wayne.
Compilation: javac Rational.java
Execution: java Rational
Immutable ADT for Rational numbers.
Invariants
-----------
- gcd(num, den) = 1, i.e, the rational number is in reduced form
- den >= 1, the denominator is always a positive integer
- 0/1 is the unique representation of 0
We employ some tricks to stave of overflow, but if you
need arbitrary precision rationals, use BigRational.java.
- See Also:
-
Field Summary
Fields -
Constructor Summary
ConstructorsConstructorDescriptionRational(int numerator, int denominator) Initializa a new Rational number with a given numerator and denominator -
Method Summary
Modifier and TypeMethodDescriptionabs()intintdoublebooleanfloatprivate static intgcd(int m, int n) inthashCode()intintValue()private static intlcm(int m, int n) longstatic RationalReturn the product of the curren value (this) times b, staving off overflow as much as possible by cross-cancellationnegate()intvoidsetRational(int numerator, int denominator) Return the difference between the current value and btoString()Methods inherited from class java.lang.Number
byteValue, shortValue
-
Field Details
-
ZERO
the fraction 0/1 -
ONE
the fraction 1/1 -
num
private int numthe numerator -
den
private int denthe denominator
-
-
Constructor Details
-
Rational
public Rational(int numerator, int denominator) Initializa a new Rational number with a given numerator and denominator- Parameters:
numerator-denominator-
-
-
Method Details
-
numerator
public int numerator() -
denominator
public int denominator() -
setRational
public void setRational(int numerator, int denominator) -
doubleValue
public double doubleValue()- Specified by:
doubleValuein classNumber
-
longValue
-
intValue
-
floatValue
public float floatValue()- Specified by:
floatValuein classNumber
-
toString
-
compareTo
-
equals
-
hashCode
-
mediant
-
gcd
private static int gcd(int m, int n) -
lcm
private static int lcm(int m, int n) -
multiply
-
add
-
negate
-
abs
-
subtract
-
reciprocal
-
divides
-