/Complex.js Secret
Created
December 8, 2014 20:06
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module.exports = Complex; | |
function Complex(real, imag) { | |
this.getReal = function () { | |
return real; | |
}; | |
this.getImaginary = function () { | |
return imag; | |
} | |
this.getModulus = function () { | |
return Math.sqrt(real*real + imag*imag); | |
}; | |
this.getConjugate = function () { | |
return new Complex(real, -imag); | |
}; | |
this.getArgument = function () { | |
return Math.atan2(imag, real); | |
}; | |
this.add = function (num) { return Complex.add(this, num); }; | |
this.subtract = function (num) { return Complex.subtract(this, num); }; | |
this.multiply = function (num) { return Complex.multiply(this, num); }; | |
this.divide = function (num) { return Complex.divide(this, num); } | |
this.divide = function (num) { | |
return Complex.divide(this, num); | |
} | |
this.toString = function () { | |
if (real === 0 && imag !== 0) { | |
return imag + 'i'; | |
} else if (imag === 0 && real !== 0) { | |
return real.toString(); | |
} else if (imag === 0 && real === 0) { | |
return 0; | |
} | |
return real.toString() + (imag < 0 ? ' - ' + imag : ' + ' + imag) + 'i'; | |
}; | |
} | |
Complex.add = function (a, b) { | |
return new Complex(a.getReal() + b.getReal(), a.getImaginary() + b.getImaginary()); | |
} | |
Complex.subtract = function (a, b) { | |
return new Complex(a.getReal() - b.getReal(), a.getImaginary() - b.getImaginary()); | |
}; | |
Complex.multiply = function (a, b) { | |
return new Complex( | |
a.getReal()*b.getReal() - a.getImaginary()*b.getImaginary(), | |
a.getReal()*b.getImaginary() + b.getReal()*a.getImaginary() | |
) | |
}; | |
Complex.divide = function (a, b) { | |
var dividend = a.multiply(b.getConjugate()) | |
var divisor = b.getReal()*b.getReal() + b.getImaginary()*b.getImaginary(); | |
return new Complex(dividend.getReal() / divisor, dividend.getImaginary() / divisor); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment