/*
 * Complex.js:
 * This file defines a Complex class to represent complex numbers.
 */

function Complex(real, imag) {
    this.x = real;       // The real part of the number
    this.y = imag;  // The imaginary part of the number
}

// Return the magnitude of a complex number. This is defined
// as its distance from the origin (0,0) of the complex plane.
Complex.prototype.magnitude = function( ) {
    return Math.sqrt(this.x*this.x + this.y*this.y);
};

// Return a complex number that is the negative of this one.
Complex.prototype.negative = function( ) {
    return new Complex(-this.x, -this.y);
};

// product.
Complex.prototype.multiply = function(b ) {
	return new Complex(this.x * b.x - this.y * b.y,
                       this.x * b.y + this.y * b.x);
};

// sum.
Complex.prototype.add = function(b ) {
	return new Complex(this.x + b.x, this.y + b.y);
};

// difference.
Complex.prototype.subtract = function(b ) {
	return new Complex(this.x - b.x, this.y - b.y);
};

//  Convert a Complex object to a string.
//  This is invoked when a Complex object is used as a string.
Complex.prototype.toString = function() {
    return "("+this.x + "+" + this.y + "i)";
};

// Return the real portion of a complex number. 
Complex.prototype.real = function( ) { return this.x; }

// Add two complex numbers and return the result.
Complex.add = function (a, b) {
    return a.add(b);
};

// Subtract one complex number from another.
Complex.subtract = function (a, b) {
    return a.subtract(b);
};

// Multiply two complex numbers and return the product.
Complex.multiply = function(a, b) {
    return a.multiply(b);
};

// Here are some useful predefined complex numbers.
Complex.zero = new Complex(0,0);
Complex.one = new Complex(1,0);
Complex.i = new Complex(0,1);

