A JavaScript complex number class
The complex number class definition: cx.js
Reference:
class cx
constructor:
var c = new cx(x, y[, polar]); // returns a new complex number object:
// x + yi, or x cis y if polar is true
properties: // these all return real numbers; read-write
c.re // real part
c.im // imaginary part
c.abs // absolute value (radius)
c.arg // argument (angle)
static property:
cx.i // returns a complex number object 0 + 1i; read-only
methods:
c.toString([polar]) // returns "x + yi" or "x cis y"; output defaults to the former
c.toPrecision(n[, polar]) // returns the same, to n significant figures
c.toPrecis(n[, polar]) // " to n significant figures, without trailing zeros
c.toFixed(n[, polar]) // " to n decimal places
c.toExponential(n[, polar]) // " to n decimal places in scientific notation
static methods: // these all return a new cx unless otherwise noted
cx.conj(c) // conjugate of c
cx.neg(c) // negative c
cx.add(c, d) // c + d; c or d may be simple or complex
cx.sub(c, d) // c - d; "
cx.mult(c, d) // c * d; "
cx.div(c, d) // c / d; "
cx.pow(c, int) // c to the int power; int is an integer >= 0
cx.root(c, int[, k]) // c to the int root; int is an integer >= 2;
// k is an integer 0 <= k <= int-1 for each of the roots (default 0)
cx.log(c) // natural logarithm (base e) of c
cx.exp(c) // e to the power of c
cx.sin(c) // the trigonometric functions and their inverses
cx.cos(c)
cx.tan(c)
cx.asin(c[, k]) // k = 0 or 1 for each of the square roots in the equation (default 0)
cx.acos(c[, k]) // k = 0 or 1 "
cx.atan(c)
cx.sinh(c) // the hyperbolic functions and their inverses
cx.cosh(c)
cx.tanh(c)
cx.asinh(c[, k]) // k = 0 or 1 for each of the square roots in the equation (default 0)
cx.acosh(c[, k]) // k = 0 or 1 "
cx.atanh(c)
cx.copy(c) // returns a new cx with the same real and imaginary parts as c
cx.eq(c, d[, epsilon]) // returns true if the real and imaginary parts are equal,
// or the difference less than the (optional) epsilon value
call one of these after the class definition:
cx.degrees(false); // input and output will use radians
cx.degrees(true); // input and output will use degrees
Some derived functions and miscellany:
c-a/b = cx.div(1, cx.pow(cx.root(c, b, k), a)) logb(c) = cx.div(cx.log(c), Math.log(b)) ac = cx.exp(cx.mult(c, Math.log(a))) typeof c = "object" c instanceof cx = true
Try it yourself; enter code into the first field below, then an expression to be evaluated into the second, and press calculate. (Note: if you write an infinite loop or other bad code, you may crash your browser.)