Skip to content

Yugandhara/Javascript-Complex-Math-Library

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

44 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Complex.js

Complex.js is a lightweight module that enables Complex mathematics in JavaScript. It comes with every elementary function and all mathematical operators. It also includes many utility functions and common non-analytical functions such as the Complex conjugate, the argument function, the absolute value function and many others.

Lastly, but most importantly, this module contains a compiler to parse human-readable expressions into native JavaScript functions. The compiler, accessible from Complex.parseFunction, accepts an arbitrary amount of parameters to pass to the function, specified by their human-readable names. Example usage can be found below in the section Parsing Human-Readable Expressions.

Although originally written for use in the browser, it can also now be used within Node.js.

Overview


## Download

To install via npm, run:

npm install complex-js

To include this module in the Node.js environment, add the line:

var Complex = require('complex-js');

In the browser, simply add the script:

<script type="text/javascript" src="complex.min.js"></script>
## Functions vs. Operators

Functions are denoted as Complex.staticMethod. For example, to evaluate the tangent of the imaginary unit, do the following:

console.log(Complex.tan(Complex(0,1)));

All functions are static, meaning that they are called directly by the Complex namespace. Operators are non-static methods, which means they must be called by an instance of Complex. For example, to raise 1+5i to the power of 3 e^((2/3)pi i), do the following:

console.log(Complex(1,5).cPow(Complex.Polar(3,2/3*Math.PI)));

Notice how cPow is a method of a Complex instance, and not of the namespace Complex. That's because it is an operator rather than a function. Non-static methods are denoted as Complex.prototype.nonStaticMethod.

## Coordinate Notation

Complex.js supports both cartesian and exponential notation. In order to declare a Complex number with cartesian coordinates, you can call the default constructor with the following arguments:

var cartesian_1_plus_5_i = Complex(1,5);

Declaring it with the new keyword is optional, since the constructor detects and corrects instantiation automatically. Optionally, you may supply the absolute value and the argument of the Complex number as well for the 3rd and 4th parameters, though this is not recommended. Exponential notation is supported through the secondary Polar constructor as such:

var exponential_1_e_to_pi_i = Complex.Polar(1,Math.PI);

Note that this constructor does not support the new keyword and should never be called with it, as it does so internally.

Similarly, both notations are supported in the toString method. Simply call toString() for exponential (the default), or toString(true) for cartesian notation.

These strings can be used to reconstruct the Complex instances, but that will be covered in the next section.

## Parsing Human-Readable Expressions

Complex.js also includes a compiler for human-readable expressions, which is very useful for constructing functions callable from JavaScript. Since it supports virtually any common notations and fully supports order of operations, it's very easy to use. It even normalizes implied multiplication and non-parenthetical grouping by default. A simple use-case example is below.

HTML:

<!-- the value is (5+i)^(.00003+10*sin(5i)) -->
<div>
	<span>Evaluate:</span>
	<input type="text" id="calc" value="(5+i)^(3e-5+10*sin(5i))"/>
</div>
<div>
	<span>Cartesian:</span>
	<span id="ans-cart"></span>
</div>
<div>
	<span>Exponential:</span>
	<span id="ans-expo"></span>
</div>
<script type="text/javascript" src="complex.min.js"></script>
<script type="text/javascript">
	...
</script>

JavaScript:

var input = document.getElementById('calc'),
	cart = document.getElementById('ans-cart'),
	expo = document.getElementById('ans-expo');

input.addEventListener('change', function(){
	try {
		var
			//will throw an error if input is invalid
			calc = Complex.parseFunction(input.value),
			//evaluate the compiled function for the answer
			ans = calc();
		//use the toString method
		cart.innerHTML = ans.toString(true);
		expo.innerHTML = ans.toString();
	} catch(error) {
		//if the parser throws an error, clear outputs and alert error
		cart.innerHTML = "";
		expo.innerHTML = "";
		alert(error);
	}
});

Note that the compiler creates a function rather than evaluating the expression that is compiled immediately. The function returned is high-performace, since it caches all real-values in the expression so that they don't need to be re-evaluated with each call.

The following is an example where the compiler provides parameters for the compiled function:

// Node.js
var Complex = require("complex-js"),
	param_a = Complex(5,1),
	param_b = Complex(3e-5,0),
	param_c = Complex(0,5),
	// human-readable variable names in expression
	complex_func = "a^(b+10*sin(c))",
	// array of parameters for function is order-dependent
	js_func = Complex.parseFunction(complex_func, ["b","a","c"]),
	// how to pass parameters to compiled function
	output = js_func(param_b, param_a, param_c);

// output cartesian form as string
console.log(output.toString(true));

The Complex.parseFunction method can also reconstruct a Complex number from a string created by Complex.toString. See below for a demonstration:

var five_plus_i_str = Complex(5,1).toString(true), //store as cartesian
    five_plus_i = (Complex.parseFunction(five_plus_i_str))();

