Skip to content

Instantly share code, notes, and snippets.

@IkarosKappler
Last active May 31, 2017 00:27
Show Gist options
  • Save IkarosKappler/bfffe6efe9a92871e48d56346114cd9e to your computer and use it in GitHub Desktop.
Save IkarosKappler/bfffe6efe9a92871e48d56346114cd9e to your computer and use it in GitHub Desktop.
A simple and minimal javascript class for complex number arithmetic (does not support SQRT yet).
/**
* A complex math class in rectangular coordinates.
*
* @author Ikaros Kappler
* @date 2017-05-03
* @modified 2017-05-30 Fixed wrong named 'div' function ('sub' duplicates).
* @version 1.0.1
**/
var Complex = (function() {
var constructor = function( re, im ) {
this.re = function() { return re; };
this.im = function() { return im; };
this.clone = function() {
return new Complex(re,im);
};
this.conjugate = function(c) {
im = -im;
return this;
};
this.add = function(c) {
re += c.re();
im += c.im();
return this;
};
this.sub = function(c) {
re -= c.re();
im -= c.im();
return this;
};
this.mul = function(c) {
re = re*c.re() - im*c.im();
im = im*c.re() + re*c.im();
return this;
};
this.div = function(c) {
re = (re*c.re() - im*c.im()) / (c.re()*c.re() + c.im()*c.im());
im = (im*c.re() + re*c.im()) / (c.re()*c.re() + c.im()*c.im());
return this;
};
this.sqrt = function() {
// Huh?
};
this.toString = function() {
return '' + re + ' + i*' + im;
};
};
return constructor;
})();
// TEST
var z = new Complex(3,4);
console.log( 'test: ' + z.re() );
@IkarosKappler
Copy link
Author

IkarosKappler commented May 31, 2017

Uargh. The div-function was called 'sub', which overrides the sub function. :(
I fixed that.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment