Instantly share code, notes, and snippets.

# bytecodeman/Rational.java Last active Feb 7, 2019

Rational Number Sample Code
 /* * Rational Number Class * Prof. A.C. Silvestri * CSC-112 Intermediate Java * 02/08/18 */ public class Rational implements Comparable { final private int num; final private int den; public final static Rational ZERO = new Rational(0); public final static Rational ONE = new Rational(1); // **************************************************************** public int getNumerator() { return num; } public int getDenominator() { return den; } // **************************************************************** public Rational() { this(0, 1); } public Rational(int num) { this(num, 1); } public Rational(int numerator, int denominator) { if (denominator == 0) { throw new ArithmeticException("denominator is zero"); } // reduce fraction int g = gcf(numerator, denominator); if (denominator > 0) { this.num = numerator / g; this.den = denominator / g; } else { this.num = -numerator / g; this.den = -denominator / g; } } // **************************************************************** public Rational times(Rational b) { int num = this.num * b.num; int den = this.den * b.den; return new Rational(num, den); } public Rational plus(Rational b) { Rational a = this; // special cases (Really Not Needed) if (a.compareTo(Rational.ZERO) == 0) return b; if (b.compareTo(Rational.ZERO) == 0) return a; int num = a.num * b.den + a.den * b.num; int den = a.den * b.den; return new Rational(num, den); } public Rational negate() { return new Rational(-this.num, this.den); } public Rational abs() { if (num >= 0) return this; else return negate(); } public Rational minus(Rational b) { Rational a = this; return a.plus(b.negate()); } public Rational reciprocal() { return new Rational(den, num); } public Rational divides(Rational b) { Rational a = this; return a.times(b.reciprocal()); } // **************************************************************** public double toDouble() { return (double) num / den; } public String toString() { if (den == 1) return num + ""; else return num + "/" + den; } // return { -, 0, + } if a < b, a = b, or a > b public int compareTo(Rational b) { Rational a = this; int lhs = a.num * b.den; int rhs = a.den * b.num; if (lhs < rhs) return -1; if (lhs > rhs) return +1; return 0; } // is this Rational object equal to y? public boolean equals(Object y) { if (this == y) return true; if (y == null) return false; if (y.getClass() != this.getClass()) return false; Rational b = (Rational) y; return compareTo(b) == 0; } private static int gcf(int m, int n) { int retval = 0; if (m < 0) m = -m; if (n < 0) n = -n; if (n == 0) retval = m; else { int rem; while ((rem = m % n) != 0) { m = n; n = rem; } retval = n; } return retval; } // Not needed or used, but just cool to see @SuppressWarnings("unused") private static int lcm(int m, int n) { if (m < 0) m = -m; if (n < 0) n = -n; return m * n / gcf(m, n); } }