INTRODUCTION TO COMPUTER SCIENCE
Robert Sedgewick and Kevin Wayne


This is the syntax highlighted version of PolarComplex.java.

/*************************************************************************
 *  Compilation:  javac PolarComplex.java
 *  Execution:    java PolarComplex
 *
 *  ADT for complex numbers using polar representation.
 *
 *  % java PolarComplex
 *  a = 5.0 + 6.0i
 *  b = -2.0000000000000004 + 2.9999999999999996i
 *  c = -27.999999999999996 + 2.9999999999999876i
 *
 *************************************************************************/

public class PolarComplex {
    private double r;        // distance
    private double theta;    // angle

    // constructor that takes in rectangular coordinates
    public PolarComplex(double re, double im) {
       r = Math.sqrt(re*re + im*im);
       theta = Math.atan2(im, re);
    }

    public double re() { return r * Math.cos(theta); }
    public double im() { return r * Math.sin(theta); }

    public String toString()  { return re() + " + " + im() + "i"; }

    // return this Complex number plus b
    public PolarComplex plus(PolarComplex b) {
       PolarComplex a = this;
       double re = a.r * Math.cos(a.theta) + b.r * Math.cos(b.theta);
       double im = a.r * Math.sin(a.theta) + b.r * Math.sin(b.theta);
       return new PolarComplex(re, im);
    }

    // return this Complex number times b
    public PolarComplex times(PolarComplex b) {
        PolarComplex a = this;
        PolarComplex c = new PolarComplex(0, 0);
        c.r = a.r * b.r;
        c.theta = a.theta + b.theta;
        return c;
    }

    public double abs() { return r;  }


    // sample client for testing - calculates roots of unity
    public static void main(String[] args) {
        PolarComplex a = new PolarComplex(5.0, 6.0);
        System.out.println("a = " + a);

        PolarComplex b = new PolarComplex(-2.0, 3.0);
        System.out.println("b = " + b);

        PolarComplex c = b.times(a);
        System.out.println("c = " + c);
    }

}


Last updated: Sat May 22 07:32:41 EDT 2004 .
Copyright © 2004, Robert Sedgewick and Kevin Wayne.