// should log true
console.log(five_plus_i instanceof Complex && five_plus_i.r === 5 && five_plus_i.i === 1);

## Documentation

Constants

For convenience, but also used in many of the trigonometric methods.

  • 0 - zero
  • 1 - one
  • I - i
  • -I - negative i
  • PI - irrational constant "pi"
  • E - irrational constant "e"
  • 2 - two
  • 2I - two i

## Constructors ### Complex(real, imag[, abs[, arg]])

The cartesian constructor for instances of the Complex class. Optionally call with new, but not required.

Arguments

  • real - A Number specifying the real value of the Complex number.
  • imag - A Number specifying the imaginary value of the Complex number.
  • abs - An optional Number specifying the absolute value of the Complex number. Not recommended unless accurately calculated.
  • arg - An optional Number specifying the argument of the Complex number. Not recommended unless accurately calculated.
### Complex.Polar(abs, arg)

The exponential constructor for instances of the Complex class. Note Do not call this constructor with new.

Arguments

  • abs - A Number specifying the absolute value of the Complex number.
  • arg - A Number specifying the argument of the Complex number.

Note In order to access the values directly from the instance, examine the following demo code:

var complex = Complex(Math.random()*2-1,Math.random()*2-1);
console.log(
	complex.r, // real part
	complex.i, // imaginary part
	complex.m, // magnitude
	complex.t  // argument
);

## Non-Static Methods ### Complex.prototype.toString([cartesian])

The toString method for the Complex class. Outputs to exponential or cartesian form.

Arguments

  • cartesian - An optional Boolean specifying the output form. If truthy, it outputs as cartesian, otherwise it outputs as exponential.
### Complex.prototype.add(complex)

Adds two Complex numbers.

Arguments

  • complex - An instance of the Complex class to add.
### Complex.prototype.sub(complex)

Subtracts a Complex number from another.

Arguments

  • complex - An instance of the Complex class to subtract.
### Complex.prototype.mult(complex)

Multiplies two Complex numbers.

Arguments

  • complex - An instance of the Complex class to multiply.
### Complex.prototype.divBy(complex)

Divides a Complex number from another.

Arguments

  • complex - An instance of the Complex class to divide by.
### Complex.prototype.pow(number)

Raises a Complex number to a real power.

Arguments

  • number - A Number to raise the Complex number to.
### Complex.prototype.cPow(complex)

Raises a Complex number to a Complex power.

Arguments

  • complex - An instance of the Complex class to raise by.
### Complex.prototype.mod(complex)

Applies a Complex Modulus to a Complex number by cartesian coordinates.

Arguments

  • complex - An instance of the Complex class for the modulus.

## Static Methods ### Complex.conj(complex)

Returns the conjugate of complex.

Arguments

  • complex - An instance of the Complex class to conjugate.
### Complex.neg(complex)

Returns the negative of complex.

Arguments

  • complex - An instance of the Complex class to negate.
### Complex.re(complex)

Returns the real component of complex as an instance of Complex. The real value is stored in the real component of the returned instance.

Arguments

  • complex - An instance of the Complex class.
### Complex.im(complex)

Returns the imaginary component of complex as an instance of Complex. The imaginary value is stored in the real component of the returned instance.

Arguments

  • complex - An instance of the Complex class.
### Complex.abs(complex)

Returns the absolute value of complex. The absolute value is stored in the real component of the returned instance.

Arguments

  • complex - An instance of the Complex class.
### Complex.arg(complex)

Returns the argument of complex. The argument is stored in the real component of the returned instance.

Arguments

  • complex - An instance of the Complex class.
### Complex.floor(complex)

Rounds down the cartesian components of complex.

Arguments

  • complex - An instance of the Complex class.
### Complex.ceil(complex)

Rounds up the cartesian components of complex.

Arguments

  • complex - An instance of the Complex class.
### Complex.round(complex)

Rounds the cartesian components of complex to the nearest integers.

Arguments

  • complex - An instance of the Complex class.
### Complex.fPart(complex)

Returns the fractional parts of the cartesian coordinates in complex.

Arguments

  • complex - An instance of the Complex class.

## Mathematical Static Methods ### Complex.exp(complex)

Returns the exponent function of complex, i.e. e^complex

Arguments

  • complex - An instance of the Complex class.
### Complex.log(complex)

Returns the natural logarithm of complex.

Arguments

  • complex - An instance of the Complex class.
### Complex.gamma(complex)

Returns the gamma function of complex.

Arguments

  • complex - An instance of the Complex class.
### Complex.fact(complex)

Returns the factorial of complex.

Arguments

  • complex - An instance of the Complex class.
### Complex.square(complex)

Returns the square of complex.

Arguments

  • complex - An instance of the Complex class.
### Complex.cube(complex)

Returns the cube of complex.

Arguments

  • complex - An instance of the Complex class.
