/*
 * A class defining the complex number data type
 *
 * Nadeem Abdul Hamid - CSC 120 - Fall 2004
 *
 */
 
public class Complex {
    
    double real;        // real part of the complex number
    double imag;        // imaginary part of the complex number
    
    
    // constructor initializes the fields of a complex number object
    public Complex(double r, double i) {
        real = r;
        imag = i;
    }
    
    // constructor gets input from keyboard to initialize fields
    public Complex() {
        System.out.println("Please enter the two parts of a complex"
                                + " number with a space in between: ");
        String str = Keyboard.readString();
        real 
            = Double.parseDouble(str.substring(0,str.indexOf(" ")));
        imag
            = Double.parseDouble(str.substring(str.indexOf(" ")+1,
                                                str.length()));
    }

    // addition:  (a+bi) + (c+di) = (a+c) + (b+d)i
    public Complex add(Complex other) {
        double a = real;
        double b = imag;
        double c = other.real;
        double d = other.imag;
        
        return new Complex(a+c, b+d);
    }
    
    // multiplication: (a+bi) * (c+di) = (ac - bd) + (ad + bc)i
    public Complex multiply(Complex other) {
        double a = real;
        double b = imag;
        double c = other.real;
        double d = other.imag;
        
        return new Complex(a*c - b*d, a*d + b*c);
    }
    
    // -(a+bi) = (-a) + (-b)i
    public Complex opposite() {
        return new Complex(-real, -imag);
    }
    
    // magnitude: |a+bi| = sqrt(a^2 + b^2)
    public double magnitude() {
        return Math.sqrt(real*real + imag*imag);
    }
    
    // complex conjugate: conj(a+bi) = a + (-b)i
    public Complex conjugate() {
        return new Complex(real, -imag);
    }
    
    // comparison for equality
    public boolean equals(Complex other) {
        final double TOLERANCE = 0.00000001;
        // boolean b = (real == other.real) && (imag == other.imag);
        boolean b = (Math.abs(real-other.real) < TOLERANCE)
                    && (Math.abs(imag-other.imag) < TOLERANCE);
        return b;
    }
    
    // conversion to string
    public String toString() {
        return "(" + real + " + " + imag + "i)";
    }

}