RationalComplex.java


Below is the syntax highlighted version of RationalComplex.java from §9.2 Floating Point.


/******************************************************************************
 *  Compilation:  javac RationalComplex.java
 *  Execution:    java RationalComplex
 *
 *  A complex number with arbitrary precision rational components.
 *
 ******************************************************************************/

public class RationalComplex {
    private final BigRational re;
    private final BigRational im;


    // create a new object with the given real and imaginary parts
    public RationalComplex(BigRational real, BigRational imag) {
        re = real;
        im = imag;
    }


    // return a string representation of the invoking Complex object
    public String toString() {
        if (im.equals(BigRational.ZERO)) return re + "";
        if (re.equals(BigRational.ZERO)) return im + "i";
        if (im.isNegative()) return re + " - " + (im.negate()) + "i";
        return re + " + " + im + "i";
    }

    // return a new Complex object whose value is (this + b)
    public RationalComplex plus(RationalComplex b) {
        RationalComplex a = this;
        BigRational real = a.re.plus(b.re);
        BigRational imag = a.im.plus(b.im);
        return new RationalComplex(real, imag);
    }

    // return a new Complex object whose value is (this - b)
    public RationalComplex minus(RationalComplex b) {
        RationalComplex a = this;
        BigRational real = a.re.minus(b.re);
        BigRational imag = a.im.minus(b.im);
        return new RationalComplex(real, imag);
    }

    // return a new Complex object whose value is (this * b)
    public RationalComplex times(RationalComplex b) {
        RationalComplex a = this;
        BigRational real = a.re.times(b.re).minus(a.im.times(b.im));
        BigRational imag = a.re.times(b.im).plus(a.im.times(b.re));
        return new RationalComplex(real, imag);
    }

    // square of 2 norm
    public BigRational normSquared() {
        return re.times(re).plus(im.times(im));
    }


  public static void main(String[] args) {
        BigRational a1 = new BigRational(5, 1);
        BigRational a2 = new BigRational(6, 1);
        BigRational b1 = new BigRational(-1, 3);
        BigRational b2 = new BigRational(2, 7);
        RationalComplex a = new RationalComplex(a1, a2);
        RationalComplex b = new RationalComplex(b1, b2);

        StdOut.println("a            = " + a);
        StdOut.println("b            = " + b);
        StdOut.println("b + a        = " + b.plus(a));
        StdOut.println("a - b        = " + a.minus(b));
        StdOut.println("a * b        = " + a.times(b));
        StdOut.println("b * a        = " + b.times(a));
    }


}


Copyright © 2000–2017, Robert Sedgewick and Kevin Wayne.
Last updated: Fri Oct 20 14:12:12 EDT 2017.