Source code for RationalField.java

What follows is the highlighted source code with comments. You can also download this file directly: RationalField.java.

/*
 * This work by W. Patrick Hooper is free of known copyright restrictions.
 * The work is in the public domain.
 * 
 * Author's website: <a href="http://wphooper.com">http://wphooper.com</a>. 
 */

package number;

import java.util.Comparator;

/**
 * This class is made to do algebra with rationals. 
 * 
 * @author W. Patrick Hooper <wphooper@gmail.com>
 * @version 1
 */
public class RationalField implements Comparator<Rational> {

    /** Construct a new RationalField. This thing has no data... */
    public RationalField(){}
    
    /**
     * Add two rationals x and y.
     */
    public Rational add(Rational x, Rational y) {
        return new Rational(x.numerator().multiply(y.denominator()).add(y.numerator().multiply(x.denominator())),
                x.denominator().multiply(y.denominator()));
    }

    /** 
     * Negate the rational x.
     */
    public Rational neg(Rational x) {
        return new Rational(x.numerator().negate(),x.denominator());
    }

    /** 
     * Return the difference, x-y.
     */
    public Rational sub(Rational x, Rational y) {
        return add(x,neg(y));
    }

    /**
     * Return the product of x and y.
     */
    public Rational mult(Rational x, Rational y) {
        return new Rational(x.numerator().multiply(y.numerator()),
                x.denominator().multiply(y.denominator()));
    }
    
    /**
     * Return the multiplicative inverse.
     */
    public Rational inv(Rational x) {
        return new Rational(x.denominator(),x.numerator());
    }
    
    /** Return the ratio, y/x. */
    public Rational div(Rational x, Rational y) {
        return mult(x,inv(y));
    }

    /** Compare two rationals. 
     * It returns 1 if x>y, 0 if x=y, and -1 if x<y. 
     */
    @Override
    public int compare(Rational x, Rational y) {
        return sub(x,y).signum();
    }
    
    
    
}
HOOPER >>>>> JAVA TUTORIAL
Last modified on August 17, 2018.
[check html] [check css]