How to calculate with imaginary numbers in JavaScript?

The math.js library supports complex numbers, matrices, and more. The library is compatible with JavaScript’s built-in Math library, so quite easy to use.

http://mathjs.org

You can just do things like:

math.i;                         // i
math.sqrt(-4)                   // 2i
var a = math.complex('2 + 3i'); // 2 + 3i
var b = math.complex(4, 5);     // 4 + 5i
math.add(a, b);                 // 6 + 8i
math.multiply(a, b);            // -7 + 22i
math.eval('e^(pi*i) + 1');      // ~0
// etc...

Edit: note that math.js comes with an expression parser, which makes it more convenient to work with complex values and mathematical expressions:

math.eval('(2 + 3i) * (4 + 5i)'); // -7 + 22i

Leave a Comment