Search code examples
javascriptmath

How to calculate with complex numbers in JavaScript?


Recently, I am trying to calculate using some equations with complex numbers. However, unlike e or π, there isn't any methods or native functions that will return i. A quick search in Google didn't get me any answer. Any ideas on how to achieve it?

function imaginary() {
  return {
    rational: this,
    imaginary: "2i"  //magic code that does this
  };
};

Number.prototype.imaginary = imaginary;

Solution

  • Assuming you really want complex numbers, and not just the imaginary component:

    I would model a complex number just as you would model a 2D point, i.e. a pair of numbers.

    Just as a point has x and y components, so a complex number has real and imaginary components. Both components can just be modeled with ordinary numeric types (int, float, etc.)

    However, you will need to define new functionality for all of the mathematical operations.

    Addition and subtraction of complex numbers works the same way as addition and subtraction of points - add the separate components to each other, don't mix them. For example:

    (3+2i)+(5+4i) = (8+6i)

    Multiplication works just like you learned in algebra when multiplying (a+b)*(c+d) = (ac+ad+bc+bd).

    Except now you also have to remember that i*i = -1. So:

    (a+bi)*(c+di) = (ac+adi+bci+bdii) = (ac-bd) + (ad+bc)i

    For division and exponentiation, see http://en.wikipedia.org/wiki/Complex_number