Complex numbers in ActionScript

Here's a class for handling complex numbers and their basic operations with ActionScript. With minor modification it should work with JavaScript as well. It should be pretty obvious to use by just looking at the source code. Due to lack of operator overloading, there are methods for Add, Subtract, Multiply, Divide and Equals. It's probaly a lot slower than the native Number class/data type.

function Complex(r, i) {

Complex.prototype=new Object();

Complex.prototype.Add=function(im) {
  return new Complex(this.r+im.r, this.i+im.i);

Complex.prototype.Subtract=function(im) {
  return new Complex(this.r-im.r, this.i-im.i);

Complex.prototype.Equals=function(c) {
  return this.r==c.r && this.i==c.i;

Complex.prototype.Multiply=function(im) {
  return new Complex(this.r*im.r-this.i*im.i, this.i*im.r+this.r*im.i);

Complex.prototype.Divide=function(im) {
  var c=this.Multiply(im.Conjugate());
  var d=im.r*im.r+im-i*im.i;
  return new Complex(c.r/d, c.i/d);

Complex.prototype.Argument=function() {
  return Math.atan2(this.i, this.r);

Complex.prototype.Modulus=function() {
  return Math.sqrt(this.r*this.r+this.i*this.i);

Complex.prototype.Conjugate=function() {
  return new Complex(this.r, -this.i);

Complex.prototype.toString=function() {
  if(this.r==0 && this.i==0) return "0";
  var s="";
  if(this.r!=0) s+=this.r;
  if(this.i>0 && this.r!=0) s+="+";
  if(this.i==1) {
    return s;
  if(this.i==-1) {
    return s;
  if(this.i!=0) s+=this.i+"i";
  return s;
Categories: Programming
Posted by Matias at 03.03.2012 07.52 (5 years ago) | 465 comments


Post a new comment

Will be displayed within an image file, hopefully undecipherable to address harvesters.

content licensed under Creative Commons BY-NC-SA - Valid HTML 5