Class Rational

java.lang.Object
java.lang.Number
Jcg.geometry.Rational
All Implemented Interfaces:
Serializable

public class Rational extends Number
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 Details

    • ZERO

      public static Rational ZERO
      the fraction 0/1
    • ONE

      public static Rational ONE
      the fraction 1/1
    • num

      private int num
      the numerator
    • den

      private int den
      the 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:
      doubleValue in class Number
    • longValue

      public long longValue()
      Specified by:
      longValue in class Number
    • intValue

      public int intValue()
      Specified by:
      intValue in class Number
    • floatValue

      public float floatValue()
      Specified by:
      floatValue in class Number
    • toString

      public String toString()
      Overrides:
      toString in class Object
    • compareTo

      public int compareTo(Rational b)
    • equals

      public boolean equals(Object y)
      Overrides:
      equals in class Object
    • hashCode

      public int hashCode()
      Overrides:
      hashCode in class Object
    • mediant

      public static Rational mediant(Rational r, Rational s)
    • gcd

      private static int gcd(int m, int n)
    • lcm

      private static int lcm(int m, int n)
    • multiply

      public Rational multiply(Rational b)
      Return the product of the curren value (this) times b, staving off overflow as much as possible by cross-cancellation
      Returns:
      the product of the current value and b
    • add

      public Rational add(Rational b)
    • negate

      public Rational negate()
    • abs

      public Rational abs()
    • subtract

      public Rational subtract(Rational b)
      Return the difference between the current value and b
      Parameters:
      b - the value to subtract
      Returns:
      the difference between the current value and b
    • reciprocal

      public Rational reciprocal()
    • divides

      public Rational divides(Rational b)