### Complex.sqrt(complex)

Returns the square root of complex.

Arguments

  • complex - An instance of the Complex class.
### Complex.cbrt(complex)

Returns the cube root of complex.

Arguments

  • complex - An instance of the Complex class.
### Complex.cos(complex)

Returns the cosine of complex.

Arguments

  • complex - An instance of the Complex class.
### Complex.sin(complex)

Returns the sine of complex.

Arguments

  • complex - An instance of the Complex class.
### Complex.tan(complex)

Returns the tangent of complex.

Arguments

  • complex - An instance of the Complex class.
### Complex.sec(complex)

Returns the secant of complex.

Arguments

  • complex - An instance of the Complex class.
### Complex.csc(complex)

Returns the cosecant of complex.

Arguments

  • complex - An instance of the Complex class.
### Complex.cot(complex)

Returns the cotangent of complex.

Arguments

  • complex - An instance of the Complex class.
### Complex.arccos(complex)

Returns the arccosine of complex.

Arguments

  • complex - An instance of the Complex class.
### Complex.arcsin(complex)

Returns the arcsine of complex.

Arguments

  • complex - An instance of the Complex class.
### Complex.arctan(complex)

Returns the arctangent of complex.

Arguments

  • complex - An instance of the Complex class.
### Complex.arcsec(complex)

Returns the arcsecant of complex.

Arguments

  • complex - An instance of the Complex class.
### Complex.arccsc(complex)

Returns the arccosecant of complex.

Arguments

  • complex - An instance of the Complex class.
### Complex.arccot(complex)

Returns the arccotangent of complex.

Arguments

  • complex - An instance of the Complex class.
### Complex.cosh(complex)

Returns the hyperbolic cosine of complex.

Arguments

  • complex - An instance of the Complex class.
### Complex.sinh(complex)

Returns the hyperbolic sine of complex.

Arguments

  • complex - An instance of the Complex class.
### Complex.tanh(complex)

Returns the hyperbolic tangent of complex.

Arguments

  • complex - An instance of the Complex class.
### Complex.sech(complex)

Returns the hyperbolic secant of complex.

Arguments

  • complex - An instance of the Complex class.
### Complex.csch(complex)

Returns the hyperbolic cosecant of complex.

Arguments

  • complex - An instance of the Complex class.
### Complex.coth(complex)

Returns the hyperbolic cotangent of complex.

Arguments

  • complex - An instance of the Complex class.
### Complex.arccosh(complex)

Returns the hyperbolic arccosine of complex.

Arguments

  • complex - An instance of the Complex class.
### Complex.arcsinh(complex)

Returns the hyperbolic arcsine of complex.

Arguments

  • complex - An instance of the Complex class.
### Complex.arctanh(complex)

Returns the hyperbolic arctangent of complex.

Arguments

  • complex - An instance of the Complex class.
### Complex.arcsech(complex)

Returns the hyperbolic arcsecant of complex.

Arguments

  • complex - An instance of the Complex class.
### Complex.arccsch(complex)

Returns the hyperbolic arccosecant of complex.

Arguments

  • complex - An instance of the Complex class.
### Complex.arccoth(complex)

Returns the hyperbolic arccotangent of complex.

Arguments

  • complex - An instance of the Complex class.

## Misc. Static Methods ### Complex.min(complex_1[, complex_2...])

Returns the first complex instance with the smallest absolute value.

Arguments

  • complex_n - An instance of the Complex class.
### Complex.max(complex_1[, complex_2...])

Returns the first complex instance with the largest absolute value.

Arguments

  • complex_n - An instance of the Complex class.
### Complex.isNaN(complex)

Returns a Boolean; if any component of complex evaluates to NaN, this returns true, otherwise false.

Arguments

  • complex - An instance of the Complex class.
### Complex.isFinite(complex)

Returns a Boolean; if the absolute value of complex is finite, this returns true, otherwise false.

Arguments

  • complex - An instance of the Complex class.
### Complex.formatFunction(string)

Returns a sterilized human-readable expression that can be parsed by Complex.parseFunction if string is a valid math expression.

Arguments

  • string - A human-readable String of a math expression to be sterilized.
### Complex.parseFunction(string[, params[, skipFormat]])

Returns a JavaScript function bound with pre-compiled constants parsed from the human-readable math expression string. Optionally, an Array of human-readable parameters may be supplied to parse from the expression. Lastly, skipFormat is an optional Boolean that can be specified if string has already been formatted by Complex.formatFunction.

Arguments

  • string - A human-readable String of a math expression to be compiled.
  • params - An optional Array[String] of human-readable parameters to parse.
  • skipFormat - An optional Boolean to determine whether to skip pre-formatting.

About

JavaScript Complex class for Complex Math (The website provided is a particular application for this project)

Resources

License

Stars

Watchers

Forks

Packages

 
 
 

Contributors