public class Complex { private static final double TINY = 1e-6; public static final Complex une; public static final Complex zero; public static final Complex eye; private final double real; private final double im; static{ une = new Complex(1,0); zero = new Complex(); eye = new Complex(1,0); } public Complex(double _real, double _imaginary){ this.real = _real; this.im = _imaginary; } public Complex(double _real){ this.real = _real; this.im = 0.0; } public Complex(){ this.real = 0.0; this.im = 0.0; } public String toString(){ if(im>=0){ return String.format("%s + i%s", real, im); }else { return String.format("%s - i%s", real, -im); } } //use this in test code to check if complex numbers //are "close enough" since == and .equals and floating //point numbers don't always play nicely. private static boolean closeEnough(Complex z, Complex w){ return z.subtract(w).magnitude() < TINY; } public boolean equals(Object o){ if(!(o instanceof Complex)){ return false; } Complex x = (Complex) o; return x.real == real && x.im == im; } public Complex add(Complex that){ return new Complex(real + that.real, im + that.im); } public Complex subtract(Complex that){ return new Complex(real-that.real, im- that.im); } public Complex multiply(Complex that){ double x = (real*that.real -im*that.im); double y = (that.real*im + real*that.im); return new Complex(x, y); } public Complex divide(Complex that){ double x = ((real*that.real+im*that.im)/(that.real*that.real+that.im*that.im)); double y = ((that.real*im-real*that.im)/(that.real*that.real+that.im*that.im)); return new Complex(x, y); } public Complex conjugate(){ return new Complex(real, -im); } public double magnitude(){ return Math.sqrt(real*real+im*im); } public Complex pow(int n){ int count = 1; Complex end = new Complex(real, im); Complex power = new Complex(real, im); while(count < n){ end = end.multiply(power); count++;} return new Complex(end.real, end.im); } public double re() { return real; } public double im(){ return im; } public double arg(){ Complex argnum = new Complex(real,im); return Math.asin(im/argnum.magnitude()); } public static void main(String[] args){ int x = 4; Complex a = new Complex(1.0,1.0); Complex b = new Complex(); Complex c = new Complex(10.0,10.0); System.out.println(a); System.out.println(b); System.out.println(a.equals(x)); Complex d = new Complex(1.0,1.0); System.out.println(a.equals(d)); System.out.println(a.add(b)); System.out.println(a.subtract(a)); System.out.println(a.divide(b)); System.out.println(a.conjugate()); Complex e = new Complex(3.0, 4.0); System.out.println(e.magnitude()); System.out.println(b.pow(2)); System.out.println(e.re()); System.out.println(e.im()); System.out.println(e.arg()); } }