function abs(arg0) { "use strict"; var name = 'abs'; if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature0(arg0); // signature: number } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: Complex if (arguments.length === 1) { return signature1(arg0); // signature: Complex } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test2(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature2(arg0); // signature: BigNumber } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test3(arg0)) { // type: Fraction if (arguments.length === 1) { return signature3(arg0); // signature: Fraction } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test4(arg0)) { // type: Unit if (arguments.length === 1) { return signature4(arg0); // signature: Unit } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test5(arg0)) { // type: Array if (arguments.length === 1) { return signature5(arg0); // signature: Array } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test6(arg0)) { // type: Matrix if (arguments.length === 1) { return signature5(arg0); // signature: Matrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test7(arg0)) { // type: string (convert to number) if (arguments.length === 1) { return signature0(convert0(arg0)); // signature: string } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test8(arg0)) { // type: boolean (convert to number) if (arguments.length === 1) { return signature0(convert1(arg0)); // signature: boolean } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test9(arg0)) { // type: null (convert to number) if (arguments.length === 1) { return signature0(convert2(arg0)); // signature: null } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'number,Complex,BigNumber,Fraction,Unit,Array,Matrix'); }
...
function factory (type, config, load, typed) {
/**
* Calculate the absolute value of a number. For matrices, the function is
* evaluated element wise.
*
* Syntax:
*
* math.abs(x)
*
* Examples:
*
* math.abs(3.5); // returns number 3.5
* math.abs(-4.2); // returns number 4.2
*
* math.abs([3, -5, -1, 0, 2]); // returns Array [3, 5, 1, 0, 2]
...
function acos(arg0) { "use strict"; var name = 'acos'; if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature0(arg0); // signature: number } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: Complex if (arguments.length === 1) { return signature1(arg0); // signature: Complex } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test2(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature2(arg0); // signature: BigNumber } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test3(arg0)) { // type: Array if (arguments.length === 1) { return signature3(arg0); // signature: Array } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test4(arg0)) { // type: Matrix if (arguments.length === 1) { return signature3(arg0); // signature: Matrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test5(arg0)) { // type: Fraction (convert to BigNumber) if (arguments.length === 1) { return signature2(convert0(arg0)); // signature: Fraction } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test6(arg0)) { // type: string (convert to number) if (arguments.length === 1) { return signature0(convert1(arg0)); // signature: string } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test7(arg0)) { // type: boolean (convert to number) if (arguments.length === 1) { return signature0(convert2(arg0)); // signature: boolean } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test8(arg0)) { // type: null (convert to number) if (arguments.length === 1) { return signature0(convert3(arg0)); // signature: null } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'number,Complex,BigNumber,Array,Matrix'); }
...
/**
* Calculate the inverse cosine of a value.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.acos(x)
*
* Examples:
*
* math.acos(0.5); // returns number 1.0471975511965979
* math.acos(math.cos(1.5)); // returns number 1.5
*
* math.acos(2); // returns Complex 0 + 1.3169578969248166 i
...
function acosh(arg0) { "use strict"; var name = 'acosh'; if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature0(arg0); // signature: number } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: Complex if (arguments.length === 1) { return signature1(arg0); // signature: Complex } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test2(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature2(arg0); // signature: BigNumber } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test3(arg0)) { // type: Array if (arguments.length === 1) { return signature3(arg0); // signature: Array } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test4(arg0)) { // type: Matrix if (arguments.length === 1) { return signature3(arg0); // signature: Matrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test5(arg0)) { // type: Fraction (convert to BigNumber) if (arguments.length === 1) { return signature2(convert0(arg0)); // signature: Fraction } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test6(arg0)) { // type: string (convert to number) if (arguments.length === 1) { return signature0(convert1(arg0)); // signature: string } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test7(arg0)) { // type: boolean (convert to number) if (arguments.length === 1) { return signature0(convert2(arg0)); // signature: boolean } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test8(arg0)) { // type: null (convert to number) if (arguments.length === 1) { return signature0(convert3(arg0)); // signature: null } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'number,Complex,BigNumber,Array,Matrix'); }
...
* Calculate the hyperbolic arccos of a value,
* defined as `acosh(x) = ln(sqrt(x^2 - 1) + x)`.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.acosh(x)
*
* Examples:
*
* math.acosh(1.5); // returns 0.9624236501192069
*
* See also:
*
...
function acot(arg0) { "use strict"; var name = 'acot'; if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature0(arg0); // signature: number } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: Complex if (arguments.length === 1) { return signature1(arg0); // signature: Complex } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test2(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature2(arg0); // signature: BigNumber } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test3(arg0)) { // type: Array if (arguments.length === 1) { return signature3(arg0); // signature: Array } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test4(arg0)) { // type: Matrix if (arguments.length === 1) { return signature3(arg0); // signature: Matrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test5(arg0)) { // type: Fraction (convert to BigNumber) if (arguments.length === 1) { return signature2(convert0(arg0)); // signature: Fraction } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test6(arg0)) { // type: string (convert to number) if (arguments.length === 1) { return signature0(convert1(arg0)); // signature: string } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test7(arg0)) { // type: boolean (convert to number) if (arguments.length === 1) { return signature0(convert2(arg0)); // signature: boolean } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test8(arg0)) { // type: null (convert to number) if (arguments.length === 1) { return signature0(convert3(arg0)); // signature: null } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'number,Complex,BigNumber,Array,Matrix'); }
...
/**
* Calculate the inverse cotangent of a value, defined as `acot(x) = atan(1/x)`.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.acot(x)
*
* Examples:
*
* math.acot(0.5); // returns number 0.4636476090008061
* math.acot(math.cot(1.5)); // returns number 1.5
*
* math.acot(2); // returns Complex 1.5707963267948966 -1.3169578969248166 i
...
function acoth(arg0) { "use strict"; var name = 'acoth'; if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature0(arg0); // signature: number } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: Complex if (arguments.length === 1) { return signature1(arg0); // signature: Complex } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test2(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature2(arg0); // signature: BigNumber } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test3(arg0)) { // type: Array if (arguments.length === 1) { return signature3(arg0); // signature: Array } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test4(arg0)) { // type: Matrix if (arguments.length === 1) { return signature3(arg0); // signature: Matrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test5(arg0)) { // type: Fraction (convert to BigNumber) if (arguments.length === 1) { return signature2(convert0(arg0)); // signature: Fraction } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test6(arg0)) { // type: string (convert to number) if (arguments.length === 1) { return signature0(convert1(arg0)); // signature: string } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test7(arg0)) { // type: boolean (convert to number) if (arguments.length === 1) { return signature0(convert2(arg0)); // signature: boolean } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test8(arg0)) { // type: null (convert to number) if (arguments.length === 1) { return signature0(convert3(arg0)); // signature: null } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'number,Complex,BigNumber,Array,Matrix'); }
...
* Calculate the hyperbolic arccotangent of a value,
* defined as `acoth(x) = atanh(1/x) = (ln((x+1)/x) + ln(x/(x-1))) / 2`.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.acoth(x)
*
* Examples:
*
* math.acoth(0.5); // returns 0.8047189562170503
*
* See also:
*
...
function acsc(arg0) { "use strict"; var name = 'acsc'; if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature0(arg0); // signature: number } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: Complex if (arguments.length === 1) { return signature1(arg0); // signature: Complex } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test2(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature2(arg0); // signature: BigNumber } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test3(arg0)) { // type: Array if (arguments.length === 1) { return signature3(arg0); // signature: Array } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test4(arg0)) { // type: Matrix if (arguments.length === 1) { return signature3(arg0); // signature: Matrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test5(arg0)) { // type: Fraction (convert to BigNumber) if (arguments.length === 1) { return signature2(convert0(arg0)); // signature: Fraction } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test6(arg0)) { // type: string (convert to number) if (arguments.length === 1) { return signature0(convert1(arg0)); // signature: string } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test7(arg0)) { // type: boolean (convert to number) if (arguments.length === 1) { return signature0(convert2(arg0)); // signature: boolean } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test8(arg0)) { // type: null (convert to number) if (arguments.length === 1) { return signature0(convert3(arg0)); // signature: null } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'number,Complex,BigNumber,Array,Matrix'); }
...
/**
* Calculate the inverse cosecant of a value, defined as `acsc(x) = asin(1/x)`.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.acsc(x)
*
* Examples:
*
* math.acsc(0.5); // returns number 0.5235987755982989
* math.acsc(math.csc(1.5)); // returns number ~1.5
*
* math.acsc(2); // returns Complex 1.5707963267948966 -1.3169578969248166 i
...
function acsch(arg0) { "use strict"; var name = 'acsch'; if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature0(arg0); // signature: number } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: Complex if (arguments.length === 1) { return signature1(arg0); // signature: Complex } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test2(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature2(arg0); // signature: BigNumber } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test3(arg0)) { // type: Array if (arguments.length === 1) { return signature3(arg0); // signature: Array } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test4(arg0)) { // type: Matrix if (arguments.length === 1) { return signature3(arg0); // signature: Matrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test5(arg0)) { // type: Fraction (convert to BigNumber) if (arguments.length === 1) { return signature2(convert0(arg0)); // signature: Fraction } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test6(arg0)) { // type: string (convert to number) if (arguments.length === 1) { return signature0(convert1(arg0)); // signature: string } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test7(arg0)) { // type: boolean (convert to number) if (arguments.length === 1) { return signature0(convert2(arg0)); // signature: boolean } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test8(arg0)) { // type: null (convert to number) if (arguments.length === 1) { return signature0(convert3(arg0)); // signature: null } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'number,Complex,BigNumber,Array,Matrix'); }
...
* Calculate the hyperbolic arccosecant of a value,
* defined as `acsch(x) = asinh(1/x) = ln(1/x + sqrt(1/x^2 + 1))`.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.acsch(x)
*
* Examples:
*
* math.acsch(0.5); // returns 1.4436354751788103
*
* See also:
*
...
function add(arg0, arg1, arg2) { "use strict"; var name = 'add'; if (test0(arg0)) { // type: number if (test0(arg1)) { // type: number if (arguments.length === 2) { return signature0(arg0, arg1); // signature: number, number } } if (test1(arg1)) { // type: Complex if (arguments.length === 2) { return signature1(convert0(arg0), arg1); // signature: number, Complex } } if (test2(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature2(convert1(arg0), arg1); // signature: number, BigNumber } } if (test3(arg1)) { // type: Fraction if (arguments.length === 2) { return signature3(convert2(arg0), arg1); // signature: number, Fraction } } if (test4(arg1)) { // type: string (convert to number) if (arguments.length === 2) { return signature0(arg0, convert3(arg1)); // signature: number, string } } if (test5(arg1)) { // type: boolean (convert to number) if (arguments.length === 2) { return signature0(arg0, convert4(arg1)); // signature: number, boolean } } if (test6(arg1)) { // type: null (convert to number) if (arguments.length === 2) { return signature0(arg0, convert5(arg1)); // signature: number, null } } } if (test1(arg0)) { // type: Complex if (test1(arg1)) { // type: Complex if (arguments.length === 2) { return signature1(arg0, arg1); // signature: Complex, Complex } } if (test0(arg1)) { // type: number (convert to Complex) if (arguments.length === 2) { return signature1(arg0, convert0(arg1)); // signature: Complex, number } } if (test2(arg1)) { // type: BigNumber (convert to Complex) if (arguments.length === 2) { return signature1(arg0, convert6(arg1)); // signature: Complex, BigNumber } } if (test3(arg1)) { // type: Fraction (convert to Complex) if (arguments.length === 2) { return signature1(arg0, convert7(arg1)); // signature: Complex, Fraction } } if (test4(arg1)) { // type: string (convert to Complex) if (arguments.length === 2) { return signature1(arg0, convert8(arg1)); // signature: Complex, string } } } if (test2(arg0)) { // type: BigNumber if (test1(arg1)) { // type: Complex if (arguments.length === 2) { return signature1(convert6(arg0), arg1); // signature: BigNumber, Complex } } if (test2(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature2(arg0, arg1); // signature: BigNumber, BigNumber } } if (test0(arg1)) { // type: number (convert to BigNumber) if (arguments.length === 2) { return signature2(arg0, convert1(arg1)); // signature: BigNumber, number } } if (test3(arg1)) { // type: Fraction (convert to BigNumber) if (arguments.length === 2) { return signature2(arg0, convert9(arg1)); // signature: BigNumber, Fraction } } if (test4(arg1)) { // type: string (convert to BigNumber) if (arguments.length === 2) { return signature2(arg0, convert10(arg1)); // signature: BigNumber, string } } if (test5(arg1)) { // type: boolean (convert to BigNumber) if (arguments.length === 2) { return signature2(arg0, convert11(arg1)); // signature: BigNumber, boolean } } if (test6(arg1)) { // type: null (convert to BigNumber) if (arguments.length === 2) { return signature2(arg0, convert12(arg1)); // signature: BigNumber, null } } } if (test3(arg0)) { // type: Fraction if (test1(arg1)) { // type: Complex if (arguments.length === 2) { return signature1(convert7(arg0), arg1); // signature: Fraction, Complex } } if (test2(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature2(convert9(arg0), arg1); // signature: Fraction, BigNumber } } if (test3(arg1)) { // type: Fraction if (a ...
...
math.eval('5.08 cm to inch'); // 2 inch
math.eval('sin(45 deg) ^ 2'); // 0.5
math.eval('9 / 3 + 2i'); // 3 + 2i
math.eval('det([-1, 2; 3, 1])'); // -7
// chaining
math.chain(3)
.add(4)
.multiply(2)
.done(); // 14
```
## Browser support
Math.js works on any ES5 compatible JavaScript engine: node.js 0.10, and Internet Explorer 9 and newer, and all other browsers (
Chrome, Firefox, Safari). If support for old browsers like Internet Explorer 8 is required, the [es5-shim](https://github.com/kriskowal
/es5-shim) library has to be loaded.
...
function and(arg0, arg1) { "use strict"; var name = 'and'; if (test0(arg0)) { // type: number if (test0(arg1)) { // type: number if (arguments.length === 2) { return signature0(arg0, arg1); // signature: number, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test1(arg1)) { // type: Complex if (arguments.length === 2) { return signature1(convert0(arg0), arg1); // signature: number, Complex } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature2(convert1(arg0), arg1); // signature: number, BigNumber } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: Fraction (convert to BigNumber) if (arguments.length === 2) { return signature2(convert1(arg0), convert2(arg1)); // signature: number, Fraction } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test4(arg1)) { // type: string (convert to number) if (arguments.length === 2) { return signature0(arg0, convert3(arg1)); // signature: number, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test5(arg1)) { // type: boolean (convert to number) if (arguments.length === 2) { return signature0(arg0, convert4(arg1)); // signature: number, boolean } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test6(arg1)) { // type: null (convert to number) if (arguments.length === 2) { return signature0(arg0, convert5(arg1)); // signature: number, null } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } } if (test1(arg0)) { // type: Complex if (test1(arg1)) { // type: Complex if (arguments.length === 2) { return signature1(arg0, arg1); // signature: Complex, Complex } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test0(arg1)) { // type: number (convert to Complex) if (arguments.length === 2) { return signature1(arg0, convert0(arg1)); // signature: Complex, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: BigNumber (convert to Complex) if (arguments.length === 2) { return signature1(arg0, convert6(arg1)); // signature: Complex, BigNumber } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: Fraction (convert to Complex) if (arguments.length === 2) { return signature1(arg0, convert7(arg1)); // signature: Complex, Fraction } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test4(arg1)) { // type: string (convert to Complex) if (arguments.length === 2) { return signature1(arg0, convert8(arg1)); // signature: Complex, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } } if (test2(arg0)) { // type: BigNumber if (test1(arg1)) { // type: Complex if (arguments.length === 2) { return signature1(convert6(arg0), arg1); // signature: BigNumber, Complex } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature2(arg0, arg1); // ...
...
/**
* Logical `and`. Test whether two values are both defined with a nonzero/nonempty value.
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.and(x, y)
*
* Examples:
*
* math.and(2, 4); // returns true
*
* a = [2, 0, 0];
* b = [3, 7, 0];
...
function arg(arg0) { "use strict"; var name = 'arg'; if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature0(arg0); // signature: number } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: Complex if (arguments.length === 1) { return signature1(arg0); // signature: Complex } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test2(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature2(arg0); // signature: BigNumber } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test3(arg0)) { // type: Array if (arguments.length === 1) { return signature3(arg0); // signature: Array } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test4(arg0)) { // type: Matrix if (arguments.length === 1) { return signature3(arg0); // signature: Matrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test5(arg0)) { // type: Fraction (convert to BigNumber) if (arguments.length === 1) { return signature2(convert0(arg0)); // signature: Fraction } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test6(arg0)) { // type: string (convert to number) if (arguments.length === 1) { return signature0(convert1(arg0)); // signature: string } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test7(arg0)) { // type: boolean (convert to number) if (arguments.length === 1) { return signature0(convert2(arg0)); // signature: boolean } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test8(arg0)) { // type: null (convert to number) if (arguments.length === 1) { return signature0(convert3(arg0)); // signature: null } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'number,Complex,BigNumber,Array,Matrix'); }
...
* the principal root is returned.
* @returns {Complex | Array.<Complex> | Matrix.<Complex>} Returns the cubic root(s) of x
* @private
*/
function _cbrtComplex(x, allRoots) {
// https://www.wikiwand.com/en/Cube_root#/Complex_numbers
var arg_3 = x.arg() / 3;
var abs = x.abs();
// principal root:
var principal = new type.Complex(_cbrtNumber(abs), 0).mul(
new type.Complex(0, arg_3).exp());
if (allRoots) {
...
function asec(arg0) { "use strict"; var name = 'asec'; if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature0(arg0); // signature: number } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: Complex if (arguments.length === 1) { return signature1(arg0); // signature: Complex } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test2(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature2(arg0); // signature: BigNumber } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test3(arg0)) { // type: Array if (arguments.length === 1) { return signature3(arg0); // signature: Array } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test4(arg0)) { // type: Matrix if (arguments.length === 1) { return signature3(arg0); // signature: Matrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test5(arg0)) { // type: Fraction (convert to BigNumber) if (arguments.length === 1) { return signature2(convert0(arg0)); // signature: Fraction } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test6(arg0)) { // type: string (convert to number) if (arguments.length === 1) { return signature0(convert1(arg0)); // signature: string } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test7(arg0)) { // type: boolean (convert to number) if (arguments.length === 1) { return signature0(convert2(arg0)); // signature: boolean } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test8(arg0)) { // type: null (convert to number) if (arguments.length === 1) { return signature0(convert3(arg0)); // signature: null } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'number,Complex,BigNumber,Array,Matrix'); }
...
/**
* Calculate the inverse secant of a value. Defined as `asec(x) = acos(1/x)`.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.asec(x)
*
* Examples:
*
* math.asec(0.5); // returns 1.0471975511965979
* math.asec(math.sec(1.5)); // returns 1.5
*
* math.asec(2); // returns 0 + 1.3169578969248166 i
...
function asech(arg0) { "use strict"; var name = 'asech'; if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature0(arg0); // signature: number } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: Complex if (arguments.length === 1) { return signature1(arg0); // signature: Complex } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test2(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature2(arg0); // signature: BigNumber } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test3(arg0)) { // type: Array if (arguments.length === 1) { return signature3(arg0); // signature: Array } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test4(arg0)) { // type: Matrix if (arguments.length === 1) { return signature3(arg0); // signature: Matrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test5(arg0)) { // type: Fraction (convert to BigNumber) if (arguments.length === 1) { return signature2(convert0(arg0)); // signature: Fraction } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test6(arg0)) { // type: string (convert to number) if (arguments.length === 1) { return signature0(convert1(arg0)); // signature: string } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test7(arg0)) { // type: boolean (convert to number) if (arguments.length === 1) { return signature0(convert2(arg0)); // signature: boolean } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test8(arg0)) { // type: null (convert to number) if (arguments.length === 1) { return signature0(convert3(arg0)); // signature: null } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'number,Complex,BigNumber,Array,Matrix'); }
...
* Calculate the hyperbolic arcsecant of a value,
* defined as `asech(x) = acosh(1/x) = ln(sqrt(1/x^2 - 1) + 1/x)`.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.asech(x)
*
* Examples:
*
* math.asech(0.5); // returns 1.3169578969248166
*
* See also:
*
...
function asin(arg0) { "use strict"; var name = 'asin'; if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature0(arg0); // signature: number } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: Complex if (arguments.length === 1) { return signature1(arg0); // signature: Complex } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test2(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature2(arg0); // signature: BigNumber } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test3(arg0)) { // type: Array if (arguments.length === 1) { return signature3(arg0); // signature: Array } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test4(arg0)) { // type: Matrix if (arguments.length === 1) { return signature3(arg0); // signature: Matrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test5(arg0)) { // type: Fraction (convert to BigNumber) if (arguments.length === 1) { return signature2(convert0(arg0)); // signature: Fraction } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test6(arg0)) { // type: string (convert to number) if (arguments.length === 1) { return signature0(convert1(arg0)); // signature: string } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test7(arg0)) { // type: boolean (convert to number) if (arguments.length === 1) { return signature0(convert2(arg0)); // signature: boolean } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test8(arg0)) { // type: null (convert to number) if (arguments.length === 1) { return signature0(convert3(arg0)); // signature: null } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'number,Complex,BigNumber,Array,Matrix'); }
...
*
* @param {number | Complex | Array | Matrix} x Function input
* @return {number | Complex | Array | Matrix} The arc cosecant of x
*/
var acsc = typed('acsc', {
'number': function (x) {
if (x <= -1 || x >= 1 || config.predictable) {
return Math.asin(1 / x);
}
return new type.Complex(x, 0).acsc();
},
'Complex': function (x) {
return x.acsc();
},
...
function asinh(arg0) { "use strict"; var name = 'asinh'; if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature0(arg0); // signature: number } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: Complex if (arguments.length === 1) { return signature1(arg0); // signature: Complex } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test2(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature2(arg0); // signature: BigNumber } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test3(arg0)) { // type: Array if (arguments.length === 1) { return signature3(arg0); // signature: Array } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test4(arg0)) { // type: Matrix if (arguments.length === 1) { return signature3(arg0); // signature: Matrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test5(arg0)) { // type: Fraction (convert to BigNumber) if (arguments.length === 1) { return signature2(convert0(arg0)); // signature: Fraction } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test6(arg0)) { // type: string (convert to number) if (arguments.length === 1) { return signature0(convert1(arg0)); // signature: string } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test7(arg0)) { // type: boolean (convert to number) if (arguments.length === 1) { return signature0(convert2(arg0)); // signature: boolean } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test8(arg0)) { // type: null (convert to number) if (arguments.length === 1) { return signature0(convert3(arg0)); // signature: null } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'number,Complex,BigNumber,Array,Matrix'); }
...
},
'Complex': function (x) {
return x.acsch();
},
'BigNumber': function (x) {
return new type.BigNumber(1).div(x).asinh();
},
'Array | Matrix': function (x) {
return deepMap(x, acsch);
}
});
...
function atan(arg0) { "use strict"; var name = 'atan'; if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature0(arg0); // signature: number } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: Complex if (arguments.length === 1) { return signature1(arg0); // signature: Complex } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test2(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature2(arg0); // signature: BigNumber } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test3(arg0)) { // type: Array if (arguments.length === 1) { return signature3(arg0); // signature: Array } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test4(arg0)) { // type: Matrix if (arguments.length === 1) { return signature3(arg0); // signature: Matrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test5(arg0)) { // type: Fraction (convert to BigNumber) if (arguments.length === 1) { return signature2(convert0(arg0)); // signature: Fraction } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test6(arg0)) { // type: string (convert to number) if (arguments.length === 1) { return signature0(convert1(arg0)); // signature: string } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test7(arg0)) { // type: boolean (convert to number) if (arguments.length === 1) { return signature0(convert2(arg0)); // signature: boolean } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test8(arg0)) { // type: null (convert to number) if (arguments.length === 1) { return signature0(convert3(arg0)); // signature: null } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'number,Complex,BigNumber,Array,Matrix'); }
...
* cot, atan
*
* @param {number | Complex | Array | Matrix} x Function input
* @return {number | Complex | Array | Matrix} The arc cotangent of x
*/
var acot = typed('acot', {
'number': function (x) {
return Math.atan(1 / x);
},
'Complex': function (x) {
return x.acot();
},
'BigNumber': function (x) {
...
function atan2(arg0, arg1) { "use strict"; var name = 'atan2'; if (test0(arg0)) { // type: number if (test0(arg1)) { // type: number if (arguments.length === 2) { return signature0(arg0, arg1); // signature: number, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test1(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature1(convert0(arg0), arg1); // signature: number, BigNumber } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: Array if (arguments.length === 2) { return signature2(arg0, arg1); // signature: number, Array } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: Matrix if (arguments.length === 2) { return signature3(arg0, arg1); // signature: number, Matrix } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test4(arg1)) { // type: Fraction (convert to BigNumber) if (arguments.length === 2) { return signature1(convert0(arg0), convert1(arg1)); // signature: number, Fraction } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test5(arg1)) { // type: string (convert to number) if (arguments.length === 2) { return signature0(arg0, convert2(arg1)); // signature: number, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test6(arg1)) { // type: boolean (convert to number) if (arguments.length === 2) { return signature0(arg0, convert3(arg1)); // signature: number, boolean } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test7(arg1)) { // type: null (convert to number) if (arguments.length === 2) { return signature0(arg0, convert4(arg1)); // signature: number, null } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'number,BigNumber,Array,Matrix'); } if (test1(arg0)) { // type: BigNumber if (test1(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature1(arg0, arg1); // signature: BigNumber, BigNumber } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: Array if (arguments.length === 2) { return signature2(arg0, arg1); // signature: BigNumber, Array } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: Matrix if (arguments.length === 2) { return signature3(arg0, arg1); // signature: BigNumber, Matrix } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test0(arg1)) { // type: number (convert to BigNumber) if (arguments.length === 2) { return signature1(arg0, convert0(arg1)); // signature: BigNumber, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test4(arg1)) { // type: Fraction (convert to BigNumber) if (arguments.length === 2) { return signature1(arg0, convert1(arg1)); // signature: BigNumber, Fraction } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test5(arg1)) { // type: string (convert to BigNumber) if (arguments.length === 2) { return signature1(arg0, convert5(arg ...
...
```js
// load math.js
var math = require('mathjs');
// functions and constants
math.round(math.e, 3); // 2.718
math.atan2(3, -3) / math.pi; // 0.75
math.log(1000, 10); // 3
math.sqrt(-4); // 2i
math.pow([[-1, 2], [3, 1]], 2); // [[7, 0], [0, 7]]
math.derivative('x^2 + x', 'x'); // 2 * x + 1
// expressions
math.eval('12 / (2.3 + 0.7)'); // 4
...
function atanh(arg0) { "use strict"; var name = 'atanh'; if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature0(arg0); // signature: number } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: Complex if (arguments.length === 1) { return signature1(arg0); // signature: Complex } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test2(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature2(arg0); // signature: BigNumber } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test3(arg0)) { // type: Array if (arguments.length === 1) { return signature3(arg0); // signature: Array } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test4(arg0)) { // type: Matrix if (arguments.length === 1) { return signature3(arg0); // signature: Matrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test5(arg0)) { // type: Fraction (convert to BigNumber) if (arguments.length === 1) { return signature2(convert0(arg0)); // signature: Fraction } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test6(arg0)) { // type: string (convert to number) if (arguments.length === 1) { return signature0(convert1(arg0)); // signature: string } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test7(arg0)) { // type: boolean (convert to number) if (arguments.length === 1) { return signature0(convert2(arg0)); // signature: boolean } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test8(arg0)) { // type: null (convert to number) if (arguments.length === 1) { return signature0(convert3(arg0)); // signature: null } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'number,Complex,BigNumber,Array,Matrix'); }
...
},
'Complex': function (x) {
return x.acoth();
},
'BigNumber': function (x) {
return new type.BigNumber(1).div(x).atanh();
},
'Array | Matrix': function (x) {
return deepMap(x, acoth);
}
});
...
function bellNumbers(arg0) { "use strict"; var name = 'bellNumbers'; if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature0(arg0); // signature: number } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature0(arg0); // signature: BigNumber } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test2(arg0)) { // type: Fraction (convert to BigNumber) if (arguments.length === 1) { return signature0(convert0(arg0)); // signature: Fraction } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test3(arg0)) { // type: string (convert to number) if (arguments.length === 1) { return signature0(convert1(arg0)); // signature: string } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test4(arg0)) { // type: boolean (convert to number) if (arguments.length === 1) { return signature0(convert2(arg0)); // signature: boolean } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test5(arg0)) { // type: null (convert to number) if (arguments.length === 1) { return signature0(convert3(arg0)); // signature: null } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'number,BigNumber'); }
...
/**
* The Bell Numbers count the number of partitions of a set. A partition is a pairwise disjoint subset of S whose union is S.
* bellNumbers only takes integer arguments.
* The following condition must be enforced: n >= 0
*
* Syntax:
*
* math.bellNumbers(n)
*
* Examples:
*
* math.bellNumbers(3); // returns 5;
* math.bellNumbers(8); // returns 4140;
*
* See also:
...
function bignumber(arg0) { "use strict"; var name = 'bignumber'; if (arguments.length === 0) { return signature0(); // signature: } if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature1(arg0); // signature: number } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature2(arg0); // signature: BigNumber } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test2(arg0)) { // type: Fraction if (arguments.length === 1) { return signature3(arg0); // signature: Fraction } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test3(arg0)) { // type: string if (arguments.length === 1) { return signature4(arg0); // signature: string } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test4(arg0)) { // type: Array if (arguments.length === 1) { return signature5(arg0); // signature: Array } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test5(arg0)) { // type: Matrix if (arguments.length === 1) { return signature5(arg0); // signature: Matrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test6(arg0)) { // type: boolean (convert to number) if (arguments.length === 1) { return signature1(convert0(arg0)); // signature: boolean } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test7(arg0)) { // type: null (convert to number) if (arguments.length === 1) { return signature1(convert1(arg0)); // signature: null } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'number,BigNumber,Fraction,string,Array,Matrix'); }
...
*/
ConstantNode.prototype._compile = function (defs, args) {
switch (this.valueType) {
case 'number':
// TODO: replace this with using config.number
var numConfig = defs.math.config().number;
if (numConfig === 'BigNumber') {
return 'math.bignumber("' + this.value + '")';
}
else if (numConfig === 'Fraction') {
return 'math.fraction("' + this.value + '")';
}
else {
// remove leading zeros like '003.2' which are not allowed by JavaScript
return this.value.replace(/^(0*)[0-9]/, function (match, zeros) {
...
function bitAnd(arg0, arg1) { "use strict"; var name = 'bitAnd'; if (test0(arg0)) { // type: number if (test0(arg1)) { // type: number if (arguments.length === 2) { return signature0(arg0, arg1); // signature: number, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test1(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature1(convert0(arg0), arg1); // signature: number, BigNumber } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: Fraction (convert to BigNumber) if (arguments.length === 2) { return signature1(convert0(arg0), convert1(arg1)); // signature: number, Fraction } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: string (convert to number) if (arguments.length === 2) { return signature0(arg0, convert2(arg1)); // signature: number, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test4(arg1)) { // type: boolean (convert to number) if (arguments.length === 2) { return signature0(arg0, convert3(arg1)); // signature: number, boolean } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test5(arg1)) { // type: null (convert to number) if (arguments.length === 2) { return signature0(arg0, convert4(arg1)); // signature: number, null } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } } if (test1(arg0)) { // type: BigNumber if (test1(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature1(arg0, arg1); // signature: BigNumber, BigNumber } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test0(arg1)) { // type: number (convert to BigNumber) if (arguments.length === 2) { return signature1(arg0, convert0(arg1)); // signature: BigNumber, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: Fraction (convert to BigNumber) if (arguments.length === 2) { return signature1(arg0, convert1(arg1)); // signature: BigNumber, Fraction } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: string (convert to BigNumber) if (arguments.length === 2) { return signature1(arg0, convert5(arg1)); // signature: BigNumber, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test4(arg1)) { // type: boolean (convert to BigNumber) if (arguments.length === 2) { return signature1(arg0, convert6(arg1)); // signature: BigNumber, boolean } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test5(arg1)) { // type: null (convert to BigNumber) if (arguments.length === 2) { return signature1(arg0, convert7(arg1)); // signature: BigNumber, null } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } } if (test6(arg0)) { // type: Array if (test6(arg1)) { // type: Array if (arguments.length === 2) { return signature2(arg0, arg1); // signature: Array, Array } } if (test7(arg1)) { // type: Matrix if (arguments.length === 2) { return signature3(arg0, arg1); // signature: Array, Matrix } } // type: any if (arguments.length === 2) { ...
...
/**
* Bitwise AND two values, `x & y`.
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.bitAnd(x, y)
*
* Examples:
*
* math.bitAnd(53, 131); // returns number 1
*
* math.bitAnd([1, 12, 31], 42); // returns Array [0, 8, 10]
*
...
function bitNot(arg0) { "use strict"; var name = 'bitNot'; if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature0(arg0); // signature: number } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature1(arg0); // signature: BigNumber } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test2(arg0)) { // type: Array if (arguments.length === 1) { return signature2(arg0); // signature: Array } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test3(arg0)) { // type: Matrix if (arguments.length === 1) { return signature2(arg0); // signature: Matrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test4(arg0)) { // type: Fraction (convert to BigNumber) if (arguments.length === 1) { return signature1(convert0(arg0)); // signature: Fraction } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test5(arg0)) { // type: string (convert to number) if (arguments.length === 1) { return signature0(convert1(arg0)); // signature: string } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test6(arg0)) { // type: boolean (convert to number) if (arguments.length === 1) { return signature0(convert2(arg0)); // signature: boolean } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test7(arg0)) { // type: null (convert to number) if (arguments.length === 1) { return signature0(convert3(arg0)); // signature: null } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'number,BigNumber,Array,Matrix'); }
...
/**
* Bitwise NOT value, `~x`.
* For matrices, the function is evaluated element wise.
* For units, the function is evaluated on the best prefix base.
*
* Syntax:
*
* math.bitNot(x)
*
* Examples:
*
* math.bitNot(1); // returns number -2
*
* math.bitNot([2, -3, 4]); // returns Array [-3, 2, 5]
*
...
function bitOr(arg0, arg1) { "use strict"; var name = 'bitOr'; if (test0(arg0)) { // type: number if (test0(arg1)) { // type: number if (arguments.length === 2) { return signature0(arg0, arg1); // signature: number, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test1(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature1(convert0(arg0), arg1); // signature: number, BigNumber } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: Fraction (convert to BigNumber) if (arguments.length === 2) { return signature1(convert0(arg0), convert1(arg1)); // signature: number, Fraction } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: string (convert to number) if (arguments.length === 2) { return signature0(arg0, convert2(arg1)); // signature: number, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test4(arg1)) { // type: boolean (convert to number) if (arguments.length === 2) { return signature0(arg0, convert3(arg1)); // signature: number, boolean } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test5(arg1)) { // type: null (convert to number) if (arguments.length === 2) { return signature0(arg0, convert4(arg1)); // signature: number, null } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } } if (test1(arg0)) { // type: BigNumber if (test1(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature1(arg0, arg1); // signature: BigNumber, BigNumber } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test0(arg1)) { // type: number (convert to BigNumber) if (arguments.length === 2) { return signature1(arg0, convert0(arg1)); // signature: BigNumber, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: Fraction (convert to BigNumber) if (arguments.length === 2) { return signature1(arg0, convert1(arg1)); // signature: BigNumber, Fraction } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: string (convert to BigNumber) if (arguments.length === 2) { return signature1(arg0, convert5(arg1)); // signature: BigNumber, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test4(arg1)) { // type: boolean (convert to BigNumber) if (arguments.length === 2) { return signature1(arg0, convert6(arg1)); // signature: BigNumber, boolean } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test5(arg1)) { // type: null (convert to BigNumber) if (arguments.length === 2) { return signature1(arg0, convert7(arg1)); // signature: BigNumber, null } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } } if (test6(arg0)) { // type: Array if (test6(arg1)) { // type: Array if (arguments.length === 2) { return signature2(arg0, arg1); // signature: Array, Array } } if (test7(arg1)) { // type: Matrix if (arguments.length === 2) { return signature3(arg0, arg1); // signature: Array, Matrix } } // type: any if (arguments.length === 2) { ...
...
/**
* Bitwise OR two values, `x | y`.
* For matrices, the function is evaluated element wise.
* For units, the function is evaluated on the lowest print base.
*
* Syntax:
*
* math.bitOr(x, y)
*
* Examples:
*
* math.bitOr(1, 2); // returns number 3
*
* math.bitOr([1, 2, 3], 4); // returns Array [5, 6, 7]
*
...
function bitXor(arg0, arg1) { "use strict"; var name = 'bitXor'; if (test0(arg0)) { // type: number if (test0(arg1)) { // type: number if (arguments.length === 2) { return signature0(arg0, arg1); // signature: number, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test1(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature1(convert0(arg0), arg1); // signature: number, BigNumber } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: Fraction (convert to BigNumber) if (arguments.length === 2) { return signature1(convert0(arg0), convert1(arg1)); // signature: number, Fraction } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: string (convert to number) if (arguments.length === 2) { return signature0(arg0, convert2(arg1)); // signature: number, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test4(arg1)) { // type: boolean (convert to number) if (arguments.length === 2) { return signature0(arg0, convert3(arg1)); // signature: number, boolean } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test5(arg1)) { // type: null (convert to number) if (arguments.length === 2) { return signature0(arg0, convert4(arg1)); // signature: number, null } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } } if (test1(arg0)) { // type: BigNumber if (test1(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature1(arg0, arg1); // signature: BigNumber, BigNumber } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test0(arg1)) { // type: number (convert to BigNumber) if (arguments.length === 2) { return signature1(arg0, convert0(arg1)); // signature: BigNumber, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: Fraction (convert to BigNumber) if (arguments.length === 2) { return signature1(arg0, convert1(arg1)); // signature: BigNumber, Fraction } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: string (convert to BigNumber) if (arguments.length === 2) { return signature1(arg0, convert5(arg1)); // signature: BigNumber, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test4(arg1)) { // type: boolean (convert to BigNumber) if (arguments.length === 2) { return signature1(arg0, convert6(arg1)); // signature: BigNumber, boolean } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test5(arg1)) { // type: null (convert to BigNumber) if (arguments.length === 2) { return signature1(arg0, convert7(arg1)); // signature: BigNumber, null } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } } if (test6(arg0)) { // type: Array if (test6(arg1)) { // type: Array if (arguments.length === 2) { return signature2(arg0, arg1); // signature: Array, Array } } if (test7(arg1)) { // type: Matrix if (arguments.length === 2) { return signature3(arg0, arg1); // signature: Array, Matrix } } // type: any if (arguments.length === 2) { ...
...
/**
* Bitwise XOR two values, `x ^ y`.
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.bitXor(x, y)
*
* Examples:
*
* math.bitXor(1, 2); // returns number 3
*
* math.bitXor([2, 3, 4], 4); // returns Array [6, 7, 0]
*
...
function bool(arg0) { "use strict"; var name = 'bool'; if (arguments.length === 0) { return signature0(); // signature: } if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature1(arg0); // signature: number } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature2(arg0); // signature: BigNumber } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test2(arg0)) { // type: string if (arguments.length === 1) { return signature3(arg0); // signature: string } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test3(arg0)) { // type: Array if (arguments.length === 1) { return signature4(arg0); // signature: Array } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test4(arg0)) { // type: Matrix if (arguments.length === 1) { return signature4(arg0); // signature: Matrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test5(arg0)) { // type: boolean if (arguments.length === 1) { return signature5(arg0); // signature: boolean } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test6(arg0)) { // type: Fraction (convert to BigNumber) if (arguments.length === 1) { return signature2(convert0(arg0)); // signature: Fraction } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test7(arg0)) { // type: null (convert to number) if (arguments.length === 1) { return signature1(convert1(arg0)); // signature: null } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'number,BigNumber,string,Array,Matrix,boolean'); }
...
* In case of a number, `true` is returned for non-zero numbers, and `false` in
* case of zero.
* Strings can be `'true'` or `'false'`, or can contain a number.
* When value is a matrix, all elements will be converted to boolean.
*
* Syntax:
*
* math.boolean(x)
*
* Examples:
*
* math.boolean(0); // returns false
* math.boolean(1); // returns true
* math.boolean(-3); // returns true
* math.boolean('true'); // returns true
...
function catalan(arg0) { "use strict"; var name = 'catalan'; if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature0(arg0); // signature: number } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature0(arg0); // signature: BigNumber } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test2(arg0)) { // type: Fraction (convert to BigNumber) if (arguments.length === 1) { return signature0(convert0(arg0)); // signature: Fraction } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test3(arg0)) { // type: string (convert to number) if (arguments.length === 1) { return signature0(convert1(arg0)); // signature: string } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test4(arg0)) { // type: boolean (convert to number) if (arguments.length === 1) { return signature0(convert2(arg0)); // signature: boolean } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test5(arg0)) { // type: null (convert to number) if (arguments.length === 1) { return signature0(convert3(arg0)); // signature: null } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'number,BigNumber'); }
...
/**
* The Catalan Numbers enumerate combinatorial structures of many different types.
* catalan only takes integer arguments.
* The following condition must be enforced: n >= 0
*
* Syntax:
*
* math.catalan(n)
*
* Examples:
*
* math.catalan(3); // returns 5;
* math.catalan(8); // returns 1430;
*
* See also:
...
function cbrt(arg0, arg1) { "use strict"; var name = 'cbrt'; if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature0(arg0); // signature: number } if (test1(arg1)) { // type: boolean if (arguments.length === 2) { return signature1(convert0(arg0), arg1); // signature: number, boolean } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'boolean'); } if (test2(arg0)) { // type: Complex if (arguments.length === 1) { return signature1(arg0); // signature: Complex } if (test1(arg1)) { // type: boolean if (arguments.length === 2) { return signature1(arg0, arg1); // signature: Complex, boolean } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'boolean'); } if (test3(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature2(arg0); // signature: BigNumber } if (test1(arg1)) { // type: boolean if (arguments.length === 2) { return signature1(convert1(arg0), arg1); // signature: BigNumber, boolean } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'boolean'); } if (test4(arg0)) { // type: Unit if (arguments.length === 1) { return signature3(arg0); // signature: Unit } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test5(arg0)) { // type: Array if (arguments.length === 1) { return signature4(arg0); // signature: Array } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test6(arg0)) { // type: Matrix if (arguments.length === 1) { return signature4(arg0); // signature: Matrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test7(arg0)) { // type: Fraction (convert to BigNumber) if (arguments.length === 1) { return signature2(convert2(arg0)); // signature: Fraction } if (test1(arg1)) { // type: boolean if (arguments.length === 2) { return signature1(convert3(arg0), arg1); // signature: Fraction, boolean } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'boolean'); } if (test8(arg0)) { // type: string (convert to number) if (arguments.length === 1) { return signature0(convert4(arg0)); // signature: string } if (test1(arg1)) { // type: boolean if (arguments.length === 2) { return signature1(convert5(arg0), arg1); // signature: string, boolean } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'boolean'); } if (test1(arg0)) { // type: boolean (convert to number) if (arguments.length === 1) { return signature0(convert6(arg0)); // signature: boolean } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test9(arg0)) { // type: null (convert to number) if (arguments.length === 1) { return signature0(convert7(arg0)); // signature: null } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'number,Complex,BigNumber,Unit,Array,Matrix'); }
...
/**
* Calculate the cubic root of a value.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.cbrt(x)
* math.cbrt(x, allRoots)
*
* Examples:
*
* math.cbrt(27); // returns 3
* math.cube(3); // returns 27
* math.cbrt(-64); // returns -4
...
function ceil(arg0) { "use strict"; var name = 'ceil'; if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature0(arg0); // signature: number } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: Complex if (arguments.length === 1) { return signature1(arg0); // signature: Complex } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test2(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature2(arg0); // signature: BigNumber } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test3(arg0)) { // type: Fraction if (arguments.length === 1) { return signature3(arg0); // signature: Fraction } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test4(arg0)) { // type: Array if (arguments.length === 1) { return signature4(arg0); // signature: Array } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test5(arg0)) { // type: Matrix if (arguments.length === 1) { return signature4(arg0); // signature: Matrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test6(arg0)) { // type: string (convert to number) if (arguments.length === 1) { return signature0(convert0(arg0)); // signature: string } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test7(arg0)) { // type: boolean (convert to number) if (arguments.length === 1) { return signature0(convert1(arg0)); // signature: boolean } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test8(arg0)) { // type: null (convert to number) if (arguments.length === 1) { return signature0(convert2(arg0)); // signature: null } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'number,Complex,BigNumber,Fraction,Array,Matrix'); }
...
/**
* Round a value towards plus infinity
* If `x` is complex, both real and imaginary part are rounded towards plus infinity.
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.ceil(x)
*
* Examples:
*
* math.ceil(3.2); // returns number 4
* math.ceil(3.8); // returns number 4
* math.ceil(-4.2); // returns number -4
* math.ceil(-4.7); // returns number -4
...
function chain(arg0) { "use strict"; var name = 'chain'; if (arguments.length === 0) { return signature0(); // signature: } // type: any if (arguments.length === 1) { return signature1(arg0); // signature: any } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } throw createError(name, arguments.length, 0, arguments[0], 'any'); }
...
math.eval('12 / (2.3 + 0.7)'); // 4
math.eval('5.08 cm to inch'); // 2 inch
math.eval('sin(45 deg) ^ 2'); // 0.5
math.eval('9 / 3 + 2i'); // 3 + 2i
math.eval('det([-1, 2; 3, 1])'); // -7
// chaining
math.chain(3)
.add(4)
.multiply(2)
.done(); // 14
```
## Browser support
...
function clone(arg0) { "use strict"; var name = 'clone'; // type: any if (arguments.length === 1) { return signature0(arg0); // signature: any } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } throw createError(name, arguments.length, 0, arguments[0], 'any'); }
...
return desc;
};
/**
* Export the help object to JSON
*/
Help.prototype.toJSON = function () {
var obj = object.clone(this.doc);
obj.mathjs = 'Help';
return obj;
};
/**
* Instantiate a Help object from a JSON object
* @param {Object} json
...
function combinations(arg0, arg1) { "use strict"; var name = 'combinations'; if (test0(arg0)) { // type: number if (test0(arg1)) { // type: number if (arguments.length === 2) { return signature0(arg0, arg1); // signature: number, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test1(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature1(convert0(arg0), arg1); // signature: number, BigNumber } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: Fraction (convert to BigNumber) if (arguments.length === 2) { return signature1(convert0(arg0), convert1(arg1)); // signature: number, Fraction } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: string (convert to number) if (arguments.length === 2) { return signature0(arg0, convert2(arg1)); // signature: number, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test4(arg1)) { // type: boolean (convert to number) if (arguments.length === 2) { return signature0(arg0, convert3(arg1)); // signature: number, boolean } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test5(arg1)) { // type: null (convert to number) if (arguments.length === 2) { return signature0(arg0, convert4(arg1)); // signature: number, null } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'number,BigNumber'); } if (test1(arg0)) { // type: BigNumber if (test1(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature1(arg0, arg1); // signature: BigNumber, BigNumber } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test0(arg1)) { // type: number (convert to BigNumber) if (arguments.length === 2) { return signature1(arg0, convert0(arg1)); // signature: BigNumber, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: Fraction (convert to BigNumber) if (arguments.length === 2) { return signature1(arg0, convert1(arg1)); // signature: BigNumber, Fraction } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: string (convert to BigNumber) if (arguments.length === 2) { return signature1(arg0, convert5(arg1)); // signature: BigNumber, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test4(arg1)) { // type: boolean (convert to BigNumber) if (arguments.length === 2) { return signature1(arg0, convert6(arg1)); // signature: BigNumber, boolean } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test5(arg1)) { // type: null (convert to BigNumber) if (arguments.length === 2) { return signature1(arg0, convert7(arg1)); // signature: BigNumber, null } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'BigNumber'); } if (test2(arg0)) { // type: Fraction (convert to BigNumber) if (test1(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature1(convert1(arg0), arg1); // signature: Fraction, BigNumber ...
...
* possibilities.
*
* Combinations only takes integer arguments.
* The following condition must be enforced: k <= n.
*
* Syntax:
*
* math.combinations(n, k)
*
* Examples:
*
* math.combinations(7, 5); // returns 21
*
* See also:
*
...
function compare(arg0, arg1) { "use strict"; var name = 'compare'; if (test0(arg0)) { // type: number if (test0(arg1)) { // type: number if (arguments.length === 2) { return signature0(arg0, arg1); // signature: number, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test1(arg1)) { // type: Complex if (arguments.length === 2) { return signature1(convert0(arg0), arg1); // signature: number, Complex } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature2(convert1(arg0), arg1); // signature: number, BigNumber } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: Fraction if (arguments.length === 2) { return signature3(convert2(arg0), arg1); // signature: number, Fraction } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test4(arg1)) { // type: string (convert to number) if (arguments.length === 2) { return signature0(arg0, convert3(arg1)); // signature: number, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test5(arg1)) { // type: boolean (convert to number) if (arguments.length === 2) { return signature0(arg0, convert4(arg1)); // signature: number, boolean } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test6(arg1)) { // type: null (convert to number) if (arguments.length === 2) { return signature0(arg0, convert5(arg1)); // signature: number, null } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } } if (test1(arg0)) { // type: Complex if (test1(arg1)) { // type: Complex if (arguments.length === 2) { return signature1(arg0, arg1); // signature: Complex, Complex } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test0(arg1)) { // type: number (convert to Complex) if (arguments.length === 2) { return signature1(arg0, convert0(arg1)); // signature: Complex, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: BigNumber (convert to Complex) if (arguments.length === 2) { return signature1(arg0, convert6(arg1)); // signature: Complex, BigNumber } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: Fraction (convert to Complex) if (arguments.length === 2) { return signature1(arg0, convert7(arg1)); // signature: Complex, Fraction } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test4(arg1)) { // type: string (convert to Complex) if (arguments.length === 2) { return signature1(arg0, convert8(arg1)); // signature: Complex, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } } if (test2(arg0)) { // type: BigNumber if (test1(arg1)) { // type: Complex if (arguments.length === 2) { return signature1(convert6(arg0), arg1); // signature: BigNumber, Complex } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature2(arg0, arg1); // signature: BigNumber, Big ...
...
* is smaller than the configured epsilon. The function cannot be used to
* compare values smaller than approximately 2.22e-16.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.compare(x, y)
*
* Examples:
*
* math.compare(6, 1); // returns 1
* math.compare(2, 3); // returns -1
* math.compare(7, 7); // returns 0
*
...
function compile(arg0) { "use strict"; var name = 'compile'; if (test0(arg0)) { // type: string if (arguments.length === 1) { return signature0(arg0); // signature: string } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: Array if (arguments.length === 1) { return signature1(arg0); // signature: Array } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test2(arg0)) { // type: Matrix if (arguments.length === 1) { return signature1(arg0); // signature: Matrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test3(arg0)) { // type: number (convert to string) if (arguments.length === 1) { return signature0(convert0(arg0)); // signature: number } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test4(arg0)) { // type: boolean (convert to string) if (arguments.length === 1) { return signature0(convert1(arg0)); // signature: boolean } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test5(arg0)) { // type: null (convert to string) if (arguments.length === 1) { return signature0(convert2(arg0)); // signature: null } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'string,Array,Matrix'); }
...
* parse(expr, options)
* parse([expr1, expr2, expr3, ...])
* parse([expr1, expr2, expr3, ...], options)
*
* Example:
*
* var node = parse('sqrt(3^2 + 4^2)');
* node.compile(math).eval(); // 5
*
* var scope = {a:3, b:4}
* var node = parse('a * b'); // 12
* var code = node.compile(math);
* code.eval(scope); // 12
* scope.a = 5;
* code.eval(scope); // 20
...
function complex(arg0, arg1) { "use strict"; var name = 'complex'; if (arguments.length === 0) { return signature0(); // signature: } if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature1(arg0); // signature: number } if (test0(arg1)) { // type: number if (arguments.length === 2) { return signature2(arg0, arg1); // signature: number, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test1(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature3(convert0(arg0), arg1); // signature: number, BigNumber } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: Fraction (convert to BigNumber) if (arguments.length === 2) { return signature3(convert0(arg0), convert1(arg1)); // signature: number, Fraction } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: string (convert to number) if (arguments.length === 2) { return signature2(arg0, convert2(arg1)); // signature: number, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test4(arg1)) { // type: boolean (convert to number) if (arguments.length === 2) { return signature2(arg0, convert3(arg1)); // signature: number, boolean } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test5(arg1)) { // type: null (convert to number) if (arguments.length === 2) { return signature2(arg0, convert4(arg1)); // signature: number, null } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'number,BigNumber'); } if (test6(arg0)) { // type: Complex if (arguments.length === 1) { return signature4(arg0); // signature: Complex } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature4(convert5(arg0)); // signature: BigNumber } if (test1(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature3(arg0, arg1); // signature: BigNumber, BigNumber } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test0(arg1)) { // type: number (convert to BigNumber) if (arguments.length === 2) { return signature3(arg0, convert0(arg1)); // signature: BigNumber, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: Fraction (convert to BigNumber) if (arguments.length === 2) { return signature3(arg0, convert1(arg1)); // signature: BigNumber, Fraction } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: string (convert to BigNumber) if (arguments.length === 2) { return signature3(arg0, convert6(arg1)); // signature: BigNumber, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test4(arg1)) { // type: boolean (convert to BigNumber) if (arguments.length === 2) { return signature3(arg0, convert7(arg1)); // signature: BigNumber, boolean } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test5(arg1)) { // type: null (convert to BigNumber) if (arguments.length === 2) { ...
...
* Syntax:
*
* math.string(value)
*
* Examples:
*
* math.string(4.2); // returns string '4.2'
* math.string(math.complex(3, 2); // returns string '3 + 2i'
*
* var u = math.unit(5, 'km');
* math.string(u.to('m')); // returns string '5000 m'
*
* math.string([true, false]); // returns ['true', 'false']
*
* See also:
...
function composition(arg0, arg1) { "use strict"; var name = 'composition'; if (test0(arg0)) { // type: number if (test0(arg1)) { // type: number if (arguments.length === 2) { return signature0(arg0, arg1); // signature: number, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test1(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature0(arg0, arg1); // signature: number, BigNumber } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: Fraction (convert to BigNumber) if (arguments.length === 2) { return signature0(arg0, convert0(arg1)); // signature: number, Fraction } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: string (convert to number) if (arguments.length === 2) { return signature0(arg0, convert1(arg1)); // signature: number, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test4(arg1)) { // type: boolean (convert to number) if (arguments.length === 2) { return signature0(arg0, convert2(arg1)); // signature: number, boolean } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test5(arg1)) { // type: null (convert to number) if (arguments.length === 2) { return signature0(arg0, convert3(arg1)); // signature: number, null } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'number,BigNumber'); } if (test1(arg0)) { // type: BigNumber if (test0(arg1)) { // type: number if (arguments.length === 2) { return signature0(arg0, arg1); // signature: BigNumber, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test1(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature0(arg0, arg1); // signature: BigNumber, BigNumber } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: Fraction (convert to BigNumber) if (arguments.length === 2) { return signature0(arg0, convert0(arg1)); // signature: BigNumber, Fraction } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: string (convert to number) if (arguments.length === 2) { return signature0(arg0, convert1(arg1)); // signature: BigNumber, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test4(arg1)) { // type: boolean (convert to number) if (arguments.length === 2) { return signature0(arg0, convert2(arg1)); // signature: BigNumber, boolean } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test5(arg1)) { // type: null (convert to number) if (arguments.length === 2) { return signature0(arg0, convert3(arg1)); // signature: BigNumber, null } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'number,BigNumber'); } if (test2(arg0)) { // type: Fraction (convert to BigNumber) if (test0(arg1)) { // type: number if (arguments.length === 2) { return signature0(convert0(arg0), arg1); // signature: Fraction, number } if (arguments.length > 2) { throw createE ...
...
* The composition counts of n into k parts.
*
* composition only takes integer arguments.
* The following condition must be enforced: k <= n.
*
* Syntax:
*
* math.composition(n, k)
*
* Examples:
*
* math.composition(5, 3); // returns 6
*
* See also:
*
...
function concat(arg0) { "use strict"; var name = 'concat'; if (test0(arg0)) { // type: ...string var varArgs = [arg0]; for (var i = 1; i < arguments.length; i++) { if (test0(arguments[i])) { varArgs.push(arguments[i]); } else { throw createError(name, arguments.length, i, arguments[i], 'string'); } } return signature0(varArgs); // signature: ...string } if (test1(arg0) || test2(arg0) || test3(arg0) || test4(arg0) || test5(arg0) || test6(arg0) || test6(arg0) || test7(arg0) || test7 (arg0)) { // type: ...Array|Matrix|number|BigNumber|Fraction|boolean|null var varArgs = [arg0]; for (var i = 1; i < arguments.length; i++) { if (test1(arguments[i]) || test2(arguments[i]) || test3(arguments[i]) || test4(arguments[i])) { varArgs.push(arguments[i]); } else if (test5(arguments[i])) { varArgs.push(convert0(arguments[i])); } else if (test6(arguments[i])) { varArgs.push(convert1(arguments[i])); } else if (test6(arguments[i])) { varArgs.push(convert2(arguments[i])); } else if (test7(arguments[i])) { varArgs.push(convert3(arguments[i])); } else if (test7(arguments[i])) { varArgs.push(convert4(arguments[i])); } else { throw createError(name, arguments.length, i, arguments[i], 'Array,Matrix,number,BigNumber'); } } return signature1(varArgs); // signature: ...Array|Matrix|number|BigNumber|Fraction|boolean|null } throw createError(name, arguments.length, 0, arguments[0], 'string,Array,Matrix,number,BigNumber'); }
...
// figure out what number of arguments the callback function expects
var args = maxArgumentCount(callback);
var recurse = function (value, index) {
if (Array.isArray(value)) {
value.forEach(function (child, i) {
// we create a copy of the index array and append the new index value
recurse(child, index.concat(i + 1)); // one based index, hence i+1
});
}
else {
// invoke the callback function with the right number of arguments
if (args === 1) {
callback(value);
}
...
function _config(options) { if (options) { var prev = object.clone(config); // validate some of the options validateOption(options, 'matrix', MATRIX); validateOption(options, 'number', NUMBER); // merge options object.deepExtend(config, options); var curr = object.clone(config); var changes = object.clone(options); // emit 'config' event math.emit('config', curr, prev, changes); return curr; } else { return object.clone(config); } }
...
/**
* Set configuration options for math.js, and get current options.
* Will emit a 'config' event, with arguments (curr, prev, changes).
*
* Syntax:
*
* math.config(config: Object): Object
*
* Examples:
*
* math.config().number; // outputs 'number'
* math.eval('0.4'); // outputs number 0.4
* math.config({number: 'Fraction'});
* math.eval('0.4'); // outputs Fraction 2/5
...
function conj(arg0) { "use strict"; var name = 'conj'; if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature0(arg0); // signature: number } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: Complex if (arguments.length === 1) { return signature1(arg0); // signature: Complex } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test2(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature2(arg0); // signature: BigNumber } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test3(arg0)) { // type: Array if (arguments.length === 1) { return signature3(arg0); // signature: Array } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test4(arg0)) { // type: Matrix if (arguments.length === 1) { return signature3(arg0); // signature: Matrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test5(arg0)) { // type: Fraction (convert to BigNumber) if (arguments.length === 1) { return signature2(convert0(arg0)); // signature: Fraction } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test6(arg0)) { // type: string (convert to number) if (arguments.length === 1) { return signature0(convert1(arg0)); // signature: string } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test7(arg0)) { // type: boolean (convert to number) if (arguments.length === 1) { return signature0(convert2(arg0)); // signature: boolean } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test8(arg0)) { // type: null (convert to number) if (arguments.length === 1) { return signature0(convert3(arg0)); // signature: null } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'number,Complex,BigNumber,Array,Matrix'); }
...
* Compute the complex conjugate of a complex value.
* If `x = a+bi`, the complex conjugate of `x` is `a - bi`.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.conj(x)
*
* Examples:
*
* math.conj(math.complex('2 + 3i')); // returns Complex 2 - 3i
* math.conj(math.complex('2 - 3i')); // returns Complex 2 + 3i
* math.conj(math.complex('-5.2i')); // returns Complex 5.2i
*
...
function cos(arg0) { "use strict"; var name = 'cos'; if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature0(arg0); // signature: number } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: Complex if (arguments.length === 1) { return signature1(arg0); // signature: Complex } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test2(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature2(arg0); // signature: BigNumber } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test3(arg0)) { // type: Unit if (arguments.length === 1) { return signature3(arg0); // signature: Unit } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test4(arg0)) { // type: Array if (arguments.length === 1) { return signature4(arg0); // signature: Array } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test5(arg0)) { // type: Matrix if (arguments.length === 1) { return signature4(arg0); // signature: Matrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test6(arg0)) { // type: Fraction (convert to BigNumber) if (arguments.length === 1) { return signature2(convert0(arg0)); // signature: Fraction } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test7(arg0)) { // type: string (convert to number) if (arguments.length === 1) { return signature0(convert1(arg0)); // signature: string } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test8(arg0)) { // type: boolean (convert to number) if (arguments.length === 1) { return signature0(convert2(arg0)); // signature: boolean } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test9(arg0)) { // type: null (convert to number) if (arguments.length === 1) { return signature0(convert3(arg0)); // signature: null } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'number,Complex,BigNumber,Unit,Array,Matrix'); }
...
var u1, u2,
picked = -1;
// We reject values outside of the interval [0, 1]
// TODO: check if it is ok to do that?
while (picked < 0 || picked > 1) {
u1 = rng();
u2 = rng();
picked = 1/6 * Math.pow(-2 * Math.log(u1), 0.5) * Math.cos(2 * Math.PI * u2) +
0.5;
}
return picked;
}
}
};
distribution.toTex = undefined; // use default template
...
function cosh(arg0) { "use strict"; var name = 'cosh'; if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature0(arg0); // signature: number } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: Complex if (arguments.length === 1) { return signature1(arg0); // signature: Complex } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test2(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature2(arg0); // signature: BigNumber } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test3(arg0)) { // type: Unit if (arguments.length === 1) { return signature3(arg0); // signature: Unit } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test4(arg0)) { // type: Array if (arguments.length === 1) { return signature4(arg0); // signature: Array } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test5(arg0)) { // type: Matrix if (arguments.length === 1) { return signature4(arg0); // signature: Matrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test6(arg0)) { // type: Fraction (convert to BigNumber) if (arguments.length === 1) { return signature2(convert0(arg0)); // signature: Fraction } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test7(arg0)) { // type: string (convert to number) if (arguments.length === 1) { return signature0(convert1(arg0)); // signature: string } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test8(arg0)) { // type: boolean (convert to number) if (arguments.length === 1) { return signature0(convert2(arg0)); // signature: boolean } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test9(arg0)) { // type: null (convert to number) if (arguments.length === 1) { return signature0(convert3(arg0)); // signature: null } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'number,Complex,BigNumber,Unit,Array,Matrix'); }
...
* Calculate the hyperbolic cosine of a value,
* defined as `cosh(x) = 1/2 * (exp(x) + exp(-x))`.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.cosh(x)
*
* Examples:
*
* math.cosh(0.5); // returns number 1.1276259652063807
*
* See also:
*
...
function cot(arg0) { "use strict"; var name = 'cot'; if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature0(arg0); // signature: number } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: Complex if (arguments.length === 1) { return signature1(arg0); // signature: Complex } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test2(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature2(arg0); // signature: BigNumber } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test3(arg0)) { // type: Unit if (arguments.length === 1) { return signature3(arg0); // signature: Unit } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test4(arg0)) { // type: Array if (arguments.length === 1) { return signature4(arg0); // signature: Array } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test5(arg0)) { // type: Matrix if (arguments.length === 1) { return signature4(arg0); // signature: Matrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test6(arg0)) { // type: Fraction (convert to BigNumber) if (arguments.length === 1) { return signature2(convert0(arg0)); // signature: Fraction } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test7(arg0)) { // type: string (convert to number) if (arguments.length === 1) { return signature0(convert1(arg0)); // signature: string } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test8(arg0)) { // type: boolean (convert to number) if (arguments.length === 1) { return signature0(convert2(arg0)); // signature: boolean } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test9(arg0)) { // type: null (convert to number) if (arguments.length === 1) { return signature0(convert3(arg0)); // signature: null } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'number,Complex,BigNumber,Unit,Array,Matrix'); }
...
* Syntax:
*
* math.acot(x)
*
* Examples:
*
* math.acot(0.5); // returns number 0.4636476090008061
* math.acot(math.cot(1.5)); // returns number 1.5
*
* math.acot(2); // returns Complex 1.5707963267948966 -1.3169578969248166 i
*
* See also:
*
* cot, atan
*
...
function coth(arg0) { "use strict"; var name = 'coth'; if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature0(arg0); // signature: number } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: Complex if (arguments.length === 1) { return signature1(arg0); // signature: Complex } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test2(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature2(arg0); // signature: BigNumber } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test3(arg0)) { // type: Unit if (arguments.length === 1) { return signature3(arg0); // signature: Unit } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test4(arg0)) { // type: Array if (arguments.length === 1) { return signature4(arg0); // signature: Array } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test5(arg0)) { // type: Matrix if (arguments.length === 1) { return signature4(arg0); // signature: Matrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test6(arg0)) { // type: Fraction (convert to BigNumber) if (arguments.length === 1) { return signature2(convert0(arg0)); // signature: Fraction } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test7(arg0)) { // type: string (convert to number) if (arguments.length === 1) { return signature0(convert1(arg0)); // signature: string } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test8(arg0)) { // type: boolean (convert to number) if (arguments.length === 1) { return signature0(convert2(arg0)); // signature: boolean } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test9(arg0)) { // type: null (convert to number) if (arguments.length === 1) { return signature0(convert3(arg0)); // signature: null } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'number,Complex,BigNumber,Unit,Array,Matrix'); }
...
* Calculate the hyperbolic cotangent of a value,
* defined as `coth(x) = 1 / tanh(x)`.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.coth(x)
*
* Examples:
*
* // coth(x) = 1 / tanh(x)
* math.coth(2); // returns 1.0373147207275482
* 1 / math.tanh(2); // returns 1.0373147207275482
*
...
function create(config) { // create a new math.js instance var math = core.create(config); math.create = create; // import data types, functions, constants, expression parser, etc. math['import'](require('./lib')); return math; }
...
* false (default), output type can vary depending
* on input values. For example `math.sqrt(-4)`
* returns `complex('2i')` when predictable is false, and
* returns `NaN` when true.
*/
function create (config) {
// create a new math.js instance
var math = core.create(config);
math.create = create;
// import data types, functions, constants, expression parser, etc.
math['import'](require('./lib'));
return math;
}
...
function createUnit(arg0, arg1, arg2) { "use strict"; var name = 'createUnit'; if (test0(arg0)) { // type: string if (arguments.length === 1) { return signature0(arg0); // signature: string } if (test1(arg1)) { // type: Unit if (arguments.length === 2) { return signature1(arg0, arg1); // signature: string, Unit } if (test2(arg2)) { // type: Object if (arguments.length === 3) { return signature2(arg0, arg1, arg2); // signature: string, Unit, Object } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } throw createError(name, arguments.length, 2, arguments[2], 'Object'); } if (test0(arg1)) { // type: string if (arguments.length === 2) { return signature1(arg0, arg1); // signature: string, string } if (test2(arg2)) { // type: Object if (arguments.length === 3) { return signature2(arg0, arg1, arg2); // signature: string, string, Object } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } throw createError(name, arguments.length, 2, arguments[2], 'Object'); } if (test3(arg1)) { // type: number (convert to string) if (arguments.length === 2) { return signature1(arg0, convert0(arg1)); // signature: string, number } if (test2(arg2)) { // type: Object if (arguments.length === 3) { return signature2(arg0, convert0(arg1), arg2); // signature: string, number, Object } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } throw createError(name, arguments.length, 2, arguments[2], 'Object'); } if (test4(arg1)) { // type: boolean (convert to string) if (arguments.length === 2) { return signature1(arg0, convert1(arg1)); // signature: string, boolean } if (test2(arg2)) { // type: Object if (arguments.length === 3) { return signature2(arg0, convert1(arg1), arg2); // signature: string, boolean, Object } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } throw createError(name, arguments.length, 2, arguments[2], 'Object'); } if (test5(arg1)) { // type: null (convert to string) if (arguments.length === 2) { return signature1(arg0, convert2(arg1)); // signature: string, null } if (test2(arg2)) { // type: Object if (arguments.length === 3) { return signature2(arg0, convert2(arg1), arg2); // signature: string, null, Object } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } throw createError(name, arguments.length, 2, arguments[2], 'Object'); } if (test2(arg1)) { // type: Object if (arguments.length === 2) { return signature1(arg0, arg1); // signature: string, Object } if (test2(arg2)) { // type: Object if (arguments.length === 3) { return signature2(arg0, arg1, arg2); // signature: string, Object, Object } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } throw createError(name, arguments.length, 2, arguments[2], 'Object'); } throw createError(name, arguments.length, 1, arguments[1], 'Unit,string,Object'); } if (test3(arg0)) { // type: number (convert to string) if (arguments.length === 1) { return signature0(convert0(arg0)); // signature: number } if (test1(arg1)) { // type: Unit if (arguments.length === 2) { return signature1(convert0(arg0), arg1); // signature: number, Unit } if (test2(arg2)) { // type: Object if (arguments.length === 3) { return signature2(convert0(arg0), arg1, arg2); // signature: number, Unit, Object } ...
n/a
function cross(arg0, arg1) { "use strict"; var name = 'cross'; if (test0(arg0)) { // type: Array if (test0(arg1)) { // type: Array if (arguments.length === 2) { return signature0(arg0, arg1); // signature: Array, Array } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test1(arg1)) { // type: Matrix if (arguments.length === 2) { return signature1(arg0, arg1); // signature: Array, Matrix } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'Array,Matrix'); } if (test1(arg0)) { // type: Matrix if (test0(arg1)) { // type: Array if (arguments.length === 2) { return signature2(arg0, arg1); // signature: Matrix, Array } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test1(arg1)) { // type: Matrix if (arguments.length === 2) { return signature3(arg0, arg1); // signature: Matrix, Matrix } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'Array,Matrix'); } throw createError(name, arguments.length, 0, arguments[0], 'Array,Matrix'); }
...
* ]
*
* If one of the input vectors has a dimension greater than 1, the output
* vector will be a 1x3 (2-dimensional) matrix.
*
* Syntax:
*
* math.cross(x, y)
*
* Examples:
*
* math.cross([1, 1, 0], [0, 1, 1]); // Returns [1, -1, 1]
* math.cross([3, -3, 1], [4, 9, 2]); // Returns [-15, -2, 39]
* math.cross([2, 3, 4], [5, 6, 7]); // Returns [-3, 6, -3]
* math.cross([[1, 2, 3]], [[4], [5], [6]]); // Returns [[-3, 6, -3]]
...
function csc(arg0) { "use strict"; var name = 'csc'; if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature0(arg0); // signature: number } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: Complex if (arguments.length === 1) { return signature1(arg0); // signature: Complex } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test2(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature2(arg0); // signature: BigNumber } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test3(arg0)) { // type: Unit if (arguments.length === 1) { return signature3(arg0); // signature: Unit } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test4(arg0)) { // type: Array if (arguments.length === 1) { return signature4(arg0); // signature: Array } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test5(arg0)) { // type: Matrix if (arguments.length === 1) { return signature4(arg0); // signature: Matrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test6(arg0)) { // type: Fraction (convert to BigNumber) if (arguments.length === 1) { return signature2(convert0(arg0)); // signature: Fraction } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test7(arg0)) { // type: string (convert to number) if (arguments.length === 1) { return signature0(convert1(arg0)); // signature: string } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test8(arg0)) { // type: boolean (convert to number) if (arguments.length === 1) { return signature0(convert2(arg0)); // signature: boolean } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test9(arg0)) { // type: null (convert to number) if (arguments.length === 1) { return signature0(convert3(arg0)); // signature: null } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'number,Complex,BigNumber,Unit,Array,Matrix'); }
...
* Syntax:
*
* math.acsc(x)
*
* Examples:
*
* math.acsc(0.5); // returns number 0.5235987755982989
* math.acsc(math.csc(1.5)); // returns number ~1.5
*
* math.acsc(2); // returns Complex 1.5707963267948966 -1.3169578969248166 i
*
* See also:
*
* csc, asin, asec
*
...
function csch(arg0) { "use strict"; var name = 'csch'; if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature0(arg0); // signature: number } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: Complex if (arguments.length === 1) { return signature1(arg0); // signature: Complex } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test2(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature2(arg0); // signature: BigNumber } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test3(arg0)) { // type: Unit if (arguments.length === 1) { return signature3(arg0); // signature: Unit } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test4(arg0)) { // type: Array if (arguments.length === 1) { return signature4(arg0); // signature: Array } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test5(arg0)) { // type: Matrix if (arguments.length === 1) { return signature4(arg0); // signature: Matrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test6(arg0)) { // type: Fraction (convert to BigNumber) if (arguments.length === 1) { return signature2(convert0(arg0)); // signature: Fraction } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test7(arg0)) { // type: string (convert to number) if (arguments.length === 1) { return signature0(convert1(arg0)); // signature: string } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test8(arg0)) { // type: boolean (convert to number) if (arguments.length === 1) { return signature0(convert2(arg0)); // signature: boolean } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test9(arg0)) { // type: null (convert to number) if (arguments.length === 1) { return signature0(convert3(arg0)); // signature: null } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'number,Complex,BigNumber,Unit,Array,Matrix'); }
...
* Calculate the hyperbolic cosecant of a value,
* defined as `csch(x) = 1 / sinh(x)`.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.csch(x)
*
* Examples:
*
* // csch(x) = 1/ sinh(x)
* math.csch(0.5); // returns 1.9190347513349437
* 1 / math.sinh(0.5); // returns 1.9190347513349437
*
...
function cube(arg0) { "use strict"; var name = 'cube'; if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature0(arg0); // signature: number } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: Complex if (arguments.length === 1) { return signature1(arg0); // signature: Complex } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test2(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature2(arg0); // signature: BigNumber } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test3(arg0)) { // type: Fraction if (arguments.length === 1) { return signature3(arg0); // signature: Fraction } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test4(arg0)) { // type: Unit if (arguments.length === 1) { return signature4(arg0); // signature: Unit } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test5(arg0)) { // type: Array if (arguments.length === 1) { return signature5(arg0); // signature: Array } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test6(arg0)) { // type: Matrix if (arguments.length === 1) { return signature5(arg0); // signature: Matrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test7(arg0)) { // type: string (convert to number) if (arguments.length === 1) { return signature0(convert0(arg0)); // signature: string } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test8(arg0)) { // type: boolean (convert to number) if (arguments.length === 1) { return signature0(convert1(arg0)); // signature: boolean } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test9(arg0)) { // type: null (convert to number) if (arguments.length === 1) { return signature0(convert2(arg0)); // signature: null } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'number,Complex,BigNumber,Fraction,Unit,Array,Matrix'); }
...
*
* math.cbrt(x)
* math.cbrt(x, allRoots)
*
* Examples:
*
* math.cbrt(27); // returns 3
* math.cube(3); // returns 27
* math.cbrt(-64); // returns -4
* math.cbrt(math.unit('27 m^3')); // returns Unit 3 m
* math.cbrt([27, 64, 125]); // returns [3, 4, 5]
*
* var x = math.complex('8i');
* math.cbrt(x); // returns Complex 1.7320508075689 + i
* math.cbrt(x, true); // returns Matrix [
...
function deepEqual(arg0, arg1) { "use strict"; var name = 'deepEqual'; // type: any // type: any if (arguments.length === 2) { return signature0(arg0, arg1); // signature: any, any } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } throw createError(name, arguments.length, 1, arguments[1], 'any'); throw createError(name, arguments.length, 0, arguments[0], 'any'); }
...
}
if (a.length != b.length) {
return false;
}
for (i = 0, len = a.length; i < len; i++) {
if (!exports.deepEqual(a[i], b[i])) {
return false;
}
}
return true;
}
else if (a instanceof Object) {
if (Array.isArray(b) || !(b instanceof Object)) {
...
function derivative(arg0, arg1, arg2) { "use strict"; var name = 'derivative'; if (test0(arg0)) { // type: string if (test0(arg1)) { // type: string if (arguments.length === 2) { return signature0(arg0, arg1); // signature: string, string } if (test1(arg2)) { // type: Object if (arguments.length === 3) { return signature1(arg0, arg1, arg2); // signature: string, string, Object } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } throw createError(name, arguments.length, 2, arguments[2], 'Object'); } if (test2(arg1)) { // type: SymbolNode if (arguments.length === 2) { return signature2(arg0, arg1); // signature: string, SymbolNode } if (test1(arg2)) { // type: Object if (arguments.length === 3) { return signature3(arg0, arg1, arg2); // signature: string, SymbolNode, Object } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } throw createError(name, arguments.length, 2, arguments[2], 'Object'); } if (test3(arg1)) { // type: number (convert to string) if (arguments.length === 2) { return signature0(arg0, convert0(arg1)); // signature: string, number } if (test1(arg2)) { // type: Object if (arguments.length === 3) { return signature1(arg0, convert0(arg1), arg2); // signature: string, number, Object } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } throw createError(name, arguments.length, 2, arguments[2], 'Object'); } if (test4(arg1)) { // type: boolean (convert to string) if (arguments.length === 2) { return signature0(arg0, convert1(arg1)); // signature: string, boolean } if (test1(arg2)) { // type: Object if (arguments.length === 3) { return signature1(arg0, convert1(arg1), arg2); // signature: string, boolean, Object } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } throw createError(name, arguments.length, 2, arguments[2], 'Object'); } if (test5(arg1)) { // type: null (convert to string) if (arguments.length === 2) { return signature0(arg0, convert2(arg1)); // signature: string, null } if (test1(arg2)) { // type: Object if (arguments.length === 3) { return signature1(arg0, convert2(arg1), arg2); // signature: string, null, Object } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } throw createError(name, arguments.length, 2, arguments[2], 'Object'); } throw createError(name, arguments.length, 1, arguments[1], 'string,SymbolNode'); } if (test6(arg0)) { // type: Node if (test0(arg1)) { // type: string if (arguments.length === 2) { return signature4(arg0, arg1); // signature: Node, string } if (test1(arg2)) { // type: Object if (arguments.length === 3) { return signature5(arg0, arg1, arg2); // signature: Node, string, Object } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } throw createError(name, arguments.length, 2, arguments[2], 'Object'); } if (test2(arg1)) { // type: SymbolNode if (arguments.length === 2) { return signature6(arg0, arg1); // signature: Node, SymbolNode } if (test1(arg2)) { // type: Object if (arguments.length === 3) { return signature7(arg0, arg1, arg2); // signature: Node, SymbolNode, Object } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } throw createError(name, arguments.length, 2, arguments[2], 'Object'); } if (t ...
...
// functions and constants
math.round(math.e, 3); // 2.718
math.atan2(3, -3) / math.pi; // 0.75
math.log(1000, 10); // 3
math.sqrt(-4); // 2i
math.pow([[-1, 2], [3, 1]], 2); // [[7, 0], [0, 7]]
math.derivative('x^2 + x', 'x'); // 2 * x + 1
// expressions
math.eval('12 / (2.3 + 0.7)'); // 4
math.eval('5.08 cm to inch'); // 2 inch
math.eval('sin(45 deg) ^ 2'); // 0.5
math.eval('9 / 3 + 2i'); // 3 + 2i
math.eval('det([-1, 2; 3, 1])'); // -7
...
function det(arg0) { "use strict"; var name = 'det'; if (test0(arg0)) { // type: Array if (arguments.length === 1) { return signature0(arg0); // signature: Array } } if (test1(arg0)) { // type: Matrix if (arguments.length === 1) { return signature0(arg0); // signature: Matrix } } // type: any if (arguments.length === 1) { return signature1(arg0); // signature: any } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } throw createError(name, arguments.length, 0, arguments[0], 'Array,Matrix,any'); }
...
var unaryMinus = load(require('../arithmetic/unaryMinus'));
/**
* Calculate the determinant of a matrix.
*
* Syntax:
*
* math.det(x)
*
* Examples:
*
* math.det([[1, 2], [3, 4]]); // returns -2
*
* var A = [
* [-2, 2, 3],
...
function diag(arg0, arg1, arg2) { "use strict"; var name = 'diag'; if (test0(arg0)) { // type: Array if (arguments.length === 1) { return signature0(arg0); // signature: Array } if (test1(arg1)) { // type: number if (arguments.length === 2) { return signature1(arg0, arg1); // signature: Array, number } if (test2(arg2)) { // type: string if (arguments.length === 3) { return signature2(arg0, arg1, arg2); // signature: Array, number, string } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } if (test1(arg2)) { // type: number (convert to string) if (arguments.length === 3) { return signature2(arg0, arg1, convert0(arg2)); // signature: Array, number, number } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } if (test3(arg2)) { // type: boolean (convert to string) if (arguments.length === 3) { return signature2(arg0, arg1, convert1(arg2)); // signature: Array, number, boolean } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } if (test4(arg2)) { // type: null (convert to string) if (arguments.length === 3) { return signature2(arg0, arg1, convert2(arg2)); // signature: Array, number, null } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } throw createError(name, arguments.length, 2, arguments[2], 'string'); } if (test5(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature3(arg0, arg1); // signature: Array, BigNumber } if (test2(arg2)) { // type: string if (arguments.length === 3) { return signature4(arg0, arg1, arg2); // signature: Array, BigNumber, string } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } if (test1(arg2)) { // type: number (convert to string) if (arguments.length === 3) { return signature4(arg0, arg1, convert0(arg2)); // signature: Array, BigNumber, number } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } if (test3(arg2)) { // type: boolean (convert to string) if (arguments.length === 3) { return signature4(arg0, arg1, convert1(arg2)); // signature: Array, BigNumber, boolean } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } if (test4(arg2)) { // type: null (convert to string) if (arguments.length === 3) { return signature4(arg0, arg1, convert2(arg2)); // signature: Array, BigNumber, null } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } throw createError(name, arguments.length, 2, arguments[2], 'string'); } if (test2(arg1)) { // type: string if (arguments.length === 2) { return signature5(arg0, arg1); // signature: Array, string } if (test2(arg2)) { // type: string if (arguments.length === 3) { return signature2(arg0, convert3(arg1), arg2); // signature: Array, string, string } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } if (test1(arg2)) { // type: number (convert to string) if (arguments.length === 3) { return signature2(arg0, convert3(arg1), convert0(arg2)); // signature: Array, string, number } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } if (test3(arg2)) { // type: boolean (convert to string) if (argume ...
...
* When `x` is a vector, a matrix with vector `x` on the diagonal will be returned.
* When `x` is a two dimensional matrix, the matrixes `k`th diagonal will be returned as vector.
* When k is positive, the values are placed on the super diagonal.
* When k is negative, the values are placed on the sub diagonal.
*
* Syntax:
*
* math.diag(X)
* math.diag(X, format)
* math.diag(X, k)
* math.diag(X, k, format)
*
* Examples:
*
* // create a diagonal matrix
...
function distance(arg0, arg1, arg2) { "use strict"; var name = 'distance'; if (test0(arg0)) { // type: Array if (arguments.length === 1) { return signature0(arg0); // signature: Array } if (test0(arg1)) { // type: Array if (arguments.length === 2) { return signature1(arg0, arg1); // signature: Array, Array } if (test0(arg2)) { // type: Array if (arguments.length === 3) { return signature2(arg0, arg1, arg2); // signature: Array, Array, Array } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } if (test1(arg2)) { // type: Matrix (convert to Array) if (arguments.length === 3) { return signature2(arg0, arg1, convert0(arg2)); // signature: Array, Array, Matrix } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } throw createError(name, arguments.length, 2, arguments[2], 'Array'); } if (test1(arg1)) { // type: Matrix (convert to Array) if (arguments.length === 2) { return signature1(arg0, convert0(arg1)); // signature: Array, Matrix } if (test0(arg2)) { // type: Array if (arguments.length === 3) { return signature2(arg0, convert0(arg1), arg2); // signature: Array, Matrix, Array } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } if (test1(arg2)) { // type: Matrix (convert to Array) if (arguments.length === 3) { return signature2(arg0, convert0(arg1), convert0(arg2)); // signature: Array, Matrix, Matrix } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } throw createError(name, arguments.length, 2, arguments[2], 'Array'); } throw createError(name, arguments.length, 1, arguments[1], 'Array'); } if (test1(arg0)) { // type: Matrix (convert to Array) if (arguments.length === 1) { return signature0(convert0(arg0)); // signature: Matrix } if (test0(arg1)) { // type: Array if (arguments.length === 2) { return signature1(convert0(arg0), arg1); // signature: Matrix, Array } if (test0(arg2)) { // type: Array if (arguments.length === 3) { return signature2(convert0(arg0), arg1, arg2); // signature: Matrix, Array, Array } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } if (test1(arg2)) { // type: Matrix (convert to Array) if (arguments.length === 3) { return signature2(convert0(arg0), arg1, convert0(arg2)); // signature: Matrix, Array, Matrix } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } throw createError(name, arguments.length, 2, arguments[2], 'Array'); } if (test1(arg1)) { // type: Matrix (convert to Array) if (arguments.length === 2) { return signature1(convert0(arg0), convert0(arg1)); // signature: Matrix, Matrix } if (test0(arg2)) { // type: Array if (arguments.length === 3) { return signature2(convert0(arg0), convert0(arg1), arg2); // signature: Matrix, Matrix, Array } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } if (test1(arg2)) { // type: Matrix (convert to Array) if (arguments.length === 3) { return signature2(convert0(arg0), convert0(arg1), convert0(arg2)); // signature: Matrix, Matrix, Matrix } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } throw createError(name, arguments.length, 2, arguments[2], 'Array'); } throw createError(name, arguments.length, 1, arguments[1], 'Array'); } if (test2(arg0)) { / ...
...
* Distance between point and a line in 2 and 3 dimensional spaces.
* Pairwise distance between a set of 2D or 3D points
* NOTE:
* When substituting coefficients of a line(a, b and c), use ax + by + c = 0 instead of ax + by = c
* For parametric equation of a 3D line, x0, y0, z0, a, b, c are from: (x−x0, y−y0, z−z0) = t(a, b, c)
*
* Syntax:
* math.distance([x1, y1], [x2, y2])
*- math.distance({pointOneX: 4, pointOneY: 5}, {pointTwoX: 2, pointTwoY: 7})
* math.distance([x1, y1, z1], [x2, y2, z2])
* math.distance({pointOneX: 4, pointOneY: 5, pointOneZ: 8}, {pointTwoX: 2, pointTwoY: 7, pointTwoZ: 9})
* math.distance([[A], [B], [C]...])
* math.distance([x1, y1], [LinePtX1, LinePtY1], [LinePtX2, LinePtY2])
* math.distance({pointX: 1, pointY: 4}, {lineOnePtX: 6, lineOnePtY: 3}, {lineTwoPtX: 2, lineTwoPtY: 8})
* math.distance([x1, y1, z1], [LinePtX1, LinePtY1, LinePtZ1], [LinePtX2, LinePtY2, LinePtZ2])
...
function divide(arg0, arg1) { "use strict"; var name = 'divide'; if (test0(arg0)) { // type: number if (test0(arg1)) { // type: number if (arguments.length === 2) { return signature0(arg0, arg1); // signature: number, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test1(arg1)) { // type: Complex if (arguments.length === 2) { return signature1(convert0(arg0), arg1); // signature: number, Complex } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature2(convert1(arg0), arg1); // signature: number, BigNumber } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: Fraction if (arguments.length === 2) { return signature3(convert2(arg0), arg1); // signature: number, Fraction } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test4(arg1)) { // type: Unit if (arguments.length === 2) { return signature4(arg0, arg1); // signature: number, Unit } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test5(arg1)) { // type: string (convert to number) if (arguments.length === 2) { return signature0(arg0, convert3(arg1)); // signature: number, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test6(arg1)) { // type: boolean (convert to number) if (arguments.length === 2) { return signature0(arg0, convert4(arg1)); // signature: number, boolean } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test7(arg1)) { // type: null (convert to number) if (arguments.length === 2) { return signature0(arg0, convert5(arg1)); // signature: number, null } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } } if (test1(arg0)) { // type: Complex if (test1(arg1)) { // type: Complex if (arguments.length === 2) { return signature1(arg0, arg1); // signature: Complex, Complex } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test0(arg1)) { // type: number (convert to Complex) if (arguments.length === 2) { return signature1(arg0, convert0(arg1)); // signature: Complex, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: BigNumber (convert to Complex) if (arguments.length === 2) { return signature1(arg0, convert6(arg1)); // signature: Complex, BigNumber } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: Fraction (convert to Complex) if (arguments.length === 2) { return signature1(arg0, convert7(arg1)); // signature: Complex, Fraction } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test5(arg1)) { // type: string (convert to Complex) if (arguments.length === 2) { return signature1(arg0, convert8(arg1)); // signature: Complex, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } } if (test2(arg0)) { // type: BigNumber if (test1(arg1)) { // type: Complex if (arguments.length === 2) { return signature1(convert6(arg0), arg1); // signature: BigNumber, Complex } ...
...
/**
* Divide two values, `x / y`.
* To divide matrices, `x` is multiplied with the inverse of `y`: `x * inv(y)`.
*
* Syntax:
*
* math.divide(x, y)
*
* Examples:
*
* math.divide(2, 3); // returns number 0.6666666666666666
*
* var a = math.complex(5, 14);
* var b = math.complex(4, 1);
...
function dot(arg0, arg1) { "use strict"; var name = 'dot'; if (test0(arg0)) { // type: Array if (test0(arg1)) { // type: Array if (arguments.length === 2) { return signature0(arg0, arg1); // signature: Array, Array } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test1(arg1)) { // type: Matrix if (arguments.length === 2) { return signature1(arg0, arg1); // signature: Array, Matrix } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'Array,Matrix'); } if (test1(arg0)) { // type: Matrix if (test0(arg1)) { // type: Array if (arguments.length === 2) { return signature2(arg0, arg1); // signature: Matrix, Array } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test1(arg1)) { // type: Matrix if (arguments.length === 2) { return signature3(arg0, arg1); // signature: Matrix, Matrix } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'Array,Matrix'); } throw createError(name, arguments.length, 0, arguments[0], 'Array,Matrix'); }
...
* Calculate the dot product of two vectors. The dot product of
* `A = [a1, a2, a3, ..., an]` and `B = [b1, b2, b3, ..., bn]` is defined as:
*
* dot(A, B) = a1 * b1 + a2 * b2 + a3 * b3 + ... + an * bn
*
* Syntax:
*
* math.dot(x, y)
*
* Examples:
*
* math.dot([2, 4, 1], [2, 2, 3]); // returns number 15
* math.multiply([2, 4, 1], [2, 2, 3]); // returns number 15
*
* See also:
...
function dotDivide(arg0, arg1) { "use strict"; var name = 'dotDivide'; if (test0(arg0)) { // type: Array if (test0(arg1)) { // type: Array if (arguments.length === 2) { return signature0(arg0, arg1); // signature: Array, Array } } if (test1(arg1)) { // type: Matrix if (arguments.length === 2) { return signature1(arg0, arg1); // signature: Array, Matrix } } // type: any if (arguments.length === 2) { return signature2(arg0, arg1); // signature: Array, any } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test1(arg0)) { // type: Matrix if (test0(arg1)) { // type: Array if (arguments.length === 2) { return signature3(arg0, arg1); // signature: Matrix, Array } } if (test1(arg1)) { // type: Matrix if (arguments.length === 2) { return signature4(arg0, arg1); // signature: Matrix, Matrix } } // type: any if (arguments.length === 2) { return signature5(arg0, arg1); // signature: Matrix, any } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } // type: any if (test0(arg1)) { // type: Array if (arguments.length === 2) { return signature6(arg0, arg1); // signature: any, Array } } if (test1(arg1)) { // type: Matrix if (arguments.length === 2) { return signature7(arg0, arg1); // signature: any, Matrix } } // type: any if (arguments.length === 2) { return signature8(arg0, arg1); // signature: any, any } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } throw createError(name, arguments.length, 1, arguments[1], 'Array,Matrix,any'); throw createError(name, arguments.length, 0, arguments[0], 'Array,Matrix,any'); }
...
/**
* Divide two matrices element wise. The function accepts both matrices and
* scalar values.
*
* Syntax:
*
* math.dotDivide(x, y)
*
* Examples:
*
* math.dotDivide(2, 4); // returns 0.5
*
* a = [[9, 5], [6, 1]];
* b = [[3, 2], [5, 2]];
...
function dotMultiply(arg0, arg1) { "use strict"; var name = 'dotMultiply'; if (test0(arg0)) { // type: Array if (test0(arg1)) { // type: Array if (arguments.length === 2) { return signature0(arg0, arg1); // signature: Array, Array } } if (test1(arg1)) { // type: Matrix if (arguments.length === 2) { return signature1(arg0, arg1); // signature: Array, Matrix } } // type: any if (arguments.length === 2) { return signature2(arg0, arg1); // signature: Array, any } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test1(arg0)) { // type: Matrix if (test0(arg1)) { // type: Array if (arguments.length === 2) { return signature3(arg0, arg1); // signature: Matrix, Array } } if (test1(arg1)) { // type: Matrix if (arguments.length === 2) { return signature4(arg0, arg1); // signature: Matrix, Matrix } } // type: any if (arguments.length === 2) { return signature5(arg0, arg1); // signature: Matrix, any } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } // type: any if (test0(arg1)) { // type: Array if (arguments.length === 2) { return signature6(arg0, arg1); // signature: any, Array } } if (test1(arg1)) { // type: Matrix if (arguments.length === 2) { return signature7(arg0, arg1); // signature: any, Matrix } } // type: any if (arguments.length === 2) { return signature8(arg0, arg1); // signature: any, any } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } throw createError(name, arguments.length, 1, arguments[1], 'Array,Matrix,any'); throw createError(name, arguments.length, 0, arguments[0], 'Array,Matrix,any'); }
...
/**
* Multiply two matrices element wise. The function accepts both matrices and
* scalar values.
*
* Syntax:
*
* math.dotMultiply(x, y)
*
* Examples:
*
* math.dotMultiply(2, 4); // returns 8
*
* a = [[9, 5], [6, 1]];
* b = [[3, 2], [5, 2]];
...
function dotPow(arg0, arg1) { "use strict"; var name = 'dotPow'; if (test0(arg0)) { // type: Array if (test0(arg1)) { // type: Array if (arguments.length === 2) { return signature0(arg0, arg1); // signature: Array, Array } } if (test1(arg1)) { // type: Matrix if (arguments.length === 2) { return signature1(arg0, arg1); // signature: Array, Matrix } } // type: any if (arguments.length === 2) { return signature2(arg0, arg1); // signature: Array, any } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test1(arg0)) { // type: Matrix if (test0(arg1)) { // type: Array if (arguments.length === 2) { return signature3(arg0, arg1); // signature: Matrix, Array } } if (test1(arg1)) { // type: Matrix if (arguments.length === 2) { return signature4(arg0, arg1); // signature: Matrix, Matrix } } // type: any if (arguments.length === 2) { return signature5(arg0, arg1); // signature: Matrix, any } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } // type: any if (test0(arg1)) { // type: Array if (arguments.length === 2) { return signature6(arg0, arg1); // signature: any, Array } } if (test1(arg1)) { // type: Matrix if (arguments.length === 2) { return signature7(arg0, arg1); // signature: any, Matrix } } // type: any if (arguments.length === 2) { return signature8(arg0, arg1); // signature: any, any } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } throw createError(name, arguments.length, 1, arguments[1], 'Array,Matrix,any'); throw createError(name, arguments.length, 0, arguments[0], 'Array,Matrix,any'); }
...
var algorithm14 = load(require('../../type/matrix/utils/algorithm14'));
/**
* Calculates the power of x to y element wise.
*
* Syntax:
*
* math.dotPow(x, y)
*
* Examples:
*
* math.dotPow(2, 3); // returns number 8
*
* var a = [[1, 2], [4, 3]];
* math.dotPow(a, 2); // returns Array [[1, 4], [16, 9]]
...
emit = function () { [native code] }
...
object.deepExtend(config, options);
var curr = object.clone(config);
var changes = object.clone(options);
// emit 'config' event
math.emit('config', curr, prev, changes);
return curr;
}
else {
return object.clone(config);
}
}
...
function equal(arg0, arg1) { "use strict"; var name = 'equal'; if (test0(arg0)) { // type: Array if (test0(arg1)) { // type: Array if (arguments.length === 2) { return signature0(arg0, arg1); // signature: Array, Array } } if (test1(arg1)) { // type: Matrix if (arguments.length === 2) { return signature1(arg0, arg1); // signature: Array, Matrix } } // type: any if (arguments.length === 2) { return signature2(arg0, arg1); // signature: Array, any } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test1(arg0)) { // type: Matrix if (test0(arg1)) { // type: Array if (arguments.length === 2) { return signature3(arg0, arg1); // signature: Matrix, Array } } if (test1(arg1)) { // type: Matrix if (arguments.length === 2) { return signature4(arg0, arg1); // signature: Matrix, Matrix } } // type: any if (arguments.length === 2) { return signature5(arg0, arg1); // signature: Matrix, any } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } // type: any if (test0(arg1)) { // type: Array if (arguments.length === 2) { return signature6(arg0, arg1); // signature: any, Array } } if (test1(arg1)) { // type: Matrix if (arguments.length === 2) { return signature7(arg0, arg1); // signature: any, Matrix } } // type: any if (arguments.length === 2) { return signature8(arg0, arg1); // signature: any, any } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } throw createError(name, arguments.length, 1, arguments[1], 'Array,Matrix,any'); throw createError(name, arguments.length, 0, arguments[0], 'Array,Matrix,any'); }
...
*
* math.deepEqual(2, 4); // returns false
*
* a = [2, 5, 1];
* b = [2, 7, 1];
*
* math.deepEqual(a, b); // returns false
* math.equal(a, b); // returns [true, false, true]
*
* See also:
*
* equal, unequal
*
* @param {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} x First matrix to compare
* @param {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} y Second matrix to compare
...
function erf(arg0) { "use strict"; var name = 'erf'; if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature0(arg0); // signature: number } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature1(arg0); // signature: BigNumber } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test2(arg0)) { // type: Array if (arguments.length === 1) { return signature2(arg0); // signature: Array } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test3(arg0)) { // type: Matrix if (arguments.length === 1) { return signature2(arg0); // signature: Matrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test4(arg0)) { // type: Fraction (convert to BigNumber) if (arguments.length === 1) { return signature1(convert0(arg0)); // signature: Fraction } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test5(arg0)) { // type: string (convert to number) if (arguments.length === 1) { return signature0(convert1(arg0)); // signature: string } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test6(arg0)) { // type: boolean (convert to number) if (arguments.length === 1) { return signature0(convert2(arg0)); // signature: boolean } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test7(arg0)) { // type: null (convert to number) if (arguments.length === 1) { return signature0(convert3(arg0)); // signature: null } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'number,BigNumber,Array,Matrix'); }
...
* "Rational Chebyshev Approximations for the Error Function" by W. J. Cody
* for an explanation of this process.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.erf(x)
*
* Examples:
*
* math.erf(0.2); // returns 0.22270258921047847
* math.erf(-0.5); // returns -0.5204998778130465
* math.erf(4); // returns 0.9999999845827421
*
...
function ArgumentsError(fn, count, min, max) { if (!(this instanceof ArgumentsError)) { throw new SyntaxError('Constructor must be called with the new operator'); } this.fn = fn; this.count = count; this.min = min; this.max = max; this.message = 'Wrong number of arguments in function ' + fn + ' (' + count + ' provided, ' + min + ((max != undefined) ? ('-' + max) : '') + ' expected)'; this.stack = (new Error()).stack; }
n/a
function Error() { [native code] }
n/a
function DimensionError(actual, expected, relation) { if (!(this instanceof DimensionError)) { throw new SyntaxError('Constructor must be called with the new operator'); } this.actual = actual; this.expected = expected; this.relation = relation; this.message = 'Dimension mismatch (' + (Array.isArray(actual) ? ('[' + actual.join(', ') + ']') : actual) + ' ' + (this.relation || '!=') + ' ' + (Array.isArray(expected) ? ('[' + expected.join(', ') + ']') : expected) + ')'; this.stack = (new Error()).stack; }
n/a
function IndexError(index, min, max) { if (!(this instanceof IndexError)) { throw new SyntaxError('Constructor must be called with the new operator'); } this.index = index; if (arguments.length < 3) { this.min = 0; this.max = min; } else { this.min = min; this.max = max; } if (this.min !== undefined && this.index < this.min) { this.message = 'Index out of range (' + this.index + ' < ' + this.min + ')'; } else if (this.max !== undefined && this.index >= this.max) { this.message = 'Index out of range (' + this.index + ' > ' + (this.max - 1) + ')'; } else { this.message = 'Index out of range (' + this.index + ')'; } this.stack = (new Error()).stack; }
n/a
function compile(arg0, arg1) { "use strict"; var name = 'compile'; if (test0(arg0)) { // type: string if (arguments.length === 1) { return signature0(arg0); // signature: string } if (test1(arg1)) { // type: Object if (arguments.length === 2) { return signature1(arg0, arg1); // signature: string, Object } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'Object'); } if (test2(arg0)) { // type: Array if (arguments.length === 1) { return signature2(arg0); // signature: Array } if (test1(arg1)) { // type: Object if (arguments.length === 2) { return signature3(arg0, arg1); // signature: Array, Object } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'Object'); } if (test3(arg0)) { // type: Matrix if (arguments.length === 1) { return signature2(arg0); // signature: Matrix } if (test1(arg1)) { // type: Object if (arguments.length === 2) { return signature3(arg0, arg1); // signature: Matrix, Object } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'Object'); } if (test4(arg0)) { // type: number (convert to string) if (arguments.length === 1) { return signature0(convert0(arg0)); // signature: number } if (test1(arg1)) { // type: Object if (arguments.length === 2) { return signature1(convert0(arg0), arg1); // signature: number, Object } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'Object'); } if (test5(arg0)) { // type: boolean (convert to string) if (arguments.length === 1) { return signature0(convert1(arg0)); // signature: boolean } if (test1(arg1)) { // type: Object if (arguments.length === 2) { return signature1(convert1(arg0), arg1); // signature: boolean, Object } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'Object'); } if (test6(arg0)) { // type: null (convert to string) if (arguments.length === 1) { return signature0(convert2(arg0)); // signature: null } if (test1(arg1)) { // type: Object if (arguments.length === 2) { return signature1(convert2(arg0), arg1); // signature: null, Object } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'Object'); } throw createError(name, arguments.length, 0, arguments[0], 'string,Array,Matrix'); }
...
math.atan2(3, -3) / math.pi; // 0.75
math.log(1000, 10); // 3
math.sqrt(-4); // 2i
math.pow([[-1, 2], [3, 1]], 2); // [[7, 0], [0, 7]]
math.derivative('x^2 + x', 'x'); // 2 * x + 1
// expressions
math.eval('12 / (2.3 + 0.7)'); // 4
math.eval('5.08 cm to inch'); // 2 inch
math.eval('sin(45 deg) ^ 2'); // 0.5
math.eval('9 / 3 + 2i'); // 3 + 2i
math.eval('det([-1, 2; 3, 1])'); // -7
// chaining
math.chain(3)
...
function exp(arg0) { "use strict"; var name = 'exp'; if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature0(arg0); // signature: number } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: Complex if (arguments.length === 1) { return signature1(arg0); // signature: Complex } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test2(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature2(arg0); // signature: BigNumber } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test3(arg0)) { // type: Array if (arguments.length === 1) { return signature3(arg0); // signature: Array } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test4(arg0)) { // type: Matrix if (arguments.length === 1) { return signature3(arg0); // signature: Matrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test5(arg0)) { // type: Fraction (convert to BigNumber) if (arguments.length === 1) { return signature2(convert0(arg0)); // signature: Fraction } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test6(arg0)) { // type: string (convert to number) if (arguments.length === 1) { return signature0(convert1(arg0)); // signature: string } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test7(arg0)) { // type: boolean (convert to number) if (arguments.length === 1) { return signature0(convert2(arg0)); // signature: boolean } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test8(arg0)) { // type: null (convert to number) if (arguments.length === 1) { return signature0(convert3(arg0)); // signature: null } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'number,Complex,BigNumber,Array,Matrix'); }
...
// https://www.wikiwand.com/en/Cube_root#/Complex_numbers
var arg_3 = x.arg() / 3;
var abs = x.abs();
// principal root:
var principal = new type.Complex(_cbrtNumber(abs), 0).mul(
new type.Complex(0, arg_3).exp());
if (allRoots) {
var all = [
principal,
new type.Complex(_cbrtNumber(abs), 0).mul(
new type.Complex(0, arg_3 + Math.PI * 2 / 3).exp()),
new type.Complex(_cbrtNumber(abs), 0).mul(
...
function Parser() { if (!(this instanceof Parser)) { throw new SyntaxError( 'Constructor must be called with the new operator'); } this.scope = {}; }
n/a
function parse(expr, options) { if (arguments.length != 1 && arguments.length != 2) { throw new ArgumentsError('parse', arguments.length, 1, 2); } // pass extra nodes extra_nodes = (options && options.nodes) ? options.nodes : {}; if (typeof expr === 'string') { // parse a single expression expression = expr; return parseStart(); } else if (Array.isArray(expr) || expr instanceof type.Matrix) { // parse an array or matrix with expressions return deepMap(expr, function (elem) { if (typeof elem !== 'string') throw new TypeError('String expected'); expression = elem; return parseStart(); }); } else { // oops throw new TypeError('String or matrix expected'); } }
n/a
function eye(arg0, arg1, arg2) { "use strict"; var name = 'eye'; if (arguments.length === 0) { return signature0(); // signature: } if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature1(arg0); // signature: number } if (test0(arg1)) { // type: number if (arguments.length === 2) { return signature2(arg0, arg1); // signature: number, number } if (test1(arg2)) { // type: string if (arguments.length === 3) { return signature3(arg0, arg1, arg2); // signature: number, number, string } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } if (test0(arg2)) { // type: number (convert to string) if (arguments.length === 3) { return signature3(arg0, arg1, convert0(arg2)); // signature: number, number, number } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } if (test2(arg2)) { // type: boolean (convert to string) if (arguments.length === 3) { return signature3(arg0, arg1, convert1(arg2)); // signature: number, number, boolean } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } if (test3(arg2)) { // type: null (convert to string) if (arguments.length === 3) { return signature3(arg0, arg1, convert2(arg2)); // signature: number, number, null } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } throw createError(name, arguments.length, 2, arguments[2], 'string'); } if (test4(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature2(arg0, arg1); // signature: number, BigNumber } if (test1(arg2)) { // type: string if (arguments.length === 3) { return signature3(arg0, arg1, arg2); // signature: number, BigNumber, string } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } if (test0(arg2)) { // type: number (convert to string) if (arguments.length === 3) { return signature3(arg0, arg1, convert0(arg2)); // signature: number, BigNumber, number } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } if (test2(arg2)) { // type: boolean (convert to string) if (arguments.length === 3) { return signature3(arg0, arg1, convert1(arg2)); // signature: number, BigNumber, boolean } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } if (test3(arg2)) { // type: null (convert to string) if (arguments.length === 3) { return signature3(arg0, arg1, convert2(arg2)); // signature: number, BigNumber, null } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } throw createError(name, arguments.length, 2, arguments[2], 'string'); } if (test1(arg1)) { // type: string if (arguments.length === 2) { return signature4(arg0, arg1); // signature: number, string } if (test1(arg2)) { // type: string if (arguments.length === 3) { return signature3(arg0, convert3(arg1), arg2); // signature: number, string, string } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } if (test0(arg2)) { // type: number (convert to string) if (arguments.length === 3) { return signature3(arg0, convert3(arg1), convert0(arg2)); // signature: number, string, number } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } ...
...
/**
* Create a 2-dimensional identity matrix with size m x n or n x n.
* The matrix has ones on the diagonal and zeros elsewhere.
*
* Syntax:
*
* math.eye(n)
* math.eye(n, format)
* math.eye(m, n)
* math.eye(m, n, format)
* math.eye([m, n])
* math.eye([m, n], format)
*
* Examples:
...
function factorial(arg0) { "use strict"; var name = 'factorial'; if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature0(arg0); // signature: number } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature1(arg0); // signature: BigNumber } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test2(arg0)) { // type: Array if (arguments.length === 1) { return signature2(arg0); // signature: Array } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test3(arg0)) { // type: Matrix if (arguments.length === 1) { return signature2(arg0); // signature: Matrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test4(arg0)) { // type: Fraction (convert to BigNumber) if (arguments.length === 1) { return signature1(convert0(arg0)); // signature: Fraction } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test5(arg0)) { // type: string (convert to number) if (arguments.length === 1) { return signature0(convert1(arg0)); // signature: string } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test6(arg0)) { // type: boolean (convert to number) if (arguments.length === 1) { return signature0(convert2(arg0)); // signature: boolean } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test7(arg0)) { // type: null (convert to number) if (arguments.length === 1) { return signature0(convert3(arg0)); // signature: null } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'number,BigNumber,Array,Matrix'); }
...
* Compute the factorial of a value
*
* Factorial only supports an integer value as argument.
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.factorial(n)
*
* Examples:
*
* math.factorial(5); // returns 120
* math.factorial(3); // returns 6
*
* See also:
...
function filter(arg0, arg1) { "use strict"; var name = 'filter'; if (test0(arg0)) { // type: Array if (test1(arg1)) { // type: function if (arguments.length === 2) { return signature0(arg0, arg1); // signature: Array, function } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: RegExp if (arguments.length === 2) { return signature1(arg0, arg1); // signature: Array, RegExp } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'function,RegExp'); } if (test3(arg0)) { // type: Matrix if (test1(arg1)) { // type: function if (arguments.length === 2) { return signature2(arg0, arg1); // signature: Matrix, function } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: RegExp if (arguments.length === 2) { return signature3(arg0, arg1); // signature: Matrix, RegExp } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'function,RegExp'); } throw createError(name, arguments.length, 0, arguments[0], 'Array,Matrix'); }
...
}
}
}
}
}
// remove duplicates
matches = matches.filter(function(elem, pos, arr) {
return arr.indexOf(elem) == pos;
});
}
return [matches, keyword];
}
...
function fix(arg0) { "use strict"; var name = 'fix'; if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature0(arg0); // signature: number } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: Complex if (arguments.length === 1) { return signature1(arg0); // signature: Complex } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test2(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature2(arg0); // signature: BigNumber } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test3(arg0)) { // type: Fraction if (arguments.length === 1) { return signature3(arg0); // signature: Fraction } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test4(arg0)) { // type: Array if (arguments.length === 1) { return signature4(arg0); // signature: Array } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test5(arg0)) { // type: Matrix if (arguments.length === 1) { return signature4(arg0); // signature: Matrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test6(arg0)) { // type: string (convert to number) if (arguments.length === 1) { return signature0(convert0(arg0)); // signature: string } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test7(arg0)) { // type: boolean (convert to number) if (arguments.length === 1) { return signature0(convert1(arg0)); // signature: boolean } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test8(arg0)) { // type: null (convert to number) if (arguments.length === 1) { return signature0(convert2(arg0)); // signature: null } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'number,Complex,BigNumber,Fraction,Array,Matrix'); }
...
function factory (type, config, load, typed) {
/**
* Round a value towards zero.
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.fix(x)
*
* Examples:
*
* math.fix(3.2); // returns number 3
* math.fix(3.8); // returns number 3
* math.fix(-4.2); // returns number -4
* math.fix(-4.7); // returns number -4
...
function flatten(arg0) { "use strict"; var name = 'flatten'; if (test0(arg0)) { // type: Array if (arguments.length === 1) { return signature0(arg0); // signature: Array } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: Matrix if (arguments.length === 1) { return signature1(arg0); // signature: Matrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'Array,Matrix'); }
...
* @returns {Array} Array whose data has been formatted to fit the
* specified dimensions
*
* @throws {DimensionError} If the product of the new dimension sizes does
* not equal that of the old ones
*/
exports.reshape = function(array, sizes) {
var flatArray = exports.flatten(array);
var newArray;
var product = function (arr) {
return arr.reduce(function (prev, curr) {
return prev * curr;
});
};
...
function floor(arg0) { "use strict"; var name = 'floor'; if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature0(arg0); // signature: number } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: Complex if (arguments.length === 1) { return signature1(arg0); // signature: Complex } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test2(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature2(arg0); // signature: BigNumber } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test3(arg0)) { // type: Fraction if (arguments.length === 1) { return signature3(arg0); // signature: Fraction } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test4(arg0)) { // type: Array if (arguments.length === 1) { return signature4(arg0); // signature: Array } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test5(arg0)) { // type: Matrix if (arguments.length === 1) { return signature4(arg0); // signature: Matrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test6(arg0)) { // type: string (convert to number) if (arguments.length === 1) { return signature0(convert0(arg0)); // signature: string } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test7(arg0)) { // type: boolean (convert to number) if (arguments.length === 1) { return signature0(convert1(arg0)); // signature: boolean } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test8(arg0)) { // type: null (convert to number) if (arguments.length === 1) { return signature0(convert2(arg0)); // signature: null } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'number,Complex,BigNumber,Fraction,Array,Matrix'); }
...
* ceil, floor, round
*
* @param {number | BigNumber | Fraction | Complex | Array | Matrix} x Number to be rounded
* @return {number | BigNumber | Fraction | Complex | Array | Matrix} Rounded value
*/
var fix = typed('fix', {
'number': function (x) {
return (x > 0) ? Math.floor(x) : Math.ceil(x);
},
'Complex': function (x) {
return new type.Complex(
(x.re > 0) ? Math.floor(x.re) : Math.ceil(x.re),
(x.im > 0) ? Math.floor(x.im) : Math.ceil(x.im)
);
...
function forEach(arg0, arg1) { "use strict"; var name = 'forEach'; if (test0(arg0)) { // type: Array if (test1(arg1)) { // type: function if (arguments.length === 2) { return signature0(arg0, arg1); // signature: Array, function } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'function'); } if (test2(arg0)) { // type: Matrix if (test1(arg1)) { // type: function if (arguments.length === 2) { return signature1(arg0, arg1); // signature: Matrix, function } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'function'); } throw createError(name, arguments.length, 0, arguments[0], 'Array,Matrix'); }
...
if (def.indexOf(keyword) == 0) {
matches.push(def);
}
}
}
// commandline keywords
['exit', 'quit', 'clear'].forEach(function (cmd) {
if (cmd.indexOf(keyword) == 0) {
matches.push(cmd);
}
});
// math functions and constants
var ignore = ['expr', 'type'];
...
function format(arg0, arg1) { "use strict"; var name = 'format'; // type: any if (arguments.length === 1) { return signature0(arg0); // signature: any } if (test0(arg1)) { // type: number if (arguments.length === 2) { return signature0(arg0, arg1); // signature: any, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test1(arg1)) { // type: function if (arguments.length === 2) { return signature0(arg0, arg1); // signature: any, function } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: string (convert to number) if (arguments.length === 2) { return signature0(arg0, convert0(arg1)); // signature: any, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: boolean (convert to number) if (arguments.length === 2) { return signature0(arg0, convert1(arg1)); // signature: any, boolean } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test4(arg1)) { // type: null (convert to number) if (arguments.length === 2) { return signature0(arg0, convert2(arg1)); // signature: any, null } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test5(arg1)) { // type: Object if (arguments.length === 2) { return signature0(arg0, arg1); // signature: any, Object } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'number,function,Object'); throw createError(name, arguments.length, 0, arguments[0], 'any'); }
...
* Helper function to format a value. Regular numbers will be rounded
* to 14 digits to prevent round-off errors from showing up.
* @param {*} value
*/
function format(value) {
var math = getMath();
return math.format(value, {
fn: function (value) {
if (typeof value === 'number') {
// round numbers
return math.format(value, PRECISION);
}
else {
return math.format(value);
...
function fraction(arg0, arg1) { "use strict"; var name = 'fraction'; if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature0(arg0); // signature: number } if (test0(arg1)) { // type: number if (arguments.length === 2) { return signature1(arg0, arg1); // signature: number, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test1(arg1)) { // type: string (convert to number) if (arguments.length === 2) { return signature1(arg0, convert0(arg1)); // signature: number, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: boolean (convert to number) if (arguments.length === 2) { return signature1(arg0, convert1(arg1)); // signature: number, boolean } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: null (convert to number) if (arguments.length === 2) { return signature1(arg0, convert2(arg1)); // signature: number, null } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'number'); } if (test4(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature2(arg0); // signature: BigNumber } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test5(arg0)) { // type: Fraction if (arguments.length === 1) { return signature3(arg0); // signature: Fraction } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: string if (arguments.length === 1) { return signature4(arg0); // signature: string } if (test0(arg1)) { // type: number if (arguments.length === 2) { return signature1(convert0(arg0), arg1); // signature: string, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test1(arg1)) { // type: string (convert to number) if (arguments.length === 2) { return signature1(convert0(arg0), convert0(arg1)); // signature: string, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: boolean (convert to number) if (arguments.length === 2) { return signature1(convert0(arg0), convert1(arg1)); // signature: string, boolean } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: null (convert to number) if (arguments.length === 2) { return signature1(convert0(arg0), convert2(arg1)); // signature: string, null } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'number'); } if (test6(arg0)) { // type: Array if (arguments.length === 1) { return signature5(arg0); // signature: Array } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test7(arg0)) { // type: Matrix if (arguments.length === 1) { return signature5(arg0); // signature: Matrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test2(arg0)) { // type: boolean (convert to number) if (arguments.length === 1) { return signature0(convert1(arg0)); // signature: boolean } if (test0(arg1)) { // type: number if (arguments.length === 2) { return signature1(convert1(arg0), arg1); // signature: bo ...
...
case 'number':
// TODO: replace this with using config.number
var numConfig = defs.math.config().number;
if (numConfig === 'BigNumber') {
return 'math.bignumber("' + this.value + '")';
}
else if (numConfig === 'Fraction') {
return 'math.fraction("' + this.value + '")';
}
else {
// remove leading zeros like '003.2' which are not allowed by JavaScript
return this.value.replace(/^(0*)[0-9]/, function (match, zeros) {
return match.substring(zeros.length);
});
}
...
function gamma(arg0) { "use strict"; var name = 'gamma'; if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature0(arg0); // signature: number } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: Complex if (arguments.length === 1) { return signature1(arg0); // signature: Complex } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test2(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature2(arg0); // signature: BigNumber } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test3(arg0)) { // type: Array if (arguments.length === 1) { return signature3(arg0); // signature: Array } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test4(arg0)) { // type: Matrix if (arguments.length === 1) { return signature3(arg0); // signature: Matrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test5(arg0)) { // type: Fraction (convert to BigNumber) if (arguments.length === 1) { return signature2(convert0(arg0)); // signature: Fraction } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test6(arg0)) { // type: string (convert to number) if (arguments.length === 1) { return signature0(convert1(arg0)); // signature: string } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test7(arg0)) { // type: boolean (convert to number) if (arguments.length === 1) { return signature0(convert2(arg0)); // signature: boolean } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test8(arg0)) { // type: null (convert to number) if (arguments.length === 1) { return signature0(convert3(arg0)); // signature: null } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'number,Complex,BigNumber,Array,Matrix'); }
...
* Compute the gamma function of a value using Lanczos approximation for
* small values, and an extended Stirling approximation for large values.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.gamma(n)
*
* Examples:
*
* math.gamma(5); // returns 24
* math.gamma(-0.5); // returns -3.5449077018110335
* math.gamma(math.i); // returns -0.15494982830180973 - 0.49801566811835596i
*
...
function gcd(arg0, arg1, arg2) { "use strict"; var name = 'gcd'; if (test0(arg0)) { // type: number if (test0(arg1)) { // type: number if (arguments.length === 2) { return signature0(arg0, arg1); // signature: number, number } if (test1(arg2) || test2(arg2) || test0(arg2) || test3(arg2)) { // type: ...Array|Matrix|number|BigNumber var varArgs = [arg2]; for (var i = 3; i < arguments.length; i++) { if (test1(arguments[i]) || test2(arguments[i]) || test0(arguments[i]) || test3(arguments[i])) { varArgs.push(arguments[i]); } else { throw createError(name, arguments.length, i, arguments[i], 'Array,Matrix,number,BigNumber'); } } return signature1(arg0, arg1, varArgs); // signature: number, number, ...Array|Matrix|number|BigNumber } throw createError(name, arguments.length, 2, arguments[2], 'Array,Matrix,number,BigNumber'); } if (test3(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature2(convert0(arg0), arg1); // signature: number, BigNumber } if (test1(arg2) || test2(arg2) || test0(arg2) || test3(arg2)) { // type: ...Array|Matrix|number|BigNumber var varArgs = [arg2]; for (var i = 3; i < arguments.length; i++) { if (test1(arguments[i]) || test2(arguments[i]) || test0(arguments[i]) || test3(arguments[i])) { varArgs.push(arguments[i]); } else { throw createError(name, arguments.length, i, arguments[i], 'Array,Matrix,number,BigNumber'); } } return signature1(arg0, arg1, varArgs); // signature: number, BigNumber, ...Array|Matrix|number|BigNumber } throw createError(name, arguments.length, 2, arguments[2], 'Array,Matrix,number,BigNumber'); } if (test4(arg1)) { // type: Fraction if (arguments.length === 2) { return signature3(convert1(arg0), arg1); // signature: number, Fraction } if (test1(arg2) || test2(arg2) || test0(arg2) || test3(arg2)) { // type: ...Array|Matrix|number|BigNumber var varArgs = [arg2]; for (var i = 3; i < arguments.length; i++) { if (test1(arguments[i]) || test2(arguments[i]) || test0(arguments[i]) || test3(arguments[i])) { varArgs.push(arguments[i]); } else { throw createError(name, arguments.length, i, arguments[i], 'Array,Matrix,number,BigNumber'); } } return signature1(arg0, convert2(arg1), varArgs); // signature: number, Fraction, ...Array|Matrix|number|BigNumber } throw createError(name, arguments.length, 2, arguments[2], 'Array,Matrix,number,BigNumber'); } if (test1(arg1)) { // type: Array if (arguments.length === 2) { return signature4(arg0, arg1); // signature: number, Array } if (test1(arg2) || test2(arg2) || test0(arg2) || test3(arg2)) { // type: ...Array|Matrix|number|BigNumber var varArgs = [arg2]; for (var i = 3; i < arguments.length; i++) { if (test1(arguments[i]) || test2(arguments[i]) || test0(arguments[i]) || test3(arguments[i])) { varArgs.push(arguments[i]); } else { throw createError(name, arguments.length, i, arguments[i], 'Array,Matrix,number,BigNumber'); } } return signature1(arg0, arg1, varArgs); // signature: number, Array, ...Array|Matrix|number|BigNumber } throw createError(name, arguments.length, 2, arguments[2], 'Array,Matrix,number,BigNumber'); } if (test2(arg1)) { // type: Matrix if (arguments.length === 2) { return signature5(arg0, arg1); // signature: number, Matrix } if (test1(arg2) || test2(arg2) || test0(arg2) || test3(arg2)) { // type: ...Array|Matrix|number|BigNumber var varArgs = [arg2]; for (var i = 3; i < arguments.length; i++) { if (test1(arguments[i]) || test2(arguments[i]) || test0(arguments[i]) || test3(arguments[i])) { varArgs.push(arguments[i]); ...
...
/**
* Calculate the greatest common divisor for two or more values or arrays.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.gcd(a, b)
* math.gcd(a, b, c, ...)
*
* Examples:
*
* math.gcd(8, 12); // returns 4
* math.gcd(-4, 6); // returns 2
* math.gcd(25, 15, -10); // returns 5
...
function help(arg0) { "use strict"; var name = 'help'; // type: any if (arguments.length === 1) { return signature0(arg0); // signature: any } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } throw createError(name, arguments.length, 0, arguments[0], 'any'); }
...
* Object | `'Object'` | `math.typeof ({a: 2, b: 3})`
* RegExp | `'RegExp'` | `math.typeof (/a regexp/)`
* undefined | `'undefined'` | `math.typeof(undefined)`
* math.type.BigNumber | `'BigNumber'` | `math.typeof (math.bignumber('2.3e500'))`
* math.type.Chain | `'Chain'` | `math.typeof (math.chain(2))`
* math.type.Complex | `'Complex'` | `math.typeof (math.complex(2, 3))`
* math.type.Fraction | `'Fraction'` | `math.typeof (math.fraction(1, 3))`
* math.type.Help | `'Help'` | `math.typeof (math.help('sqrt
'))`
* math.type.Index | `'Index'` | `math.typeof (math.index(1, 3))`
* math.type.Matrix | `'Matrix'` | `math.typeof (math.matrix([[1,2], [3, 4]]))`
* math.type.Range | `'Range'` | `math.typeof (math.range(0, 10))`
* math.type.Unit | `'Unit'` | `math.typeof (math.unit('45 deg'))`
*
* Syntax:
*
...
function hypot(arg0) { "use strict"; var name = 'hypot'; if (test0(arg0)) { // type: Array if (arguments.length === 1) { return signature0(arg0); // signature: Array } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: Matrix if (arguments.length === 1) { return signature1(arg0); // signature: Matrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test2(arg0) || test3(arg0) || test4(arg0) || test5(arg0) || test5(arg0) || test6(arg0) || test6(arg0) || test7(arg0) || test7 (arg0)) { // type: ...number|BigNumber|Fraction|string|boolean|null var varArgs = [arg0]; for (var i = 1; i < arguments.length; i++) { if (test2(arguments[i]) || test3(arguments[i])) { varArgs.push(arguments[i]); } else if (test4(arguments[i])) { varArgs.push(convert0(arguments[i])); } else if (test5(arguments[i])) { varArgs.push(convert1(arguments[i])); } else if (test5(arguments[i])) { varArgs.push(convert2(arguments[i])); } else if (test6(arguments[i])) { varArgs.push(convert3(arguments[i])); } else if (test6(arguments[i])) { varArgs.push(convert4(arguments[i])); } else if (test7(arguments[i])) { varArgs.push(convert5(arguments[i])); } else if (test7(arguments[i])) { varArgs.push(convert6(arguments[i])); } else { throw createError(name, arguments.length, i, arguments[i], 'number,BigNumber'); } } return signature2(varArgs); // signature: ...number|BigNumber|Fraction|string|boolean|null } throw createError(name, arguments.length, 0, arguments[0], 'Array,Matrix,number,BigNumber'); }
...
*
* hypot(a, b, c, ...) = sqrt(a^2 + b^2 + c^2 + ...)
*
* For matrix input, the hypotenusa is calculated for all values in the matrix.
*
* Syntax:
*
* math.hypot(a, b, ...)
* math.hypot([a, b, c, ...])
*
* Examples:
*
* math.hypot(3, 4); // 5
* math.hypot(3, 4, 5); // 7.0710678118654755
* math.hypot([3, 4, 5]); // 7.0710678118654755
...
function im(arg0) { "use strict"; var name = 'im'; if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature0(arg0); // signature: number } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: Complex if (arguments.length === 1) { return signature1(arg0); // signature: Complex } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test2(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature2(arg0); // signature: BigNumber } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test3(arg0)) { // type: Array if (arguments.length === 1) { return signature3(arg0); // signature: Array } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test4(arg0)) { // type: Matrix if (arguments.length === 1) { return signature3(arg0); // signature: Matrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test5(arg0)) { // type: Fraction (convert to BigNumber) if (arguments.length === 1) { return signature2(convert0(arg0)); // signature: Fraction } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test6(arg0)) { // type: string (convert to number) if (arguments.length === 1) { return signature0(convert1(arg0)); // signature: string } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test7(arg0)) { // type: boolean (convert to number) if (arguments.length === 1) { return signature0(convert2(arg0)); // signature: boolean } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test8(arg0)) { // type: null (convert to number) if (arguments.length === 1) { return signature0(convert3(arg0)); // signature: null } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'number,Complex,BigNumber,Array,Matrix'); }
...
* Get the imaginary part of a complex number.
* For a complex number `a + bi`, the function returns `b`.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.im(x)
*
* Examples:
*
* var a = math.complex(2, 3);
* math.re(a); // returns number 2
* math.im(a); // returns number 3
*
...
function math_import(object, options) { var num = arguments.length; if (num !== 1 && num !== 2) { throw new ArgumentsError('import', num, 1, 2); } if (!options) { options = {}; } if (isFactory(object)) { _importFactory(object, options); } // TODO: allow a typed-function with name too else if (Array.isArray(object)) { object.forEach(function (entry) { math_import(entry, options); }); } else if (typeof object === 'object') { // a map with functions for (var name in object) { if (object.hasOwnProperty(name)) { var value = object[name]; if (isSupportedType(value)) { _import(name, value, options); } else if (isFactory(object)) { _importFactory(object, options); } else { math_import(value, options); } } } } else { if (!options.silent) { throw new TypeError('Factory, Object, or Array expected'); } } }
...
function factory (type, config, load, typed, math) {
/**
* Import functions from an object or a module
*
* Syntax:
*
* math.import(object)
* math.import(object, options)
*
* Where:
*
* - `object: Object`
* An object with functions to be imported.
* - `options: Object` An object with import options. Available options:
...
function index(arg0) { "use strict"; var name = 'index'; if (test0(arg0) || test1(arg0) || test2(arg0) || test3(arg0) || test4(arg0) || test5(arg0) || test6(arg0) || test7(arg0) || test7 (arg0) || test7(arg0) || test8(arg0) || test8(arg0) || test8(arg0)) { // type: ...number|string|BigNumber|Range|Array|Matrix|Fraction |boolean|null var varArgs = [arg0]; for (var i = 1; i < arguments.length; i++) { if (test0(arguments[i]) || test1(arguments[i]) || test2(arguments[i]) || test3(arguments[i]) || test4(arguments[i]) || test5 (arguments[i])) { varArgs.push(arguments[i]); } else if (test6(arguments[i])) { varArgs.push(convert0(arguments[i])); } else if (test7(arguments[i])) { varArgs.push(convert1(arguments[i])); } else if (test7(arguments[i])) { varArgs.push(convert2(arguments[i])); } else if (test7(arguments[i])) { varArgs.push(convert3(arguments[i])); } else if (test8(arguments[i])) { varArgs.push(convert4(arguments[i])); } else if (test8(arguments[i])) { varArgs.push(convert5(arguments[i])); } else if (test8(arguments[i])) { varArgs.push(convert6(arguments[i])); } else { throw createError(name, arguments.length, i, arguments[i], 'number,string,BigNumber,Range,Array,Matrix'); } } return signature0(varArgs); // signature: ...number|string|BigNumber|Range|Array|Matrix|Fraction|boolean|null } throw createError(name, arguments.length, 0, arguments[0], 'number,string,BigNumber,Range,Array,Matrix'); }
...
'})()'
}
else { // ConstantNode
return range._compile(defs, childArgs);
}
});
return 'math.index(' + dimensions.join(', ') + ')';
};
/**
* Execute a callback for each of the child nodes of this node
* @param {function(child: Node, path: string, parent: Node)} callback
*/
IndexNode.prototype.forEach = function (callback) {
...
function intersect(arg0, arg1, arg2, arg3) { "use strict"; var name = 'intersect'; if (test0(arg0)) { // type: Array if (test0(arg1)) { // type: Array if (test0(arg2)) { // type: Array if (arguments.length === 3) { return signature0(arg0, arg1, arg2); // signature: Array, Array, Array } if (test0(arg3)) { // type: Array if (arguments.length === 4) { return signature1(arg0, arg1, arg2, arg3); // signature: Array, Array, Array, Array } if (arguments.length > 4) { throw createError(name, arguments.length, 4, arguments[4]); } } if (test1(arg3)) { // type: Matrix (convert to Array) if (arguments.length === 4) { return signature1(arg0, arg1, arg2, convert0(arg3)); // signature: Array, Array, Array, Matrix } if (arguments.length > 4) { throw createError(name, arguments.length, 4, arguments[4]); } } throw createError(name, arguments.length, 3, arguments[3], 'Array'); } if (test1(arg2)) { // type: Matrix (convert to Array) if (arguments.length === 3) { return signature0(arg0, arg1, convert0(arg2)); // signature: Array, Array, Matrix } if (test0(arg3)) { // type: Array if (arguments.length === 4) { return signature1(arg0, arg1, convert0(arg2), arg3); // signature: Array, Array, Matrix, Array } if (arguments.length > 4) { throw createError(name, arguments.length, 4, arguments[4]); } } if (test1(arg3)) { // type: Matrix (convert to Array) if (arguments.length === 4) { return signature1(arg0, arg1, convert0(arg2), convert0(arg3)); // signature: Array, Array, Matrix, Matrix } if (arguments.length > 4) { throw createError(name, arguments.length, 4, arguments[4]); } } throw createError(name, arguments.length, 3, arguments[3], 'Array'); } throw createError(name, arguments.length, 2, arguments[2], 'Array'); } if (test1(arg1)) { // type: Matrix if (test0(arg2)) { // type: Array if (arguments.length === 3) { return signature0(arg0, convert0(arg1), arg2); // signature: Array, Matrix, Array } if (test0(arg3)) { // type: Array if (arguments.length === 4) { return signature1(arg0, convert0(arg1), arg2, arg3); // signature: Array, Matrix, Array, Array } if (arguments.length > 4) { throw createError(name, arguments.length, 4, arguments[4]); } } if (test1(arg3)) { // type: Matrix (convert to Array) if (arguments.length === 4) { return signature1(arg0, convert0(arg1), arg2, convert0(arg3)); // signature: Array, Matrix, Array, Matrix } if (arguments.length > 4) { throw createError(name, arguments.length, 4, arguments[4]); } } throw createError(name, arguments.length, 3, arguments[3], 'Array'); } if (test1(arg2)) { // type: Matrix if (arguments.length === 3) { return signature2(convert1(arg0), arg1, arg2); // signature: Array, Matrix, Matrix } if (test0(arg3)) { // type: Array if (arguments.length === 4) { return signature1(arg0, convert0(arg1), convert0(arg2), arg3); // signature: Array, Matrix, Matrix, Array } if (arguments.length > 4) { throw createError(name, arguments.length, 4, arguments[4]); } } if (test1(arg3)) { // type: Matrix if (arguments.length === 4) { return signature3(convert1(arg0), arg1, arg2, arg3); // signature: Array, Matrix, Matrix, Matrix } if (arguments.length > 4) { throw createError(name, arguments.length, 4, arguments[4]); } } throw createError(name, arguments.length, 3, arguments[3], 'Array,Matrix ...
...
* arrays or 1 dimensional matrices. The line intersection functions return null
* if the lines do not meet.
*
* Note: Fill the plane coefficients as `x + y + z = c` and not as `x + y + z + c = 0`.
*
* Syntax:
*
* math.intersect(endPoint1Line1, endPoint2Line1, endPoint1Line2, endPoint2Line2)
* math.intersect(endPoint1, endPoint2, planeCoefficients)
*
* Examples:
*
* math.intersect([0, 0], [10, 10], [10, 0], [0, 10]); // Returns [5, 5]
* math.intersect([0, 0, 0], [10, 10, 0], [10, 0, 0], [0, 10, 0]); // Returns [5, 5, 0]
* math.intersect([1, 0, 1], [4, -2, 2], [1, 1, 1, 6]); // Returns [7, -4, 3]
...
function inv(arg0) { "use strict"; var name = 'inv'; if (test0(arg0)) { // type: Array if (arguments.length === 1) { return signature0(arg0); // signature: Array } } if (test1(arg0)) { // type: Matrix if (arguments.length === 1) { return signature0(arg0); // signature: Matrix } } // type: any if (arguments.length === 1) { return signature1(arg0); // signature: any } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } throw createError(name, arguments.length, 0, arguments[0], 'Array,Matrix,any'); }
...
var eye = load(require('./eye'));
/**
* Calculate the inverse of a square matrix.
*
* Syntax:
*
* math.inv(x)
*
* Examples:
*
* math.inv([[1, 2], [3, 4]]); // returns [[-2, 1], [1.5, -0.5]]
* math.inv(4); // returns 0.25
* 1 / 4; // returns 0.25
*
...
function isInteger(arg0) { "use strict"; var name = 'isInteger'; if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature0(arg0); // signature: number } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature1(arg0); // signature: BigNumber } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test2(arg0)) { // type: Fraction if (arguments.length === 1) { return signature2(arg0); // signature: Fraction } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test3(arg0)) { // type: Array if (arguments.length === 1) { return signature3(arg0); // signature: Array } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test4(arg0)) { // type: Matrix if (arguments.length === 1) { return signature3(arg0); // signature: Matrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test5(arg0)) { // type: string (convert to number) if (arguments.length === 1) { return signature0(convert0(arg0)); // signature: string } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test6(arg0)) { // type: boolean (convert to number) if (arguments.length === 1) { return signature0(convert1(arg0)); // signature: boolean } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test7(arg0)) { // type: null (convert to number) if (arguments.length === 1) { return signature0(convert2(arg0)); // signature: null } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'number,BigNumber,Fraction,Array,Matrix'); }
...
/**
* Test whether index is an integer number with index >= 0 and index < length
* when length is provided
* @param {number} index Zero-based index
* @param {number} [length] Length of the array
*/
exports.validateIndex = function(index, length) {
if (!number.isNumber(index) || !number.isInteger(index)) {
throw new TypeError('Index must be an integer (value: ' + index + ')');
}
if (index < 0 || (typeof length === 'number' && index >= length)) {
throw new IndexError(index, length);
}
};
...
function isNaN(arg0) { "use strict"; var name = 'isNaN'; if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature0(arg0); // signature: number } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: Complex if (arguments.length === 1) { return signature1(arg0); // signature: Complex } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test2(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature2(arg0); // signature: BigNumber } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test3(arg0)) { // type: Fraction if (arguments.length === 1) { return signature3(arg0); // signature: Fraction } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test4(arg0)) { // type: Unit if (arguments.length === 1) { return signature4(arg0); // signature: Unit } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test5(arg0)) { // type: Array if (arguments.length === 1) { return signature5(arg0); // signature: Array } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test6(arg0)) { // type: Matrix if (arguments.length === 1) { return signature5(arg0); // signature: Matrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test7(arg0)) { // type: string (convert to number) if (arguments.length === 1) { return signature0(convert0(arg0)); // signature: string } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test8(arg0)) { // type: boolean (convert to number) if (arguments.length === 1) { return signature0(convert1(arg0)); // signature: boolean } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test9(arg0)) { // type: null (convert to number) if (arguments.length === 1) { return signature0(convert2(arg0)); // signature: null } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'number,Complex,BigNumber,Fraction,Unit,Array,Matrix'); }
...
},
'Complex, Complex': function (x, y) {
return (x.re !== 0 || x.im !== 0) && (y.re !== 0 || y.im !== 0);
},
'BigNumber, BigNumber': function (x, y) {
return !x.isZero() && !y.isZero() && !x.isNaN() && !y
.isNaN();
},
'Unit, Unit': function (x, y) {
return and(x.value, y.value);
},
'Matrix, Matrix': function (x, y) {
...
function isNegative(arg0) { "use strict"; var name = 'isNegative'; if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature0(arg0); // signature: number } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature1(arg0); // signature: BigNumber } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test2(arg0)) { // type: Fraction if (arguments.length === 1) { return signature2(arg0); // signature: Fraction } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test3(arg0)) { // type: Unit if (arguments.length === 1) { return signature3(arg0); // signature: Unit } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test4(arg0)) { // type: Array if (arguments.length === 1) { return signature4(arg0); // signature: Array } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test5(arg0)) { // type: Matrix if (arguments.length === 1) { return signature4(arg0); // signature: Matrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test6(arg0)) { // type: string (convert to number) if (arguments.length === 1) { return signature0(convert0(arg0)); // signature: string } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test7(arg0)) { // type: boolean (convert to number) if (arguments.length === 1) { return signature0(convert1(arg0)); // signature: boolean } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test8(arg0)) { // type: null (convert to number) if (arguments.length === 1) { return signature0(convert2(arg0)); // signature: null } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'number,BigNumber,Fraction,Unit,Array,Matrix'); }
...
return new type.Complex(
(x.re > 0) ? Math.floor(x.re) : Math.ceil(x.re),
(x.im > 0) ? Math.floor(x.im) : Math.ceil(x.im)
);
},
'BigNumber': function (x) {
return x.isNegative() ? x.ceil() : x.floor();
},
'Fraction': function (x) {
return x.s < 0 ? x.ceil() : x.floor();
},
'Array | Matrix': function (x) {
...
function isNumeric(arg0) { "use strict"; var name = 'isNumeric'; if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature0(arg0); // signature: number } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: Complex if (arguments.length === 1) { return signature1(arg0); // signature: Complex } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test2(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature0(arg0); // signature: BigNumber } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test3(arg0)) { // type: Fraction if (arguments.length === 1) { return signature0(arg0); // signature: Fraction } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test4(arg0)) { // type: Unit if (arguments.length === 1) { return signature1(arg0); // signature: Unit } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test5(arg0)) { // type: string if (arguments.length === 1) { return signature1(arg0); // signature: string } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test6(arg0)) { // type: Array if (arguments.length === 1) { return signature2(arg0); // signature: Array } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test7(arg0)) { // type: Matrix if (arguments.length === 1) { return signature2(arg0); // signature: Matrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test8(arg0)) { // type: boolean if (arguments.length === 1) { return signature0(arg0); // signature: boolean } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test9(arg0)) { // type: null (convert to number) if (arguments.length === 1) { return signature0(convert0(arg0)); // signature: null } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'number,Complex,BigNumber,Fraction,Unit,string,Array,Matrix,boolean '); }
...
/**
* Test whether a value is an numeric value.
*
* The function is evaluated element-wise in case of Array or Matrix input.
*
* Syntax:
*
* math.isNumeric(x)
*
* Examples:
*
* math.isNumeric(2); // returns true
* math.isNumeric(0); // returns true
* math.isNumeric(math.bignumber(500)); // returns true
* math.isNumeric(math.fraction(4)); // returns true
...
function isPositive(arg0) { "use strict"; var name = 'isPositive'; if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature0(arg0); // signature: number } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature1(arg0); // signature: BigNumber } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test2(arg0)) { // type: Fraction if (arguments.length === 1) { return signature2(arg0); // signature: Fraction } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test3(arg0)) { // type: Unit if (arguments.length === 1) { return signature3(arg0); // signature: Unit } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test4(arg0)) { // type: Array if (arguments.length === 1) { return signature4(arg0); // signature: Array } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test5(arg0)) { // type: Matrix if (arguments.length === 1) { return signature4(arg0); // signature: Matrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test6(arg0)) { // type: string (convert to number) if (arguments.length === 1) { return signature0(convert0(arg0)); // signature: string } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test7(arg0)) { // type: boolean (convert to number) if (arguments.length === 1) { return signature0(convert1(arg0)); // signature: boolean } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test8(arg0)) { // type: null (convert to number) if (arguments.length === 1) { return signature0(convert2(arg0)); // signature: null } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'number,BigNumber,Fraction,Unit,Array,Matrix'); }
...
* Test whether a value is positive: larger than zero.
* The function supports types `number`, `BigNumber`, `Fraction`, and `Unit`.
*
* The function is evaluated element-wise in case of Array or Matrix input.
*
* Syntax:
*
* math.isPositive(x)
*
* Examples:
*
* math.isPositive(3); // returns true
* math.isPositive(-2); // returns false
* math.isPositive(0); // returns false
* math.isPositive(-0); // returns false
...
function isPrime(arg0) { "use strict"; var name = 'isPrime'; if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature0(arg0); // signature: number } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature1(arg0); // signature: BigNumber } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test2(arg0)) { // type: Array if (arguments.length === 1) { return signature2(arg0); // signature: Array } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test3(arg0)) { // type: Matrix if (arguments.length === 1) { return signature2(arg0); // signature: Matrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test4(arg0)) { // type: Fraction (convert to BigNumber) if (arguments.length === 1) { return signature1(convert0(arg0)); // signature: Fraction } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test5(arg0)) { // type: string (convert to number) if (arguments.length === 1) { return signature0(convert1(arg0)); // signature: string } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test6(arg0)) { // type: boolean (convert to number) if (arguments.length === 1) { return signature0(convert2(arg0)); // signature: boolean } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test7(arg0)) { // type: null (convert to number) if (arguments.length === 1) { return signature0(convert3(arg0)); // signature: null } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'number,BigNumber,Array,Matrix'); }
...
* Test whether a value is prime: has no divisors other than itself and one.
* The function supports type `number`, `bignumber`.
*
* The function is evaluated element-wise in case of Array or Matrix input.
*
* Syntax:
*
* math.isPrime(x)
*
* Examples:
*
* math.isPrime(3); // returns true
* math.isPrime(-2); // returns false
* math.isPrime(0); // returns false
* math.isPrime(-0); // returns false
...
function isZero(arg0) { "use strict"; var name = 'isZero'; if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature0(arg0); // signature: number } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: Complex if (arguments.length === 1) { return signature1(arg0); // signature: Complex } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test2(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature2(arg0); // signature: BigNumber } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test3(arg0)) { // type: Fraction if (arguments.length === 1) { return signature3(arg0); // signature: Fraction } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test4(arg0)) { // type: Unit if (arguments.length === 1) { return signature4(arg0); // signature: Unit } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test5(arg0)) { // type: Array if (arguments.length === 1) { return signature5(arg0); // signature: Array } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test6(arg0)) { // type: Matrix if (arguments.length === 1) { return signature5(arg0); // signature: Matrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test7(arg0)) { // type: string (convert to number) if (arguments.length === 1) { return signature0(convert0(arg0)); // signature: string } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test8(arg0)) { // type: boolean (convert to number) if (arguments.length === 1) { return signature0(convert1(arg0)); // signature: boolean } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test9(arg0)) { // type: null (convert to number) if (arguments.length === 1) { return signature0(convert2(arg0)); // signature: null } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'number,Complex,BigNumber,Fraction,Unit,Array,Matrix'); }
...
},
'number': function (x) {
return !!x;
},
'BigNumber': function (x) {
return !x.isZero();
},
'string': function (x) {
// try case insensitive
var lcase = x.toLowerCase();
if (lcase === 'true') {
return true;
...
function kldivergence(arg0, arg1) { "use strict"; var name = 'kldivergence'; if (test0(arg0)) { // type: Array if (test0(arg1)) { // type: Array if (arguments.length === 2) { return signature0(arg0, arg1); // signature: Array, Array } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test1(arg1)) { // type: Matrix if (arguments.length === 2) { return signature1(arg0, arg1); // signature: Array, Matrix } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'Array,Matrix'); } if (test1(arg0)) { // type: Matrix if (test0(arg1)) { // type: Array if (arguments.length === 2) { return signature2(arg0, arg1); // signature: Matrix, Array } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test1(arg1)) { // type: Matrix if (arguments.length === 2) { return signature3(arg0, arg1); // signature: Matrix, Matrix } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'Array,Matrix'); } throw createError(name, arguments.length, 0, arguments[0], 'Array,Matrix'); }
...
var isNumeric = load(require('../utils/isNumeric'));
/**
* Calculate the Kullback-Leibler (KL) divergence between two distributions
*
* Syntax:
*
* math.kldivergence(x, y)
*
* Examples:
*
* math.kldivergence([0.7,0.5,0.4], [0.2,0.9,0.5]); //returns 0.24376698773121153
*
*
* @param {Array | Matrix} q First vector
...
function kron(arg0, arg1) { "use strict"; var name = 'kron'; if (test0(arg0)) { // type: Array if (test0(arg1)) { // type: Array if (arguments.length === 2) { return signature0(arg0, arg1); // signature: Array, Array } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test1(arg1)) { // type: Matrix if (arguments.length === 2) { return signature1(arg0, arg1); // signature: Array, Matrix } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'Array,Matrix'); } if (test1(arg0)) { // type: Matrix if (test0(arg1)) { // type: Array if (arguments.length === 2) { return signature2(arg0, arg1); // signature: Matrix, Array } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test1(arg1)) { // type: Matrix if (arguments.length === 2) { return signature3(arg0, arg1); // signature: Matrix, Matrix } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'Array,Matrix'); } throw createError(name, arguments.length, 0, arguments[0], 'Array,Matrix'); }
...
*
* NOTE: If a one dimensional vector / matrix is given, it will be
* wrapped so its two dimensions.
* See the examples.
*
* Syntax:
*
* math.kron(x, y)
*
* Examples:
*
* math.kron([[1, 0], [0, 1]], [[1, 2], [3, 4]]);
* // returns [ [ 1, 2, 0, 0 ], [ 3, 4, 0, 0 ], [ 0, 0, 1, 2 ], [ 0, 0, 3, 4 ] ]
*
* math.kron([1,1], [2,3,4]);
...
function larger(arg0, arg1) { "use strict"; var name = 'larger'; if (test0(arg0)) { // type: number if (test0(arg1)) { // type: number if (arguments.length === 2) { return signature0(arg0, arg1); // signature: number, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test1(arg1)) { // type: Complex if (arguments.length === 2) { return signature1(convert0(arg0), arg1); // signature: number, Complex } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature2(convert1(arg0), arg1); // signature: number, BigNumber } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: Fraction if (arguments.length === 2) { return signature3(convert2(arg0), arg1); // signature: number, Fraction } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test4(arg1)) { // type: string (convert to number) if (arguments.length === 2) { return signature0(arg0, convert3(arg1)); // signature: number, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test5(arg1)) { // type: boolean (convert to number) if (arguments.length === 2) { return signature0(arg0, convert4(arg1)); // signature: number, boolean } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test6(arg1)) { // type: null (convert to number) if (arguments.length === 2) { return signature0(arg0, convert5(arg1)); // signature: number, null } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } } if (test1(arg0)) { // type: Complex if (test1(arg1)) { // type: Complex if (arguments.length === 2) { return signature1(arg0, arg1); // signature: Complex, Complex } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test0(arg1)) { // type: number (convert to Complex) if (arguments.length === 2) { return signature1(arg0, convert0(arg1)); // signature: Complex, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: BigNumber (convert to Complex) if (arguments.length === 2) { return signature1(arg0, convert6(arg1)); // signature: Complex, BigNumber } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: Fraction (convert to Complex) if (arguments.length === 2) { return signature1(arg0, convert7(arg1)); // signature: Complex, Fraction } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test4(arg1)) { // type: string (convert to Complex) if (arguments.length === 2) { return signature1(arg0, convert8(arg1)); // signature: Complex, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } } if (test2(arg0)) { // type: BigNumber if (test1(arg1)) { // type: Complex if (arguments.length === 2) { return signature1(convert6(arg0), arg1); // signature: BigNumber, Complex } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature2(arg0, arg1); // signature: BigNumber, BigNu ...
...
*
* Syntax:
*
* math.largerEq(x, y)
*
* Examples:
*
* math.larger(2, 1 + 1); // returns false
* math.largerEq(2, 1 + 1); // returns true
*
* See also:
*
* equal, unequal, smaller, smallerEq, larger, compare
*
* @param {number | BigNumber | Fraction | boolean | Unit | string | Array | Matrix} x First value to compare
...
function largerEq(arg0, arg1) { "use strict"; var name = 'largerEq'; if (test0(arg0)) { // type: number if (test0(arg1)) { // type: number if (arguments.length === 2) { return signature0(arg0, arg1); // signature: number, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test1(arg1)) { // type: Complex if (arguments.length === 2) { return signature1(convert0(arg0), arg1); // signature: number, Complex } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature2(convert1(arg0), arg1); // signature: number, BigNumber } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: Fraction if (arguments.length === 2) { return signature3(convert2(arg0), arg1); // signature: number, Fraction } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test4(arg1)) { // type: string (convert to number) if (arguments.length === 2) { return signature0(arg0, convert3(arg1)); // signature: number, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test5(arg1)) { // type: boolean (convert to number) if (arguments.length === 2) { return signature0(arg0, convert4(arg1)); // signature: number, boolean } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test6(arg1)) { // type: null (convert to number) if (arguments.length === 2) { return signature0(arg0, convert5(arg1)); // signature: number, null } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } } if (test1(arg0)) { // type: Complex if (test1(arg1)) { // type: Complex if (arguments.length === 2) { return signature1(arg0, arg1); // signature: Complex, Complex } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test0(arg1)) { // type: number (convert to Complex) if (arguments.length === 2) { return signature1(arg0, convert0(arg1)); // signature: Complex, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: BigNumber (convert to Complex) if (arguments.length === 2) { return signature1(arg0, convert6(arg1)); // signature: Complex, BigNumber } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: Fraction (convert to Complex) if (arguments.length === 2) { return signature1(arg0, convert7(arg1)); // signature: Complex, Fraction } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test4(arg1)) { // type: string (convert to Complex) if (arguments.length === 2) { return signature1(arg0, convert8(arg1)); // signature: Complex, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } } if (test2(arg0)) { // type: BigNumber if (test1(arg1)) { // type: Complex if (arguments.length === 2) { return signature1(convert6(arg0), arg1); // signature: BigNumber, Complex } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature2(arg0, arg1); // signature: BigNumber, B ...
...
* difference between x and y is smaller than the configured epsilon. The
* function cannot be used to compare values smaller than approximately 2.22e-16.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.largerEq(x, y)
*
* Examples:
*
* math.larger(2, 1 + 1); // returns false
* math.largerEq(2, 1 + 1); // returns true
*
* See also:
...
function lcm(arg0, arg1, arg2) { "use strict"; var name = 'lcm'; if (test0(arg0)) { // type: number if (test0(arg1)) { // type: number if (arguments.length === 2) { return signature0(arg0, arg1); // signature: number, number } if (test1(arg2) || test2(arg2) || test0(arg2) || test3(arg2)) { // type: ...Array|Matrix|number|BigNumber var varArgs = [arg2]; for (var i = 3; i < arguments.length; i++) { if (test1(arguments[i]) || test2(arguments[i]) || test0(arguments[i]) || test3(arguments[i])) { varArgs.push(arguments[i]); } else { throw createError(name, arguments.length, i, arguments[i], 'Array,Matrix,number,BigNumber'); } } return signature1(arg0, arg1, varArgs); // signature: number, number, ...Array|Matrix|number|BigNumber } throw createError(name, arguments.length, 2, arguments[2], 'Array,Matrix,number,BigNumber'); } if (test3(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature2(convert0(arg0), arg1); // signature: number, BigNumber } if (test1(arg2) || test2(arg2) || test0(arg2) || test3(arg2)) { // type: ...Array|Matrix|number|BigNumber var varArgs = [arg2]; for (var i = 3; i < arguments.length; i++) { if (test1(arguments[i]) || test2(arguments[i]) || test0(arguments[i]) || test3(arguments[i])) { varArgs.push(arguments[i]); } else { throw createError(name, arguments.length, i, arguments[i], 'Array,Matrix,number,BigNumber'); } } return signature1(arg0, arg1, varArgs); // signature: number, BigNumber, ...Array|Matrix|number|BigNumber } throw createError(name, arguments.length, 2, arguments[2], 'Array,Matrix,number,BigNumber'); } if (test4(arg1)) { // type: Fraction if (arguments.length === 2) { return signature3(convert1(arg0), arg1); // signature: number, Fraction } if (test1(arg2) || test2(arg2) || test0(arg2) || test3(arg2)) { // type: ...Array|Matrix|number|BigNumber var varArgs = [arg2]; for (var i = 3; i < arguments.length; i++) { if (test1(arguments[i]) || test2(arguments[i]) || test0(arguments[i]) || test3(arguments[i])) { varArgs.push(arguments[i]); } else { throw createError(name, arguments.length, i, arguments[i], 'Array,Matrix,number,BigNumber'); } } return signature1(arg0, convert2(arg1), varArgs); // signature: number, Fraction, ...Array|Matrix|number|BigNumber } throw createError(name, arguments.length, 2, arguments[2], 'Array,Matrix,number,BigNumber'); } if (test1(arg1)) { // type: Array if (arguments.length === 2) { return signature4(arg0, arg1); // signature: number, Array } if (test1(arg2) || test2(arg2) || test0(arg2) || test3(arg2)) { // type: ...Array|Matrix|number|BigNumber var varArgs = [arg2]; for (var i = 3; i < arguments.length; i++) { if (test1(arguments[i]) || test2(arguments[i]) || test0(arguments[i]) || test3(arguments[i])) { varArgs.push(arguments[i]); } else { throw createError(name, arguments.length, i, arguments[i], 'Array,Matrix,number,BigNumber'); } } return signature1(arg0, arg1, varArgs); // signature: number, Array, ...Array|Matrix|number|BigNumber } throw createError(name, arguments.length, 2, arguments[2], 'Array,Matrix,number,BigNumber'); } if (test2(arg1)) { // type: Matrix if (arguments.length === 2) { return signature5(arg0, arg1); // signature: number, Matrix } if (test1(arg2) || test2(arg2) || test0(arg2) || test3(arg2)) { // type: ...Array|Matrix|number|BigNumber var varArgs = [arg2]; for (var i = 3; i < arguments.length; i++) { if (test1(arguments[i]) || test2(arguments[i]) || test0(arguments[i]) || test3(arguments[i])) { varArgs.push(arguments[i]); ...
...
*
* lcm(a, b) = abs(a * b) / gcd(a, b)
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.lcm(a, b)
* math.lcm(a, b, c, ...)
*
* Examples:
*
* math.lcm(4, 6); // returns 12
* math.lcm(6, 21); // returns 42
* math.lcm(6, 21, 5); // returns 210
...
function leftShift(arg0, arg1) { "use strict"; var name = 'leftShift'; if (test0(arg0)) { // type: number if (test0(arg1)) { // type: number if (arguments.length === 2) { return signature0(arg0, arg1); // signature: number, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test1(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature1(convert0(arg0), arg1); // signature: number, BigNumber } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: Array if (arguments.length === 2) { return signature2(arg0, arg1); // signature: number, Array } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: Matrix if (arguments.length === 2) { return signature3(arg0, arg1); // signature: number, Matrix } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test4(arg1)) { // type: Fraction (convert to BigNumber) if (arguments.length === 2) { return signature1(convert0(arg0), convert1(arg1)); // signature: number, Fraction } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test5(arg1)) { // type: string (convert to number) if (arguments.length === 2) { return signature0(arg0, convert2(arg1)); // signature: number, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test6(arg1)) { // type: boolean (convert to number) if (arguments.length === 2) { return signature0(arg0, convert3(arg1)); // signature: number, boolean } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test7(arg1)) { // type: null (convert to number) if (arguments.length === 2) { return signature0(arg0, convert4(arg1)); // signature: number, null } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'number,BigNumber,Array,Matrix'); } if (test1(arg0)) { // type: BigNumber if (test1(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature1(arg0, arg1); // signature: BigNumber, BigNumber } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: Array if (arguments.length === 2) { return signature2(arg0, arg1); // signature: BigNumber, Array } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: Matrix if (arguments.length === 2) { return signature3(arg0, arg1); // signature: BigNumber, Matrix } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test0(arg1)) { // type: number (convert to BigNumber) if (arguments.length === 2) { return signature1(arg0, convert0(arg1)); // signature: BigNumber, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test4(arg1)) { // type: Fraction (convert to BigNumber) if (arguments.length === 2) { return signature1(arg0, convert1(arg1)); // signature: BigNumber, Fraction } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test5(arg1)) { // type: string (convert to BigNumber) if (arguments.length === 2) { return signature1(arg0, conv ...
...
/**
* Bitwise left logical shift of a value x by y number of bits, `x << y`.
* For matrices, the function is evaluated element wise.
* For units, the function is evaluated on the best prefix base.
*
* Syntax:
*
* math.leftShift(x, y)
*
* Examples:
*
* math.leftShift(1, 2); // returns number 4
*
* math.leftShift([1, 2, 3], 4); // returns Array [16, 32, 64]
*
...
function log(arg0, arg1) { "use strict"; var name = 'log'; if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature0(arg0); // signature: number } } if (test1(arg0)) { // type: Complex if (arguments.length === 1) { return signature1(arg0); // signature: Complex } } if (test2(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature2(arg0); // signature: BigNumber } } if (test3(arg0)) { // type: Array if (arguments.length === 1) { return signature3(arg0); // signature: Array } } if (test4(arg0)) { // type: Matrix if (arguments.length === 1) { return signature3(arg0); // signature: Matrix } } if (test5(arg0)) { // type: Fraction (convert to BigNumber) if (arguments.length === 1) { return signature2(convert0(arg0)); // signature: Fraction } } if (test6(arg0)) { // type: string (convert to number) if (arguments.length === 1) { return signature0(convert1(arg0)); // signature: string } } if (test7(arg0)) { // type: boolean (convert to number) if (arguments.length === 1) { return signature0(convert2(arg0)); // signature: boolean } } if (test8(arg0)) { // type: null (convert to number) if (arguments.length === 1) { return signature0(convert3(arg0)); // signature: null } } // type: any // type: any if (arguments.length === 2) { return signature4(arg0, arg1); // signature: any, any } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } throw createError(name, arguments.length, 1, arguments[1], 'any'); throw createError(name, arguments.length, 0, arguments[0], 'number,Complex,BigNumber,Array,Matrix,any'); }
...
```js
// load math.js
var math = require('mathjs');
// functions and constants
math.round(math.e, 3); // 2.718
math.atan2(3, -3) / math.pi; // 0.75
math.log(1000, 10); // 3
math.sqrt(-4); // 2i
math.pow([[-1, 2], [3, 1]], 2); // [[7, 0], [0, 7]]
math.derivative('x^2 + x', 'x'); // 2 * x + 1
// expressions
math.eval('12 / (2.3 + 0.7)'); // 4
math.eval('5.08 cm to inch'); // 2 inch
...
function log10(arg0) { "use strict"; var name = 'log10'; if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature0(arg0); // signature: number } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: Complex if (arguments.length === 1) { return signature1(arg0); // signature: Complex } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test2(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature2(arg0); // signature: BigNumber } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test3(arg0)) { // type: Array if (arguments.length === 1) { return signature3(arg0); // signature: Array } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test4(arg0)) { // type: Matrix if (arguments.length === 1) { return signature3(arg0); // signature: Matrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test5(arg0)) { // type: Fraction (convert to BigNumber) if (arguments.length === 1) { return signature2(convert0(arg0)); // signature: Fraction } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test6(arg0)) { // type: string (convert to number) if (arguments.length === 1) { return signature0(convert1(arg0)); // signature: string } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test7(arg0)) { // type: boolean (convert to number) if (arguments.length === 1) { return signature0(convert2(arg0)); // signature: boolean } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test8(arg0)) { // type: null (convert to number) if (arguments.length === 1) { return signature0(convert3(arg0)); // signature: null } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'number,Complex,BigNumber,Array,Matrix'); }
...
/**
* Calculate the 10-base logarithm of a value. This is the same as calculating `log(x, 10)`.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.log10(x)
*
* Examples:
*
* math.log10(0.00001); // returns -5
* math.log10(10000); // returns 4
* math.log(10000) / math.log(10); // returns 4
* math.pow(10, 4); // returns 10000
...
function lsolve(arg0, arg1) { "use strict"; var name = 'lsolve'; if (test0(arg0)) { // type: Array if (test0(arg1)) { // type: Array if (arguments.length === 2) { return signature0(arg0, arg1); // signature: Array, Array } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test1(arg1)) { // type: Matrix if (arguments.length === 2) { return signature0(arg0, arg1); // signature: Array, Matrix } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'Array,Matrix'); } if (test2(arg0)) { // type: DenseMatrix if (test0(arg1)) { // type: Array if (arguments.length === 2) { return signature1(arg0, arg1); // signature: DenseMatrix, Array } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test1(arg1)) { // type: Matrix if (arguments.length === 2) { return signature1(arg0, arg1); // signature: DenseMatrix, Matrix } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'Array,Matrix'); } if (test3(arg0)) { // type: SparseMatrix if (test0(arg1)) { // type: Array if (arguments.length === 2) { return signature2(arg0, arg1); // signature: SparseMatrix, Array } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test1(arg1)) { // type: Matrix if (arguments.length === 2) { return signature2(arg0, arg1); // signature: SparseMatrix, Matrix } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'Array,Matrix'); } if (test1(arg0)) { // type: Matrix (convert to Array) if (test0(arg1)) { // type: Array if (arguments.length === 2) { return signature0(convert0(arg0), arg1); // signature: Matrix, Array } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test1(arg1)) { // type: Matrix if (arguments.length === 2) { return signature0(convert0(arg0), arg1); // signature: Matrix, Matrix } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'Array,Matrix'); } throw createError(name, arguments.length, 0, arguments[0], 'Array,DenseMatrix,SparseMatrix'); }
n/a
function lup(arg0) { "use strict"; var name = 'lup'; if (test0(arg0)) { // type: Array if (arguments.length === 1) { return signature0(arg0); // signature: Array } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: DenseMatrix if (arguments.length === 1) { return signature1(arg0); // signature: DenseMatrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test2(arg0)) { // type: SparseMatrix if (arguments.length === 1) { return signature2(arg0); // signature: SparseMatrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test3(arg0)) { // type: Matrix (convert to Array) if (arguments.length === 1) { return signature0(convert0(arg0)); // signature: Matrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'Array,DenseMatrix,SparseMatrix'); }
n/a
function lusolve(arg0, arg1, arg2, arg3) { "use strict"; var name = 'lusolve'; if (test0(arg0)) { // type: Array if (test0(arg1)) { // type: Array if (arguments.length === 2) { return signature0(arg0, arg1); // signature: Array, Array } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test1(arg1)) { // type: Matrix if (arguments.length === 2) { return signature0(arg0, arg1); // signature: Array, Matrix } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'Array,Matrix'); } if (test2(arg0)) { // type: DenseMatrix if (test0(arg1)) { // type: Array if (arguments.length === 2) { return signature1(arg0, arg1); // signature: DenseMatrix, Array } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test1(arg1)) { // type: Matrix if (arguments.length === 2) { return signature1(arg0, arg1); // signature: DenseMatrix, Matrix } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'Array,Matrix'); } if (test3(arg0)) { // type: SparseMatrix if (test0(arg1)) { // type: Array if (arguments.length === 2) { return signature2(arg0, arg1); // signature: SparseMatrix, Array } if (test4(arg2)) { // type: number if (test4(arg3)) { // type: number if (arguments.length === 4) { return signature3(arg0, arg1, arg2, arg3); // signature: SparseMatrix, Array, number, number } if (arguments.length > 4) { throw createError(name, arguments.length, 4, arguments[4]); } } if (test5(arg3)) { // type: string (convert to number) if (arguments.length === 4) { return signature3(arg0, arg1, arg2, convert0(arg3)); // signature: SparseMatrix, Array, number, string } if (arguments.length > 4) { throw createError(name, arguments.length, 4, arguments[4]); } } if (test6(arg3)) { // type: boolean (convert to number) if (arguments.length === 4) { return signature3(arg0, arg1, arg2, convert1(arg3)); // signature: SparseMatrix, Array, number, boolean } if (arguments.length > 4) { throw createError(name, arguments.length, 4, arguments[4]); } } if (test7(arg3)) { // type: null (convert to number) if (arguments.length === 4) { return signature3(arg0, arg1, arg2, convert2(arg3)); // signature: SparseMatrix, Array, number, null } if (arguments.length > 4) { throw createError(name, arguments.length, 4, arguments[4]); } } throw createError(name, arguments.length, 3, arguments[3], 'number'); } if (test5(arg2)) { // type: string (convert to number) if (test4(arg3)) { // type: number if (arguments.length === 4) { return signature3(arg0, arg1, convert0(arg2), arg3); // signature: SparseMatrix, Array, string, number } if (arguments.length > 4) { throw createError(name, arguments.length, 4, arguments[4]); } } if (test5(arg3)) { // type: string (convert to number) if (arguments.length === 4) { return signature3(arg0, arg1, convert0(arg2), convert0(arg3)); // signature: SparseMatrix, Array, string, string } if (arguments.length > 4) { throw createError(name, arguments.length, 4, arguments[4]); } } if (test6(arg3)) { // type: boolean (convert to number) if (arguments.length === 4) { return signature3(arg0, arg1, convert0(arg2), convert1(arg3)); ...
n/a
function mad(arg0) { "use strict"; var name = 'mad'; if (test0(arg0)) { // type: Array if (arguments.length === 1) { return signature0(arg0); // signature: Array } } if (test1(arg0)) { // type: Matrix if (arguments.length === 1) { return signature0(arg0); // signature: Matrix } } if (arguments.length > 0) { var varArgs = []; for (var i = 0; i < arguments.length; i++) { varArgs.push(arguments[i]); } return signature1(varArgs); // signature: ...any } throw createError(name, arguments.length, 0, arguments[0], 'Array,Matrix,any'); }
...
/**
* Compute the median absolute deviation of a matrix or a list with values.
* The median absolute deviation is defined as the median of the absolute
* deviations from the median.
*
* Syntax:
*
* math.mad(a, b, c, ...)
* math.mad(A)
*
* Examples:
*
* math.mad(10, 20, 30); // returns 10
* math.mad([1, 2, 3]); // returns 1
* math.mad([[1, 2, 3], [4, 5, 6]]); // returns 1.5
...
function map(arg0, arg1) { "use strict"; var name = 'map'; if (test0(arg0)) { // type: Array if (test1(arg1)) { // type: function if (arguments.length === 2) { return signature0(arg0, arg1); // signature: Array, function } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'function'); } if (test2(arg0)) { // type: Matrix if (test1(arg1)) { // type: function if (arguments.length === 2) { return signature1(arg0, arg1); // signature: Matrix, function } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'function'); } throw createError(name, arguments.length, 0, arguments[0], 'Array,Matrix'); }
...
if (res && res.isResultSet) {
// we can have 0 or 1 results in the ResultSet, as the CLI
// does not allow multiple expressions separated by a return
res = res.entries[0];
node = node.blocks
.filter(function (entry) { return entry.visible; })
.map(function (entry) { return entry.node })[0];
}
if (node) {
if (node.isAssignmentNode) {
var name = findSymbolName(node);
if (name != null) {
scope.ans = scope[name];
...
function matrix(arg0, arg1, arg2) { "use strict"; var name = 'matrix'; if (arguments.length === 0) { return signature0(); // signature: } if (test0(arg0)) { // type: string if (arguments.length === 1) { return signature1(arg0); // signature: string } if (test0(arg1)) { // type: string if (arguments.length === 2) { return signature2(arg0, arg1); // signature: string, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test1(arg1)) { // type: number (convert to string) if (arguments.length === 2) { return signature2(arg0, convert0(arg1)); // signature: string, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: boolean (convert to string) if (arguments.length === 2) { return signature2(arg0, convert1(arg1)); // signature: string, boolean } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: null (convert to string) if (arguments.length === 2) { return signature2(arg0, convert2(arg1)); // signature: string, null } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'string'); } if (test4(arg0)) { // type: Array if (arguments.length === 1) { return signature3(arg0); // signature: Array } if (test0(arg1)) { // type: string if (arguments.length === 2) { return signature4(arg0, arg1); // signature: Array, string } if (test0(arg2)) { // type: string if (arguments.length === 3) { return signature4(arg0, arg1, arg2); // signature: Array, string, string } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } if (test1(arg2)) { // type: number (convert to string) if (arguments.length === 3) { return signature4(arg0, arg1, convert0(arg2)); // signature: Array, string, number } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } if (test2(arg2)) { // type: boolean (convert to string) if (arguments.length === 3) { return signature4(arg0, arg1, convert1(arg2)); // signature: Array, string, boolean } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } if (test3(arg2)) { // type: null (convert to string) if (arguments.length === 3) { return signature4(arg0, arg1, convert2(arg2)); // signature: Array, string, null } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } throw createError(name, arguments.length, 2, arguments[2], 'string'); } if (test1(arg1)) { // type: number (convert to string) if (arguments.length === 2) { return signature4(arg0, convert0(arg1)); // signature: Array, number } if (test0(arg2)) { // type: string if (arguments.length === 3) { return signature4(arg0, convert0(arg1), arg2); // signature: Array, number, string } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } if (test1(arg2)) { // type: number (convert to string) if (arguments.length === 3) { return signature4(arg0, convert0(arg1), convert0(arg2)); // signature: Array, number, number } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } if (test2(arg2)) { // type: boolean (convert to string) if (arguments.length === 3) { return signature4(a ...
...
ArrayNode.prototype._compile = function (defs, args) {
var asMatrix = (defs.math.config().matrix !== 'Array');
var items = this.items.map(function (node) {
return node._compile(defs, args);
});
return (asMatrix ? 'math.matrix([' : '[') +
items.join(',') +
(asMatrix ? '])' : ']');
};
/**
* Execute a callback for each of the child nodes of this node
* @param {function(child: Node, path: string, parent: Node)} callback
...
function max(arg0, arg1) { "use strict"; var name = 'max'; if (test0(arg0)) { // type: Array if (arguments.length === 1) { return signature0(arg0); // signature: Array } if (test1(arg1)) { // type: number if (arguments.length === 2) { return signature1(arg0, arg1); // signature: Array, number } } if (test2(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature1(arg0, arg1); // signature: Array, BigNumber } } if (test3(arg1)) { // type: Fraction (convert to BigNumber) if (arguments.length === 2) { return signature1(arg0, convert0(arg1)); // signature: Array, Fraction } } if (test4(arg1)) { // type: string (convert to number) if (arguments.length === 2) { return signature1(arg0, convert1(arg1)); // signature: Array, string } } if (test5(arg1)) { // type: boolean (convert to number) if (arguments.length === 2) { return signature1(arg0, convert2(arg1)); // signature: Array, boolean } } if (test6(arg1)) { // type: null (convert to number) if (arguments.length === 2) { return signature1(arg0, convert3(arg1)); // signature: Array, null } } } if (test7(arg0)) { // type: Matrix if (arguments.length === 1) { return signature0(arg0); // signature: Matrix } if (test1(arg1)) { // type: number if (arguments.length === 2) { return signature1(arg0, arg1); // signature: Matrix, number } } if (test2(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature1(arg0, arg1); // signature: Matrix, BigNumber } } if (test3(arg1)) { // type: Fraction (convert to BigNumber) if (arguments.length === 2) { return signature1(arg0, convert0(arg1)); // signature: Matrix, Fraction } } if (test4(arg1)) { // type: string (convert to number) if (arguments.length === 2) { return signature1(arg0, convert1(arg1)); // signature: Matrix, string } } if (test5(arg1)) { // type: boolean (convert to number) if (arguments.length === 2) { return signature1(arg0, convert2(arg1)); // signature: Matrix, boolean } } if (test6(arg1)) { // type: null (convert to number) if (arguments.length === 2) { return signature1(arg0, convert3(arg1)); // signature: Matrix, null } } } if (arguments.length > 0) { var varArgs = []; for (var i = 0; i < arguments.length; i++) { varArgs.push(arguments[i]); } return signature2(varArgs); // signature: ...any } throw createError(name, arguments.length, 0, arguments[0], 'Array,Matrix,any'); }
...
* @return {number} Returns the maximum number of expected arguments.
* Returns -1 when no signatures where found on the function.
*/
exports.maxArgumentCount = function (fn) {
return Object.keys(fn.signatures || {})
.reduce(function (args, signature) {
var count = (signature.match(/,/g) || []).length + 1;
return Math.max(args, count);
}, -1);
};
...
function mean(arg0, arg1) { "use strict"; var name = 'mean'; if (test0(arg0)) { // type: Array if (arguments.length === 1) { return signature0(arg0); // signature: Array } if (test1(arg1)) { // type: number if (arguments.length === 2) { return signature1(arg0, arg1); // signature: Array, number } } if (test2(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature1(arg0, arg1); // signature: Array, BigNumber } } if (test3(arg1)) { // type: Fraction (convert to BigNumber) if (arguments.length === 2) { return signature1(arg0, convert0(arg1)); // signature: Array, Fraction } } if (test4(arg1)) { // type: string (convert to number) if (arguments.length === 2) { return signature1(arg0, convert1(arg1)); // signature: Array, string } } if (test5(arg1)) { // type: boolean (convert to number) if (arguments.length === 2) { return signature1(arg0, convert2(arg1)); // signature: Array, boolean } } if (test6(arg1)) { // type: null (convert to number) if (arguments.length === 2) { return signature1(arg0, convert3(arg1)); // signature: Array, null } } } if (test7(arg0)) { // type: Matrix if (arguments.length === 1) { return signature0(arg0); // signature: Matrix } if (test1(arg1)) { // type: number if (arguments.length === 2) { return signature1(arg0, arg1); // signature: Matrix, number } } if (test2(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature1(arg0, arg1); // signature: Matrix, BigNumber } } if (test3(arg1)) { // type: Fraction (convert to BigNumber) if (arguments.length === 2) { return signature1(arg0, convert0(arg1)); // signature: Matrix, Fraction } } if (test4(arg1)) { // type: string (convert to number) if (arguments.length === 2) { return signature1(arg0, convert1(arg1)); // signature: Matrix, string } } if (test5(arg1)) { // type: boolean (convert to number) if (arguments.length === 2) { return signature1(arg0, convert2(arg1)); // signature: Matrix, boolean } } if (test6(arg1)) { // type: null (convert to number) if (arguments.length === 2) { return signature1(arg0, convert3(arg1)); // signature: Matrix, null } } } if (arguments.length > 0) { var varArgs = []; for (var i = 0; i < arguments.length; i++) { varArgs.push(arguments[i]); } return signature2(varArgs); // signature: ...any } throw createError(name, arguments.length, 0, arguments[0], 'Array,Matrix,any'); }
...
* Compute the mean value of matrix or a list with values.
* In case of a multi dimensional array, the mean of the flattened array
* will be calculated. When `dim` is provided, the maximum over the selected
* dimension will be calculated. Parameter `dim` is zero-based.
*
* Syntax:
*
* math.mean(a, b, c, ...)
* math.mean(A)
* math.mean(A, dim)
*
* Examples:
*
* math.mean(2, 1, 4, 3); // returns 2.5
* math.mean([1, 2.7, 3.2, 4]); // returns 2.725
...
function median(arg0, arg1) { "use strict"; var name = 'median'; if (test0(arg0)) { // type: Array if (arguments.length === 1) { return signature0(arg0); // signature: Array } if (test1(arg1)) { // type: number if (arguments.length === 2) { return signature1(arg0, arg1); // signature: Array, number } } if (test2(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature1(arg0, arg1); // signature: Array, BigNumber } } if (test3(arg1)) { // type: Fraction (convert to BigNumber) if (arguments.length === 2) { return signature1(arg0, convert0(arg1)); // signature: Array, Fraction } } if (test4(arg1)) { // type: string (convert to number) if (arguments.length === 2) { return signature1(arg0, convert1(arg1)); // signature: Array, string } } if (test5(arg1)) { // type: boolean (convert to number) if (arguments.length === 2) { return signature1(arg0, convert2(arg1)); // signature: Array, boolean } } if (test6(arg1)) { // type: null (convert to number) if (arguments.length === 2) { return signature1(arg0, convert3(arg1)); // signature: Array, null } } } if (test7(arg0)) { // type: Matrix if (arguments.length === 1) { return signature0(arg0); // signature: Matrix } if (test1(arg1)) { // type: number if (arguments.length === 2) { return signature1(arg0, arg1); // signature: Matrix, number } } if (test2(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature1(arg0, arg1); // signature: Matrix, BigNumber } } if (test3(arg1)) { // type: Fraction (convert to BigNumber) if (arguments.length === 2) { return signature1(arg0, convert0(arg1)); // signature: Matrix, Fraction } } if (test4(arg1)) { // type: string (convert to number) if (arguments.length === 2) { return signature1(arg0, convert1(arg1)); // signature: Matrix, string } } if (test5(arg1)) { // type: boolean (convert to number) if (arguments.length === 2) { return signature1(arg0, convert2(arg1)); // signature: Matrix, boolean } } if (test6(arg1)) { // type: null (convert to number) if (arguments.length === 2) { return signature1(arg0, convert3(arg1)); // signature: Matrix, null } } } if (arguments.length > 0) { var varArgs = []; for (var i = 0; i < arguments.length; i++) { varArgs.push(arguments[i]); } return signature2(varArgs); // signature: ...any } throw createError(name, arguments.length, 0, arguments[0], 'Array,Matrix,any'); }
...
* Supported types of values are: Number, BigNumber, Unit
*
* In case of a (multi dimensional) array or matrix, the median of all
* elements will be calculated.
*
* Syntax:
*
* math.median(a, b, c, ...)
* math.median(A)
*
* Examples:
*
* math.median(5, 2, 7); // returns 5
* math.median([3, -1, 5, 7]); // returns 4
*
...
function min(arg0, arg1) { "use strict"; var name = 'min'; if (test0(arg0)) { // type: Array if (arguments.length === 1) { return signature0(arg0); // signature: Array } if (test1(arg1)) { // type: number if (arguments.length === 2) { return signature1(arg0, arg1); // signature: Array, number } } if (test2(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature1(arg0, arg1); // signature: Array, BigNumber } } if (test3(arg1)) { // type: Fraction (convert to BigNumber) if (arguments.length === 2) { return signature1(arg0, convert0(arg1)); // signature: Array, Fraction } } if (test4(arg1)) { // type: string (convert to number) if (arguments.length === 2) { return signature1(arg0, convert1(arg1)); // signature: Array, string } } if (test5(arg1)) { // type: boolean (convert to number) if (arguments.length === 2) { return signature1(arg0, convert2(arg1)); // signature: Array, boolean } } if (test6(arg1)) { // type: null (convert to number) if (arguments.length === 2) { return signature1(arg0, convert3(arg1)); // signature: Array, null } } } if (test7(arg0)) { // type: Matrix if (arguments.length === 1) { return signature0(arg0); // signature: Matrix } if (test1(arg1)) { // type: number if (arguments.length === 2) { return signature1(arg0, arg1); // signature: Matrix, number } } if (test2(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature1(arg0, arg1); // signature: Matrix, BigNumber } } if (test3(arg1)) { // type: Fraction (convert to BigNumber) if (arguments.length === 2) { return signature1(arg0, convert0(arg1)); // signature: Matrix, Fraction } } if (test4(arg1)) { // type: string (convert to number) if (arguments.length === 2) { return signature1(arg0, convert1(arg1)); // signature: Matrix, string } } if (test5(arg1)) { // type: boolean (convert to number) if (arguments.length === 2) { return signature1(arg0, convert2(arg1)); // signature: Matrix, boolean } } if (test6(arg1)) { // type: null (convert to number) if (arguments.length === 2) { return signature1(arg0, convert3(arg1)); // signature: Matrix, null } } } if (arguments.length > 0) { var varArgs = []; for (var i = 0; i < arguments.length; i++) { varArgs.push(arguments[i]); } return signature2(varArgs); // signature: ...any } throw createError(name, arguments.length, 0, arguments[0], 'Array,Matrix,any'); }
...
* @private
*/
function _resize (array, size, dim, defaultValue) {
var i;
var elem;
var oldLen = array.length;
var newLen = size[dim];
var minLen = Math.min(oldLen, newLen);
// apply new length
array.length = newLen;
if (dim < size.length - 1) {
// non-last dimension
var dimNext = dim + 1;
...
function mod(arg0, arg1) { "use strict"; var name = 'mod'; if (test0(arg0)) { // type: number if (test0(arg1)) { // type: number if (arguments.length === 2) { return signature0(arg0, arg1); // signature: number, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test1(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature1(convert0(arg0), arg1); // signature: number, BigNumber } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: Fraction if (arguments.length === 2) { return signature2(convert1(arg0), arg1); // signature: number, Fraction } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: string (convert to number) if (arguments.length === 2) { return signature0(arg0, convert2(arg1)); // signature: number, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test4(arg1)) { // type: boolean (convert to number) if (arguments.length === 2) { return signature0(arg0, convert3(arg1)); // signature: number, boolean } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test5(arg1)) { // type: null (convert to number) if (arguments.length === 2) { return signature0(arg0, convert4(arg1)); // signature: number, null } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } } if (test1(arg0)) { // type: BigNumber if (test1(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature1(arg0, arg1); // signature: BigNumber, BigNumber } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test0(arg1)) { // type: number (convert to BigNumber) if (arguments.length === 2) { return signature1(arg0, convert0(arg1)); // signature: BigNumber, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: Fraction (convert to BigNumber) if (arguments.length === 2) { return signature1(arg0, convert5(arg1)); // signature: BigNumber, Fraction } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: string (convert to BigNumber) if (arguments.length === 2) { return signature1(arg0, convert6(arg1)); // signature: BigNumber, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test4(arg1)) { // type: boolean (convert to BigNumber) if (arguments.length === 2) { return signature1(arg0, convert7(arg1)); // signature: BigNumber, boolean } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test5(arg1)) { // type: null (convert to BigNumber) if (arguments.length === 2) { return signature1(arg0, convert8(arg1)); // signature: BigNumber, null } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } } if (test2(arg0)) { // type: Fraction if (test1(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature1(convert5(arg0), arg1); // signature: Fraction, BigNumber } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: Fraction if (arguments.length === 2) { return signature2(arg0, ar ...
...
if (!a.isInt() || !b.isInt()) {
throw new Error('Parameters in function gcd must be integer numbers');
}
// http://en.wikipedia.org/wiki/Euclidean_algorithm
var zero = new type.BigNumber(0);
while (!b.isZero()) {
var r = a.mod(b);
a = b;
b = r;
}
return a.lt(zero) ? a.neg() : a;
}
}
...
function mode(arg0) { "use strict"; var name = 'mode'; if (test0(arg0)) { // type: Array if (arguments.length === 1) { return signature0(arg0); // signature: Array } } if (test1(arg0)) { // type: Matrix if (arguments.length === 1) { return signature0(arg0); // signature: Matrix } } if (arguments.length > 0) { var varArgs = []; for (var i = 0; i < arguments.length; i++) { varArgs.push(arguments[i]); } return signature1(varArgs); // signature: ...any } throw createError(name, arguments.length, 0, arguments[0], 'Array,Matrix,any'); }
...
/**
* Computes the mode of a set of numbers or a list with values(numbers or characters).
* If there are more than one modes, it returns a list of those values.
*
* Syntax:
*
* math.mode(a, b, c, ...)
* math.mode(A)
*
* Examples:
*
* math.mode(2, 1, 4, 3, 1); // returns [1]
* math.mode([1, 2.7, 3.2, 4, 2.7]); // returns [2.7]
* math.mode(1, 4, 6, 1, 6) // returns [1, 6]
...
function multinomial(arg0) { "use strict"; var name = 'multinomial'; if (test0(arg0)) { // type: Array if (arguments.length === 1) { return signature0(arg0); // signature: Array } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: Matrix if (arguments.length === 1) { return signature0(arg0); // signature: Matrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'Array,Matrix'); }
...
* Multinomial Coefficients compute the number of ways of picking a1, a2, ..., ai unordered outcomes from `n` possibilities.
*
* multinomial takes one array of integers as an argument.
* The following condition must be enforced: every ai <= 0
*
* Syntax:
*
* math.multinomial(a) // a is an array type
*
* Examples:
*
* math.multinomial([1,2,1]); // returns 12
*
* See also:
*
...
function multiply(arg0, arg1, arg2) { "use strict"; var name = 'multiply'; if (test0(arg0)) { // type: number if (test0(arg1)) { // type: number if (arguments.length === 2) { return signature0(arg0, arg1); // signature: number, number } } if (test1(arg1)) { // type: Complex if (arguments.length === 2) { return signature1(convert0(arg0), arg1); // signature: number, Complex } } if (test2(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature2(convert1(arg0), arg1); // signature: number, BigNumber } } if (test3(arg1)) { // type: Fraction if (arguments.length === 2) { return signature3(convert2(arg0), arg1); // signature: number, Fraction } } if (test4(arg1)) { // type: Unit if (arguments.length === 2) { return signature4(arg0, arg1); // signature: number, Unit } } if (test5(arg1)) { // type: string (convert to number) if (arguments.length === 2) { return signature0(arg0, convert3(arg1)); // signature: number, string } } if (test6(arg1)) { // type: boolean (convert to number) if (arguments.length === 2) { return signature0(arg0, convert4(arg1)); // signature: number, boolean } } if (test7(arg1)) { // type: null (convert to number) if (arguments.length === 2) { return signature0(arg0, convert5(arg1)); // signature: number, null } } } if (test1(arg0)) { // type: Complex if (test1(arg1)) { // type: Complex if (arguments.length === 2) { return signature1(arg0, arg1); // signature: Complex, Complex } } if (test4(arg1)) { // type: Unit if (arguments.length === 2) { return signature4(arg0, arg1); // signature: Complex, Unit } } if (test0(arg1)) { // type: number (convert to Complex) if (arguments.length === 2) { return signature1(arg0, convert0(arg1)); // signature: Complex, number } } if (test2(arg1)) { // type: BigNumber (convert to Complex) if (arguments.length === 2) { return signature1(arg0, convert6(arg1)); // signature: Complex, BigNumber } } if (test3(arg1)) { // type: Fraction (convert to Complex) if (arguments.length === 2) { return signature1(arg0, convert7(arg1)); // signature: Complex, Fraction } } if (test5(arg1)) { // type: string (convert to Complex) if (arguments.length === 2) { return signature1(arg0, convert8(arg1)); // signature: Complex, string } } } if (test2(arg0)) { // type: BigNumber if (test1(arg1)) { // type: Complex if (arguments.length === 2) { return signature1(convert6(arg0), arg1); // signature: BigNumber, Complex } } if (test2(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature2(arg0, arg1); // signature: BigNumber, BigNumber } } if (test4(arg1)) { // type: Unit if (arguments.length === 2) { return signature4(arg0, arg1); // signature: BigNumber, Unit } } if (test0(arg1)) { // type: number (convert to BigNumber) if (arguments.length === 2) { return signature2(arg0, convert1(arg1)); // signature: BigNumber, number } } if (test3(arg1)) { // type: Fraction (convert to BigNumber) if (arguments.length === 2) { return signature2(arg0, convert9(arg1)); // signature: BigNumber, Fraction } } if (test5(arg1)) { // type: string (convert to BigNumber) if (arguments.length === 2) { return signature2(arg0, convert10(arg1)); // signature: BigNumber, string } } if (test6(arg1)) { // type: boolean (convert to BigNumber) if (arguments.length === 2) { return signature2(arg0, convert11(arg1)); // signature: BigNumber, boolean } } if (test7(arg1)) { // type: null (convert to BigNumber) if (arguments.length === 2) { return signature2(arg0, convert12(arg1)); // signature ...
...
math.eval('sin(45 deg) ^ 2'); // 0.5
math.eval('9 / 3 + 2i'); // 3 + 2i
math.eval('det([-1, 2; 3, 1])'); // -7
// chaining
math.chain(3)
.add(4)
.multiply(2)
.done(); // 14
```
## Browser support
Math.js works on any ES5 compatible JavaScript engine: node.js 0.10, and Internet Explorer 9 and newer, and all other browsers (
Chrome, Firefox, Safari). If support for old browsers like Internet Explorer 8 is required, the [es5-shim](https://github.com/kriskowal
/es5-shim) library has to be loaded.
...
function norm(arg0, arg1) { "use strict"; var name = 'norm'; if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature0(arg0); // signature: number } if (test0(arg1)) { // type: number if (arguments.length === 2) { return signature1(arg0, arg1); // signature: number, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test1(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature1(arg0, arg1); // signature: number, BigNumber } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: string if (arguments.length === 2) { return signature1(arg0, arg1); // signature: number, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: Fraction (convert to BigNumber) if (arguments.length === 2) { return signature1(arg0, convert0(arg1)); // signature: number, Fraction } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test4(arg1)) { // type: boolean (convert to number) if (arguments.length === 2) { return signature1(arg0, convert1(arg1)); // signature: number, boolean } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test5(arg1)) { // type: null (convert to number) if (arguments.length === 2) { return signature1(arg0, convert2(arg1)); // signature: number, null } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'number,BigNumber,string'); } if (test6(arg0)) { // type: Complex if (arguments.length === 1) { return signature2(arg0); // signature: Complex } if (test0(arg1)) { // type: number if (arguments.length === 2) { return signature1(arg0, arg1); // signature: Complex, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test1(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature1(arg0, arg1); // signature: Complex, BigNumber } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: string if (arguments.length === 2) { return signature1(arg0, arg1); // signature: Complex, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: Fraction (convert to BigNumber) if (arguments.length === 2) { return signature1(arg0, convert0(arg1)); // signature: Complex, Fraction } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test4(arg1)) { // type: boolean (convert to number) if (arguments.length === 2) { return signature1(arg0, convert1(arg1)); // signature: Complex, boolean } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test5(arg1)) { // type: null (convert to number) if (arguments.length === 2) { return signature1(arg0, convert2(arg1)); // signature: Complex, null } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'number,BigNumber,string'); } if (test1(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature3(arg0); // signature: BigNumber } if (test0(arg1)) { // type: nu ...
...
/**
* Calculate the norm of a number, vector or matrix.
*
* The second parameter p is optional. If not provided, it defaults to 2.
*
* Syntax:
*
* math.norm(x)
* math.norm(x, p)
*
* Examples:
*
* math.abs(-3.5); // returns 3.5
* math.norm(-3.5); // returns 3.5
*
...
function not(arg0) { "use strict"; var name = 'not'; if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature0(arg0); // signature: number } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: Complex if (arguments.length === 1) { return signature1(arg0); // signature: Complex } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test2(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature2(arg0); // signature: BigNumber } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test3(arg0)) { // type: Unit if (arguments.length === 1) { return signature3(arg0); // signature: Unit } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test4(arg0)) { // type: Array if (arguments.length === 1) { return signature4(arg0); // signature: Array } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test5(arg0)) { // type: Matrix if (arguments.length === 1) { return signature4(arg0); // signature: Matrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test6(arg0)) { // type: Fraction (convert to BigNumber) if (arguments.length === 1) { return signature2(convert0(arg0)); // signature: Fraction } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test7(arg0)) { // type: string (convert to number) if (arguments.length === 1) { return signature0(convert1(arg0)); // signature: string } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test8(arg0)) { // type: boolean (convert to number) if (arguments.length === 1) { return signature0(convert2(arg0)); // signature: boolean } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test9(arg0)) { // type: null (convert to number) if (arguments.length === 1) { return signature0(convert3(arg0)); // signature: null } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'number,Complex,BigNumber,Unit,Array,Matrix'); }
...
/**
* Logical `not`. Flips boolean value of a given parameter.
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.not(x)
*
* Examples:
*
* math.not(2); // returns false
* math.not(0); // returns true
* math.not(true); // returns false
*
...
function nthRoot(arg0, arg1) { "use strict"; var name = 'nthRoot'; if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature0(arg0); // signature: number } if (test0(arg1)) { // type: number if (arguments.length === 2) { return signature1(arg0, arg1); // signature: number, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test1(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature2(convert0(arg0), arg1); // signature: number, BigNumber } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: Array if (arguments.length === 2) { return signature3(arg0, arg1); // signature: number, Array } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: Matrix if (arguments.length === 2) { return signature4(arg0, arg1); // signature: number, Matrix } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test4(arg1)) { // type: Fraction (convert to BigNumber) if (arguments.length === 2) { return signature2(convert0(arg0), convert1(arg1)); // signature: number, Fraction } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test5(arg1)) { // type: string (convert to number) if (arguments.length === 2) { return signature1(arg0, convert2(arg1)); // signature: number, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test6(arg1)) { // type: boolean (convert to number) if (arguments.length === 2) { return signature1(arg0, convert3(arg1)); // signature: number, boolean } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test7(arg1)) { // type: null (convert to number) if (arguments.length === 2) { return signature1(arg0, convert4(arg1)); // signature: number, null } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'number,BigNumber,Array,Matrix'); } if (test8(arg0)) { // type: Complex if (arguments.length === 1) { return signature5(arg0); // signature: Complex } if (test0(arg1)) { // type: number if (arguments.length === 2) { return signature6(arg0, arg1); // signature: Complex, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test5(arg1)) { // type: string (convert to number) if (arguments.length === 2) { return signature6(arg0, convert2(arg1)); // signature: Complex, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test6(arg1)) { // type: boolean (convert to number) if (arguments.length === 2) { return signature6(arg0, convert3(arg1)); // signature: Complex, boolean } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test7(arg1)) { // type: null (convert to number) if (arguments.length === 2) { return signature6(arg0, convert4(arg1)); // signature: Complex, null } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'number'); } if (test1(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature7(arg0); // signature: BigNumber } if ...
...
*
* x^root = A
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.nthRoot(a)
* math.nthRoot(a, root)
*
* Examples:
*
* math.nthRoot(9, 2); // returns 3, as 3^2 == 9
* math.sqrt(9); // returns 3, as 3^2 == 9
* math.nthRoot(64, 3); // returns 4, as 4^3 == 64
...
function number(arg0, arg1) { "use strict"; var name = 'number'; if (arguments.length === 0) { return signature0(); // signature: } if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature1(arg0); // signature: number } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature2(arg0); // signature: BigNumber } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test2(arg0)) { // type: Fraction if (arguments.length === 1) { return signature3(arg0); // signature: Fraction } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test3(arg0)) { // type: Unit if (arguments.length === 1) { return signature4(arg0); // signature: Unit } if (test3(arg1)) { // type: Unit if (arguments.length === 2) { return signature5(arg0, arg1); // signature: Unit, Unit } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test4(arg1)) { // type: string if (arguments.length === 2) { return signature5(arg0, arg1); // signature: Unit, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test0(arg1)) { // type: number (convert to string) if (arguments.length === 2) { return signature5(arg0, convert0(arg1)); // signature: Unit, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test5(arg1)) { // type: boolean (convert to string) if (arguments.length === 2) { return signature5(arg0, convert1(arg1)); // signature: Unit, boolean } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test6(arg1)) { // type: null (convert to string) if (arguments.length === 2) { return signature5(arg0, convert2(arg1)); // signature: Unit, null } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'Unit,string'); } if (test4(arg0)) { // type: string if (arguments.length === 1) { return signature6(arg0); // signature: string } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test7(arg0)) { // type: Array if (arguments.length === 1) { return signature7(arg0); // signature: Array } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test8(arg0)) { // type: Matrix if (arguments.length === 1) { return signature7(arg0); // signature: Matrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test5(arg0)) { // type: boolean (convert to number) if (arguments.length === 1) { return signature1(convert3(arg0)); // signature: boolean } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test6(arg0)) { // type: null (convert to number) if (arguments.length === 1) { return signature1(convert4(arg0)); // signature: null } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'number,BigNumber,Fraction,Unit,string,Array,Matrix'); }
...
function factory (type, config, load, typed) {
/**
* Create a number or convert a string, boolean, or unit to a number.
* When value is a matrix, all elements will be converted to number.
*
* Syntax:
*
* math.number(value)
* math.number(unit, valuelessUnit)
*
* Examples:
*
* math.number(2); // returns number 2
* math.number('7.2'); // returns number 7.2
* math.number(true); // returns number 1
...
off = function () { [native code] }
n/a
on = function () { [native code] }
...
}
// load math.js now, right *after* loading the prompt.
var math = getMath();
// TODO: automatic insertion of 'ans' before operators like +, -, *, /
rl.on('line', function(line) {
var expr = line.trim();
switch (expr.toLowerCase()) {
case 'quit':
case 'exit':
// exit application
rl.close();
...
once = function () { [native code] }
n/a
function ones(arg0, arg1) { "use strict"; var name = 'ones'; if (arguments.length === 0) { return signature0(); // signature: } if (test0(arg0)) { // type: Array if (arguments.length === 1) { return signature1(arg0); // signature: Array } if (test1(arg1)) { // type: string if (arguments.length === 2) { return signature2(arg0, arg1); // signature: Array, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: number (convert to string) if (arguments.length === 2) { return signature2(arg0, convert0(arg1)); // signature: Array, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: boolean (convert to string) if (arguments.length === 2) { return signature2(arg0, convert1(arg1)); // signature: Array, boolean } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test4(arg1)) { // type: null (convert to string) if (arguments.length === 2) { return signature2(arg0, convert2(arg1)); // signature: Array, null } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'string'); } if (test5(arg0)) { // type: Matrix if (arguments.length === 1) { return signature3(arg0); // signature: Matrix } if (test1(arg1)) { // type: string if (arguments.length === 2) { return signature2(arg0, arg1); // signature: Matrix, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: number (convert to string) if (arguments.length === 2) { return signature2(arg0, convert0(arg1)); // signature: Matrix, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: boolean (convert to string) if (arguments.length === 2) { return signature2(arg0, convert1(arg1)); // signature: Matrix, boolean } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test4(arg1)) { // type: null (convert to string) if (arguments.length === 2) { return signature2(arg0, convert2(arg1)); // signature: Matrix, null } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'string'); } if (test2(arg0) || test6(arg0) || test1(arg0) || test7(arg0) || test3(arg0) || test3(arg0) || test3(arg0) || test4(arg0) || test4 (arg0) || test4(arg0)) { // type: ...number|BigNumber|string|Fraction|boolean|null var varArgs = [arg0]; for (var i = 1; i < arguments.length; i++) { if (test2(arguments[i]) || test6(arguments[i]) || test1(arguments[i])) { varArgs.push(arguments[i]); } else if (test7(arguments[i])) { varArgs.push(convert3(arguments[i])); } else if (test3(arguments[i])) { varArgs.push(convert4(arguments[i])); } else if (test3(arguments[i])) { varArgs.push(convert5(arguments[i])); } else if (test3(arguments[i])) { varArgs.push(convert1(arguments[i])); } else if (test4(arguments[i])) { varArgs.push(convert6(arguments[i])); } else if (test4(arguments[i])) { varArgs.push(convert2(arguments[i])); } else if (test4(arguments[i])) { varArgs.push(convert7(arguments[i])); } else { throw createError(name, arguments.length, i, arguments[i], 'number,BigNumber,string'); } } return signature4(varArgs); // signature: ...number|BigNum ...
...
/**
* Create a matrix filled with ones. The created matrix can have one or
* multiple dimensions.
*
* Syntax:
*
* math.ones(m)
* math.ones(m, format)
* math.ones(m, n)
* math.ones(m, n, format)
* math.ones([m, n])
* math.ones([m, n], format)
* math.ones([m, n, p, ...])
* math.ones([m, n, p, ...], format)
...
function or(arg0, arg1) { "use strict"; var name = 'or'; if (test0(arg0)) { // type: number if (test0(arg1)) { // type: number if (arguments.length === 2) { return signature0(arg0, arg1); // signature: number, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test1(arg1)) { // type: Complex if (arguments.length === 2) { return signature1(convert0(arg0), arg1); // signature: number, Complex } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature2(convert1(arg0), arg1); // signature: number, BigNumber } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: Fraction (convert to BigNumber) if (arguments.length === 2) { return signature2(convert1(arg0), convert2(arg1)); // signature: number, Fraction } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test4(arg1)) { // type: string (convert to number) if (arguments.length === 2) { return signature0(arg0, convert3(arg1)); // signature: number, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test5(arg1)) { // type: boolean (convert to number) if (arguments.length === 2) { return signature0(arg0, convert4(arg1)); // signature: number, boolean } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test6(arg1)) { // type: null (convert to number) if (arguments.length === 2) { return signature0(arg0, convert5(arg1)); // signature: number, null } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } } if (test1(arg0)) { // type: Complex if (test1(arg1)) { // type: Complex if (arguments.length === 2) { return signature1(arg0, arg1); // signature: Complex, Complex } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test0(arg1)) { // type: number (convert to Complex) if (arguments.length === 2) { return signature1(arg0, convert0(arg1)); // signature: Complex, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: BigNumber (convert to Complex) if (arguments.length === 2) { return signature1(arg0, convert6(arg1)); // signature: Complex, BigNumber } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: Fraction (convert to Complex) if (arguments.length === 2) { return signature1(arg0, convert7(arg1)); // signature: Complex, Fraction } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test4(arg1)) { // type: string (convert to Complex) if (arguments.length === 2) { return signature1(arg0, convert8(arg1)); // signature: Complex, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } } if (test2(arg0)) { // type: BigNumber if (test1(arg1)) { // type: Complex if (arguments.length === 2) { return signature1(convert6(arg0), arg1); // signature: BigNumber, Complex } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature2(arg0, arg1); // si ...
...
/**
* Logical `or`. Test if at least one value is defined with a nonzero/nonempty value.
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.or(x, y)
*
* Examples:
*
* math.or(2, 4); // returns true
*
* a = [2, 5, 0];
* b = [0, 22, 0];
...
function parse(arg0, arg1) { "use strict"; var name = 'parse'; if (test0(arg0)) { // type: string if (arguments.length === 1) { return signature0(arg0); // signature: string } if (test1(arg1)) { // type: Object if (arguments.length === 2) { return signature0(arg0, arg1); // signature: string, Object } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'Object'); } if (test2(arg0)) { // type: Array if (arguments.length === 1) { return signature0(arg0); // signature: Array } if (test1(arg1)) { // type: Object if (arguments.length === 2) { return signature0(arg0, arg1); // signature: Array, Object } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'Object'); } if (test3(arg0)) { // type: Matrix if (arguments.length === 1) { return signature0(arg0); // signature: Matrix } if (test1(arg1)) { // type: Object if (arguments.length === 2) { return signature0(arg0, arg1); // signature: Matrix, Object } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'Object'); } if (test4(arg0)) { // type: number (convert to string) if (arguments.length === 1) { return signature0(convert0(arg0)); // signature: number } if (test1(arg1)) { // type: Object if (arguments.length === 2) { return signature0(convert0(arg0), arg1); // signature: number, Object } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'Object'); } if (test5(arg0)) { // type: boolean (convert to string) if (arguments.length === 1) { return signature0(convert1(arg0)); // signature: boolean } if (test1(arg1)) { // type: Object if (arguments.length === 2) { return signature0(convert1(arg0), arg1); // signature: boolean, Object } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'Object'); } if (test6(arg0)) { // type: null (convert to string) if (arguments.length === 1) { return signature0(convert2(arg0)); // signature: null } if (test1(arg1)) { // type: Object if (arguments.length === 2) { return signature0(convert2(arg0), arg1); // signature: null, Object } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'Object'); } throw createError(name, arguments.length, 0, arguments[0], 'string,Array,Matrix'); }
...
if (!expr) {
break;
}
switch (mode) {
case 'eval':
// evaluate expression
try {
var node = math.parse(expr);
var res = node.eval(scope);
if (res && res.isResultSet) {
// we can have 0 or 1 results in the ResultSet, as the CLI
// does not allow multiple expressions separated by a return
res = res.entries[0];
node = node.blocks
...
function parser() { "use strict"; var name = 'parser'; if (arguments.length === 0) { return signature0(); // signature: } if (arguments.length > 0) { throw createError(name, arguments.length, 0, arguments[0]); } }
...
* parser.remove(name); // clear a variable from the
* // parsers scope
* parser.clear(); // clear the parsers scope
*
* Example usage:
* var parser = new Parser();
* // Note: there is a convenience method which can be used instead:
* // var parser = new math.parser();
*
* // evaluate expressions
* parser.eval('sqrt(3^2 + 4^2)'); // 5
* parser.eval('sqrt(-4)'); // 2i
* parser.eval('2 inch in cm'); // 5.08 cm
* parser.eval('cos(45 deg)'); // 0.7071067811865476
*
...
function partitionSelect(arg0, arg1, arg2) { "use strict"; var name = 'partitionSelect'; if (test0(arg0)) { // type: Array if (test1(arg1)) { // type: number if (arguments.length === 2) { return signature0(arg0, arg1); // signature: Array, number } if (test2(arg2)) { // type: string if (arguments.length === 3) { return signature1(arg0, arg1, arg2); // signature: Array, number, string } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } if (test3(arg2)) { // type: function if (arguments.length === 3) { return signature2(arg0, arg1, arg2); // signature: Array, number, function } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } if (test1(arg2)) { // type: number (convert to string) if (arguments.length === 3) { return signature1(arg0, arg1, convert0(arg2)); // signature: Array, number, number } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } if (test4(arg2)) { // type: boolean (convert to string) if (arguments.length === 3) { return signature1(arg0, arg1, convert1(arg2)); // signature: Array, number, boolean } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } if (test5(arg2)) { // type: null (convert to string) if (arguments.length === 3) { return signature1(arg0, arg1, convert2(arg2)); // signature: Array, number, null } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } throw createError(name, arguments.length, 2, arguments[2], 'string,function'); } if (test2(arg1)) { // type: string (convert to number) if (arguments.length === 2) { return signature0(arg0, convert3(arg1)); // signature: Array, string } if (test2(arg2)) { // type: string if (arguments.length === 3) { return signature1(arg0, convert3(arg1), arg2); // signature: Array, string, string } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } if (test3(arg2)) { // type: function if (arguments.length === 3) { return signature2(arg0, convert3(arg1), arg2); // signature: Array, string, function } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } if (test1(arg2)) { // type: number (convert to string) if (arguments.length === 3) { return signature1(arg0, convert3(arg1), convert0(arg2)); // signature: Array, string, number } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } if (test4(arg2)) { // type: boolean (convert to string) if (arguments.length === 3) { return signature1(arg0, convert3(arg1), convert1(arg2)); // signature: Array, string, boolean } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } if (test5(arg2)) { // type: null (convert to string) if (arguments.length === 3) { return signature1(arg0, convert3(arg1), convert2(arg2)); // signature: Array, string, null } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } throw createError(name, arguments.length, 2, arguments[2], 'string,function'); } if (test4(arg1)) { // type: boolean (convert to number) if (arguments.length === 2) { return signature0(arg0, convert4(arg1)); // signature: Array, boolean } if (test2(arg2)) { // type: string if (arguments.length === 3) { ...
...
/**
* Partition-based selection of an array or 1D matrix.
* Will find the kth smallest value, and mutates the input array.
* Uses Quickselect.
*
* Syntax:
*
* math.partitionSelect(x, k)
* math.partitionSelect(x, k, compare)
*
* Examples:
*
* math.partitionSelect([5, 10, 1], 2); // returns 10
* math.partitionSelect(['C', 'B', 'A', 'D'], 1); // returns 'B'
*
...
function permutations(arg0, arg1) { "use strict"; var name = 'permutations'; if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature0(arg0); // signature: number } if (test0(arg1)) { // type: number if (arguments.length === 2) { return signature1(arg0, arg1); // signature: number, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test1(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature2(convert0(arg0), arg1); // signature: number, BigNumber } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: Fraction (convert to BigNumber) if (arguments.length === 2) { return signature2(convert0(arg0), convert1(arg1)); // signature: number, Fraction } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: string (convert to number) if (arguments.length === 2) { return signature1(arg0, convert2(arg1)); // signature: number, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test4(arg1)) { // type: boolean (convert to number) if (arguments.length === 2) { return signature1(arg0, convert3(arg1)); // signature: number, boolean } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test5(arg1)) { // type: null (convert to number) if (arguments.length === 2) { return signature1(arg0, convert4(arg1)); // signature: number, null } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'number,BigNumber'); } if (test1(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature0(arg0); // signature: BigNumber } if (test1(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature2(arg0, arg1); // signature: BigNumber, BigNumber } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test0(arg1)) { // type: number (convert to BigNumber) if (arguments.length === 2) { return signature2(arg0, convert0(arg1)); // signature: BigNumber, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: Fraction (convert to BigNumber) if (arguments.length === 2) { return signature2(arg0, convert1(arg1)); // signature: BigNumber, Fraction } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: string (convert to BigNumber) if (arguments.length === 2) { return signature2(arg0, convert5(arg1)); // signature: BigNumber, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test4(arg1)) { // type: boolean (convert to BigNumber) if (arguments.length === 2) { return signature2(arg0, convert6(arg1)); // signature: BigNumber, boolean } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test5(arg1)) { // type: null (convert to BigNumber) if (arguments.length === 2) { return signature2(arg0, convert7(arg1)); // signature: BigNumber, null } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'BigNumber'); } if (test2(arg0)) { // type: Fracti ...
...
* from a set of `n` elements.
*
* Permutations only takes integer arguments.
* The following condition must be enforced: k <= n.
*
* Syntax:
*
* math.permutations(n)
* math.permutations(n, k)
*
* Examples:
*
* math.permutations(5); // 120
* math.permutations(5, 3); // 60
*
...
function pow(arg0, arg1) { "use strict"; var name = 'pow'; if (test0(arg0)) { // type: number if (test0(arg1)) { // type: number if (arguments.length === 2) { return signature0(arg0, arg1); // signature: number, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test1(arg1)) { // type: Complex if (arguments.length === 2) { return signature1(convert0(arg0), arg1); // signature: number, Complex } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature2(convert1(arg0), arg1); // signature: number, BigNumber } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: Fraction if (arguments.length === 2) { return signature3(convert2(arg0), arg1); // signature: number, Fraction } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test4(arg1)) { // type: string (convert to number) if (arguments.length === 2) { return signature0(arg0, convert3(arg1)); // signature: number, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test5(arg1)) { // type: boolean (convert to number) if (arguments.length === 2) { return signature0(arg0, convert4(arg1)); // signature: number, boolean } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test6(arg1)) { // type: null (convert to number) if (arguments.length === 2) { return signature0(arg0, convert5(arg1)); // signature: number, null } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'number,Complex,BigNumber,Fraction'); } if (test1(arg0)) { // type: Complex if (test1(arg1)) { // type: Complex if (arguments.length === 2) { return signature1(arg0, arg1); // signature: Complex, Complex } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test0(arg1)) { // type: number (convert to Complex) if (arguments.length === 2) { return signature1(arg0, convert0(arg1)); // signature: Complex, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: BigNumber (convert to Complex) if (arguments.length === 2) { return signature1(arg0, convert6(arg1)); // signature: Complex, BigNumber } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: Fraction (convert to Complex) if (arguments.length === 2) { return signature1(arg0, convert7(arg1)); // signature: Complex, Fraction } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test4(arg1)) { // type: string (convert to Complex) if (arguments.length === 2) { return signature1(arg0, convert8(arg1)); // signature: Complex, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'Complex'); } if (test2(arg0)) { // type: BigNumber if (test1(arg1)) { // type: Complex if (arguments.length === 2) { return signature1(convert6(arg0), arg1); // signature: BigNumber, Complex } if (arguments.length > 2) { throw createError(name, arguments.length, 2, argume ...
...
var math = require('mathjs');
// functions and constants
math.round(math.e, 3); // 2.718
math.atan2(3, -3) / math.pi; // 0.75
math.log(1000, 10); // 3
math.sqrt(-4); // 2i
math.pow([[-1, 2], [3, 1]], 2); // [[7, 0], [0, 7]]
math.derivative('x^2 + x', 'x'); // 2 * x + 1
// expressions
math.eval('12 / (2.3 + 0.7)'); // 4
math.eval('5.08 cm to inch'); // 2 inch
math.eval('sin(45 deg) ^ 2'); // 0.5
math.eval('9 / 3 + 2i'); // 3 + 2i
...
function print(arg0, arg1, arg2) { "use strict"; var name = 'print'; if (test0(arg0)) { // type: string if (test1(arg1)) { // type: Object if (arguments.length === 2) { return signature0(arg0, arg1); // signature: string, Object } if (test2(arg2)) { // type: number if (arguments.length === 3) { return signature0(arg0, arg1, arg2); // signature: string, Object, number } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } if (test0(arg2)) { // type: string (convert to number) if (arguments.length === 3) { return signature0(arg0, arg1, convert0(arg2)); // signature: string, Object, string } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } if (test3(arg2)) { // type: boolean (convert to number) if (arguments.length === 3) { return signature0(arg0, arg1, convert1(arg2)); // signature: string, Object, boolean } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } if (test4(arg2)) { // type: null (convert to number) if (arguments.length === 3) { return signature0(arg0, arg1, convert2(arg2)); // signature: string, Object, null } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } if (test1(arg2)) { // type: Object if (arguments.length === 3) { return signature0(arg0, arg1, arg2); // signature: string, Object, Object } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } throw createError(name, arguments.length, 2, arguments[2], 'number,Object'); } throw createError(name, arguments.length, 1, arguments[1], 'Object'); } if (test2(arg0)) { // type: number (convert to string) if (test1(arg1)) { // type: Object if (arguments.length === 2) { return signature0(convert3(arg0), arg1); // signature: number, Object } if (test2(arg2)) { // type: number if (arguments.length === 3) { return signature0(convert3(arg0), arg1, arg2); // signature: number, Object, number } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } if (test0(arg2)) { // type: string (convert to number) if (arguments.length === 3) { return signature0(convert3(arg0), arg1, convert0(arg2)); // signature: number, Object, string } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } if (test3(arg2)) { // type: boolean (convert to number) if (arguments.length === 3) { return signature0(convert3(arg0), arg1, convert1(arg2)); // signature: number, Object, boolean } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } if (test4(arg2)) { // type: null (convert to number) if (arguments.length === 3) { return signature0(convert3(arg0), arg1, convert2(arg2)); // signature: number, Object, null } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } if (test1(arg2)) { // type: Object if (arguments.length === 3) { return signature0(convert3(arg0), arg1, arg2); // signature: number, Object, Object } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } throw createError(name, arguments.length, 2, arguments[2], 'number,Object'); } throw createError(name, arguments.length, 1, arguments[1], 'Object'); } if (test3(arg0)) { // type: boolean (convert to string) if (test1(arg1)) { // typ ...
...
function factory (type, config, load, typed) {
/**
* Interpolate values into a string template.
*
* Syntax:
*
* math.print(template, values)
* math.print(template, values, precision)
* math.print(template, values, options)
*
* Example usage:
*
* // the following outputs: 'Lucy is 5 years old'
* math.print('Lucy is $age years old', {age: 5});
...
function prod(arg0, arg1) { "use strict"; var name = 'prod'; if (test0(arg0)) { // type: Array if (arguments.length === 1) { return signature0(arg0); // signature: Array } if (test1(arg1)) { // type: number if (arguments.length === 2) { return signature1(arg0, arg1); // signature: Array, number } } if (test2(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature1(arg0, arg1); // signature: Array, BigNumber } } if (test3(arg1)) { // type: Fraction (convert to BigNumber) if (arguments.length === 2) { return signature1(arg0, convert0(arg1)); // signature: Array, Fraction } } if (test4(arg1)) { // type: string (convert to number) if (arguments.length === 2) { return signature1(arg0, convert1(arg1)); // signature: Array, string } } if (test5(arg1)) { // type: boolean (convert to number) if (arguments.length === 2) { return signature1(arg0, convert2(arg1)); // signature: Array, boolean } } if (test6(arg1)) { // type: null (convert to number) if (arguments.length === 2) { return signature1(arg0, convert3(arg1)); // signature: Array, null } } } if (test7(arg0)) { // type: Matrix if (arguments.length === 1) { return signature0(arg0); // signature: Matrix } if (test1(arg1)) { // type: number if (arguments.length === 2) { return signature1(arg0, arg1); // signature: Matrix, number } } if (test2(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature1(arg0, arg1); // signature: Matrix, BigNumber } } if (test3(arg1)) { // type: Fraction (convert to BigNumber) if (arguments.length === 2) { return signature1(arg0, convert0(arg1)); // signature: Matrix, Fraction } } if (test4(arg1)) { // type: string (convert to number) if (arguments.length === 2) { return signature1(arg0, convert1(arg1)); // signature: Matrix, string } } if (test5(arg1)) { // type: boolean (convert to number) if (arguments.length === 2) { return signature1(arg0, convert2(arg1)); // signature: Matrix, boolean } } if (test6(arg1)) { // type: null (convert to number) if (arguments.length === 2) { return signature1(arg0, convert3(arg1)); // signature: Matrix, null } } } if (arguments.length > 0) { var varArgs = []; for (var i = 0; i < arguments.length; i++) { varArgs.push(arguments[i]); } return signature2(varArgs); // signature: ...any } throw createError(name, arguments.length, 0, arguments[0], 'Array,Matrix,any'); }
...
/**
* Compute the product of a matrix or a list with values.
* In case of a (multi dimensional) array or matrix, the sum of all
* elements will be calculated.
*
* Syntax:
*
* math.prod(a, b, c, ...)
* math.prod(A)
*
* Examples:
*
* math.multiply(2, 3); // returns 6
* math.prod(2, 3); // returns 6
* math.prod(2, 3, 4); // returns 24
...
function qr(arg0) { "use strict"; var name = 'qr'; if (test0(arg0)) { // type: Array if (arguments.length === 1) { return signature0(arg0); // signature: Array } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: DenseMatrix if (arguments.length === 1) { return signature1(arg0); // signature: DenseMatrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test2(arg0)) { // type: SparseMatrix if (arguments.length === 1) { return signature2(arg0); // signature: SparseMatrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test3(arg0)) { // type: Matrix (convert to Array) if (arguments.length === 1) { return signature0(convert0(arg0)); // signature: Matrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'Array,DenseMatrix,SparseMatrix'); }
n/a
function quantileSeq(data, probOrN, sorted) { var probArr, dataArr, one; if (arguments.length < 2 || arguments.length > 3) { throw new SyntaxError('Function quantileSeq requires two or three parameters'); } if (isCollection(data)) { sorted = sorted || false; if (typeof sorted === 'boolean') { dataArr = data.valueOf(); if (isNumber(probOrN)) { if (probOrN < 0) { throw new Error('N/prob must be non-negative'); } if (probOrN <= 1) { // quantileSeq([a, b, c, d, ...], prob[,sorted]) return _quantileSeq(dataArr, probOrN, sorted); } if (probOrN > 1) { // quantileSeq([a, b, c, d, ...], N[,sorted]) if (!isInteger(probOrN)) { throw new Error('N must be a positive integer'); } var nPlusOne = probOrN + 1; probArr = new Array(probOrN); for (var i = 0; i < probOrN;) { probArr[i] = _quantileSeq(dataArr, (++i) / nPlusOne, sorted); } return probArr; } } if (probOrN && probOrN.isBigNumber) { if (probOrN.isNegative()) { throw new Error('N/prob must be non-negative'); } one = new probOrN.constructor(1); if (probOrN.lte(one)) { // quantileSeq([a, b, c, d, ...], prob[,sorted]) return _quantileSeq(dataArr, probOrN, sorted); } if (probOrN.gt(one)) { // quantileSeq([a, b, c, d, ...], N[,sorted]) if (!probOrN.isInteger()) { throw new Error('N must be a positive integer'); } // largest possible Array length is 2^32-1; // 2^32 < 10^15, thus safe conversion guaranteed var intN = probOrN.toNumber(); if (intN > 4294967295) { throw new Error('N must be less than or equal to 2^32-1, as that is the maximum length of an Array'); } var nPlusOne = new type.BigNumber(intN + 1); probArr = new Array(intN); for (var i = 0; i < intN;) { probArr[i] = _quantileSeq(dataArr, new type.BigNumber(++i).div(nPlusOne), sorted); } return probArr; } } if (Array.isArray(probOrN)) { // quantileSeq([a, b, c, d, ...], [prob1, prob2, ...][,sorted]) probArr = new Array(probOrN.length); for (var i = 0; i < probArr.length; ++i) { var currProb = probOrN[i]; if (isNumber(currProb)) { if (currProb < 0 || currProb > 1) { throw new Error('Probability must be between 0 and 1, inclusive'); } } else if (currProb && currProb.isBigNumber) { one = new currProb.constructor(1); if (currProb.isNegative() || currProb.gt(one)) { throw new Error('Probability must be between 0 and 1, inclusive'); } } else { throw new TypeError('Unexpected type of argument in function quantileSeq'); // FIXME: becomes redundant when converted to typed-function } probArr[i] = _quantileSeq(dataArr, currProb, sorted); } return probArr; } throw new TypeError('Unexpected type of argument in function quantileSeq'); // FIXME: becomes redundant when converted to typed-function } throw new TypeError('Unexpected type of argument in function quantileSeq'); // FIXME: becomes redundant when converted to typed -function } throw new TypeError('Unexpected type of argument in function quantileSeq'); // FIXME: becomes redundant when converted to typed -function }
...
* Supported types of probability are: Number, BigNumber
*
* In case of a (multi dimensional) array or matrix, the prob order quantile
* of all elements will be calculated.
*
* Syntax:
*
* math.quantileSeq(A, prob[, sorted])
* math.quantileSeq(A, [prob1, prob2, ...][, sorted])
* math.quantileSeq(A, N[, sorted])
*
* Examples:
*
* math.quantileSeq([3, -1, 5, 7], 0.5); // returns 4
* math.quantileSeq([3, -1, 5, 7], [1/3, 2/3]); // returns [3, 5]
...
function range(arg0, arg1, arg2, arg3) { "use strict"; var name = 'range'; if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature0(convert0(arg0)); // signature: number } if (test0(arg1)) { // type: number if (arguments.length === 2) { return signature1(arg0, arg1); // signature: number, number } if (test0(arg2)) { // type: number if (arguments.length === 3) { return signature2(arg0, arg1, arg2); // signature: number, number, number } if (test1(arg3)) { // type: boolean if (arguments.length === 4) { return signature3(arg0, arg1, arg2, arg3); // signature: number, number, number, boolean } if (arguments.length > 4) { throw createError(name, arguments.length, 4, arguments[4]); } } throw createError(name, arguments.length, 3, arguments[3], 'boolean'); } if (test2(arg2)) { // type: BigNumber if (arguments.length === 3) { return signature4(convert1(arg0), convert1(arg1), arg2); // signature: number, number, BigNumber } if (test1(arg3)) { // type: boolean if (arguments.length === 4) { return signature5(convert1(arg0), convert1(arg1), arg2, arg3); // signature: number, number, BigNumber, boolean } if (arguments.length > 4) { throw createError(name, arguments.length, 4, arguments[4]); } } throw createError(name, arguments.length, 3, arguments[3], 'boolean'); } if (test1(arg2)) { // type: boolean if (arguments.length === 3) { return signature6(arg0, arg1, arg2); // signature: number, number, boolean } if (test1(arg3)) { // type: boolean if (arguments.length === 4) { return signature3(arg0, arg1, convert2(arg2), arg3); // signature: number, number, boolean, boolean } if (arguments.length > 4) { throw createError(name, arguments.length, 4, arguments[4]); } } throw createError(name, arguments.length, 3, arguments[3], 'boolean'); } if (test3(arg2)) { // type: Fraction (convert to BigNumber) if (arguments.length === 3) { return signature4(convert1(arg0), convert1(arg1), convert3(arg2)); // signature: number, number, Fraction } if (test1(arg3)) { // type: boolean if (arguments.length === 4) { return signature5(convert1(arg0), convert1(arg1), convert3(arg2), arg3); // signature: number, number, Fraction, boolean } if (arguments.length > 4) { throw createError(name, arguments.length, 4, arguments[4]); } } throw createError(name, arguments.length, 3, arguments[3], 'boolean'); } if (test4(arg2)) { // type: string (convert to number) if (arguments.length === 3) { return signature2(arg0, arg1, convert4(arg2)); // signature: number, number, string } if (test1(arg3)) { // type: boolean if (arguments.length === 4) { return signature3(arg0, arg1, convert4(arg2), arg3); // signature: number, number, string, boolean } if (arguments.length > 4) { throw createError(name, arguments.length, 4, arguments[4]); } } throw createError(name, arguments.length, 3, arguments[3], 'boolean'); } if (test5(arg2)) { // type: null (convert to number) if (arguments.length === 3) { return signature2(arg0, arg1, convert5(arg2)); // signature: number, number, null } if (test1(arg3)) { // type: boolean if (arguments.length === 4) { return signature3(arg0, arg1, convert5(arg2), arg3); // signature: number, number, null, boolean } if (arguments.length > 4) { throw createError(name, arguments.length, 4, arguments[4]); } } throw createError(name, arguments.length, 3, ar ...
...
* the name of the argument, and the value is `true`.
* The object may not be mutated, but must be
* extended instead.
* @return {string} js
* @private
*/
RangeNode.prototype._compile = function (defs, args) {
return 'math.range(' +
this.start._compile(defs, args) + ', ' +
this.end._compile(defs, args) +
(this.step ? (', ' + this.step._compile(defs, args)) : '') +
')';
};
/**
...
function re(arg0) { "use strict"; var name = 're'; if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature0(arg0); // signature: number } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: Complex if (arguments.length === 1) { return signature1(arg0); // signature: Complex } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test2(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature2(arg0); // signature: BigNumber } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test3(arg0)) { // type: Array if (arguments.length === 1) { return signature3(arg0); // signature: Array } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test4(arg0)) { // type: Matrix if (arguments.length === 1) { return signature3(arg0); // signature: Matrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test5(arg0)) { // type: Fraction (convert to BigNumber) if (arguments.length === 1) { return signature2(convert0(arg0)); // signature: Fraction } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test6(arg0)) { // type: string (convert to number) if (arguments.length === 1) { return signature0(convert1(arg0)); // signature: string } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test7(arg0)) { // type: boolean (convert to number) if (arguments.length === 1) { return signature0(convert2(arg0)); // signature: boolean } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test8(arg0)) { // type: null (convert to number) if (arguments.length === 1) { return signature0(convert3(arg0)); // signature: null } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'number,Complex,BigNumber,Array,Matrix'); }
...
* Syntax:
*
* math.im(x)
*
* Examples:
*
* var a = math.complex(2, 3);
* math.re(a); // returns number 2
* math.im(a); // returns number 3
*
* math.re(math.complex('-5.2i')); // returns number -5.2
* math.re(math.complex(2.4)); // returns number 0
*
* See also:
*
...
function reshape(arg0, arg1) { "use strict"; var name = 'reshape'; if (test0(arg0)) { // type: Array if (test0(arg1)) { // type: Array if (arguments.length === 2) { return signature0(arg0, arg1); // signature: Array, Array } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test1(arg1)) { // type: Matrix (convert to Array) if (arguments.length === 2) { return signature0(arg0, convert0(arg1)); // signature: Array, Matrix } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'Array'); } if (test1(arg0)) { // type: Matrix if (test0(arg1)) { // type: Array if (arguments.length === 2) { return signature1(arg0, arg1); // signature: Matrix, Array } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test1(arg1)) { // type: Matrix (convert to Array) if (arguments.length === 2) { return signature1(arg0, convert0(arg1)); // signature: Matrix, Matrix } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'Array'); } throw createError(name, arguments.length, 0, arguments[0], 'Array,Matrix'); }
...
var matrix = load(require('../../type/matrix/function/matrix'));
/**
* Reshape a multi dimensional array to fit the specified dimensions
*
* Syntax:
*
* math.reshape(x, sizes)
*
* Examples:
*
* math.reshape([1, 2, 3, 4, 5, 6], [2, 3]);
* // returns Array [[1, 2, 3], [4, 5, 6]]
*
* math.reshape([[1, 2], [3, 4]], [1, 4]);
...
function resize(x, size, defaultValue) { if (arguments.length != 2 && arguments.length != 3) { throw new ArgumentsError('resize', arguments.length, 2, 3); } if (size && size.isMatrix === true) { size = size.valueOf(); // get Array } if (size.length && size[0] && size[0].isBigNumber === true) { // convert bignumbers to numbers size = size.map(function (value) { return (value && value.isBigNumber === true) ? value.toNumber() : value; }); } // check x is a Matrix if (x && x.isMatrix === true) { // use optimized matrix implementation, return copy return x.resize(size, defaultValue, true); } if (typeof x === 'string') { // resize string return _resizeString(x, size, defaultValue); } // check result should be a matrix var asMatrix = Array.isArray(x) ? false : (config.matrix !== 'Array'); if (size.length == 0) { // output a scalar while (Array.isArray(x)) { x = x[0]; } return clone(x); } else { // output an array/matrix if (!Array.isArray(x)) { x = [x]; } x = clone(x); var res = array.resize(x, size, defaultValue); return asMatrix ? matrix(res) : res; } }
...
// get matrix storage constructor
var F = type.Matrix.storage(format);
// create diagonal matrix (use optimized implementation for storage format)
return F.diagonal(size, one, 0, defaultValue);
}
// create and resize array
var res = array.resize([], size, defaultValue);
// fill in ones on the diagonal
var minimum = rows < cols ? rows : cols;
// fill diagonal
for (var d = 0; d < minimum; d++) {
res[d][d] = one;
}
return res;
...
function rightArithShift(arg0, arg1) { "use strict"; var name = 'rightArithShift'; if (test0(arg0)) { // type: number if (test0(arg1)) { // type: number if (arguments.length === 2) { return signature0(arg0, arg1); // signature: number, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test1(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature1(convert0(arg0), arg1); // signature: number, BigNumber } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: Array if (arguments.length === 2) { return signature2(arg0, arg1); // signature: number, Array } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: Matrix if (arguments.length === 2) { return signature3(arg0, arg1); // signature: number, Matrix } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test4(arg1)) { // type: Fraction (convert to BigNumber) if (arguments.length === 2) { return signature1(convert0(arg0), convert1(arg1)); // signature: number, Fraction } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test5(arg1)) { // type: string (convert to number) if (arguments.length === 2) { return signature0(arg0, convert2(arg1)); // signature: number, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test6(arg1)) { // type: boolean (convert to number) if (arguments.length === 2) { return signature0(arg0, convert3(arg1)); // signature: number, boolean } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test7(arg1)) { // type: null (convert to number) if (arguments.length === 2) { return signature0(arg0, convert4(arg1)); // signature: number, null } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'number,BigNumber,Array,Matrix'); } if (test1(arg0)) { // type: BigNumber if (test1(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature1(arg0, arg1); // signature: BigNumber, BigNumber } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: Array if (arguments.length === 2) { return signature2(arg0, arg1); // signature: BigNumber, Array } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: Matrix if (arguments.length === 2) { return signature3(arg0, arg1); // signature: BigNumber, Matrix } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test0(arg1)) { // type: number (convert to BigNumber) if (arguments.length === 2) { return signature1(arg0, convert0(arg1)); // signature: BigNumber, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test4(arg1)) { // type: Fraction (convert to BigNumber) if (arguments.length === 2) { return signature1(arg0, convert1(arg1)); // signature: BigNumber, Fraction } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test5(arg1)) { // type: string (convert to BigNumber) if (arguments.length === 2) { return signature ...
...
/**
* Bitwise right arithmetic shift of a value x by y number of bits, `x >> y`.
* For matrices, the function is evaluated element wise.
* For units, the function is evaluated on the best prefix base.
*
* Syntax:
*
* math.rightArithShift(x, y)
*
* Examples:
*
* math.rightArithShift(4, 2); // returns number 1
*
* math.rightArithShift([16, -32, 64], 4); // returns Array [1, -2, 3]
*
...
function rightLogShift(arg0, arg1) { "use strict"; var name = 'rightLogShift'; if (test0(arg0)) { // type: number if (test0(arg1)) { // type: number if (arguments.length === 2) { return signature0(arg0, arg1); // signature: number, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test1(arg1)) { // type: Array if (arguments.length === 2) { return signature1(arg0, arg1); // signature: number, Array } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: Matrix if (arguments.length === 2) { return signature2(arg0, arg1); // signature: number, Matrix } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: string (convert to number) if (arguments.length === 2) { return signature0(arg0, convert0(arg1)); // signature: number, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test4(arg1)) { // type: boolean (convert to number) if (arguments.length === 2) { return signature0(arg0, convert1(arg1)); // signature: number, boolean } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test5(arg1)) { // type: null (convert to number) if (arguments.length === 2) { return signature0(arg0, convert2(arg1)); // signature: number, null } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'number,Array,Matrix'); } if (test6(arg0)) { // type: BigNumber if (test1(arg1)) { // type: Array if (arguments.length === 2) { return signature1(arg0, arg1); // signature: BigNumber, Array } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: Matrix if (arguments.length === 2) { return signature2(arg0, arg1); // signature: BigNumber, Matrix } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'Array,Matrix'); } if (test1(arg0)) { // type: Array if (test0(arg1)) { // type: number if (arguments.length === 2) { return signature3(arg0, arg1); // signature: Array, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test6(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature3(arg0, arg1); // signature: Array, BigNumber } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test1(arg1)) { // type: Array if (arguments.length === 2) { return signature4(arg0, arg1); // signature: Array, Array } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: Matrix if (arguments.length === 2) { return signature5(arg0, arg1); // signature: Array, Matrix } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test7(arg1)) { // type: Fraction (convert to BigNumber) if (arguments.length === 2) { return signature3(arg0, convert3(arg1)); // signature: Array, Fraction } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: string (convert to number) if (arguments.length === 2) { return signature3(arg0, c ...
...
/**
* Bitwise right logical shift of value x by y number of bits, `x >>> y`.
* For matrices, the function is evaluated element wise.
* For units, the function is evaluated on the best prefix base.
*
* Syntax:
*
* math.rightLogShift(x, y)
*
* Examples:
*
* math.rightLogShift(4, 2); // returns number 1
*
* math.rightLogShift([16, -32, 64], 4); // returns Array [1, 2, 3]
*
...
function round(arg0, arg1) { "use strict"; var name = 'round'; if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature0(arg0); // signature: number } if (test0(arg1)) { // type: number if (arguments.length === 2) { return signature1(arg0, arg1); // signature: number, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test1(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature2(arg0, arg1); // signature: number, BigNumber } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: Array if (arguments.length === 2) { return signature3(arg0, arg1); // signature: number, Array } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: Matrix if (arguments.length === 2) { return signature4(arg0, arg1); // signature: number, Matrix } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test4(arg1)) { // type: Fraction (convert to BigNumber) if (arguments.length === 2) { return signature2(arg0, convert0(arg1)); // signature: number, Fraction } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test5(arg1)) { // type: string (convert to number) if (arguments.length === 2) { return signature1(arg0, convert1(arg1)); // signature: number, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test6(arg1)) { // type: boolean (convert to number) if (arguments.length === 2) { return signature1(arg0, convert2(arg1)); // signature: number, boolean } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test7(arg1)) { // type: null (convert to number) if (arguments.length === 2) { return signature1(arg0, convert3(arg1)); // signature: number, null } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'number,BigNumber,Array,Matrix'); } if (test8(arg0)) { // type: Complex if (arguments.length === 1) { return signature5(arg0); // signature: Complex } if (test0(arg1)) { // type: number if (arguments.length === 2) { return signature6(arg0, arg1); // signature: Complex, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test1(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature7(arg0, arg1); // signature: Complex, BigNumber } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: Array if (arguments.length === 2) { return signature3(arg0, arg1); // signature: Complex, Array } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: Matrix if (arguments.length === 2) { return signature4(arg0, arg1); // signature: Complex, Matrix } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test4(arg1)) { // type: Fraction (convert to BigNumber) if (arguments.length === 2) { return signature7(arg0, convert0(arg1)); // signature: Complex, Fraction } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test5(arg1)) { ...
...
[chained operations](http://mathjs.org/docs/chained_operations.html).
```js
// load math.js
var math = require('mathjs');
// functions and constants
math.round(math.e, 3); // 2.718
math.atan2(3, -3) / math.pi; // 0.75
math.log(1000, 10); // 3
math.sqrt(-4); // 2i
math.pow([[-1, 2], [3, 1]], 2); // [[7, 0], [0, 7]]
math.derivative('x^2 + x', 'x'); // 2 * x + 1
// expressions
...
function sec(arg0) { "use strict"; var name = 'sec'; if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature0(arg0); // signature: number } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: Complex if (arguments.length === 1) { return signature1(arg0); // signature: Complex } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test2(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature2(arg0); // signature: BigNumber } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test3(arg0)) { // type: Unit if (arguments.length === 1) { return signature3(arg0); // signature: Unit } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test4(arg0)) { // type: Array if (arguments.length === 1) { return signature4(arg0); // signature: Array } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test5(arg0)) { // type: Matrix if (arguments.length === 1) { return signature4(arg0); // signature: Matrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test6(arg0)) { // type: Fraction (convert to BigNumber) if (arguments.length === 1) { return signature2(convert0(arg0)); // signature: Fraction } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test7(arg0)) { // type: string (convert to number) if (arguments.length === 1) { return signature0(convert1(arg0)); // signature: string } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test8(arg0)) { // type: boolean (convert to number) if (arguments.length === 1) { return signature0(convert2(arg0)); // signature: boolean } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test9(arg0)) { // type: null (convert to number) if (arguments.length === 1) { return signature0(convert3(arg0)); // signature: null } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'number,Complex,BigNumber,Unit,Array,Matrix'); }
...
* Syntax:
*
* math.asec(x)
*
* Examples:
*
* math.asec(0.5); // returns 1.0471975511965979
* math.asec(math.sec(1.5)); // returns 1.5
*
* math.asec(2); // returns 0 + 1.3169578969248166 i
*
* See also:
*
* acos, acot, acsc
*
...
function sech(arg0) { "use strict"; var name = 'sech'; if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature0(arg0); // signature: number } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: Complex if (arguments.length === 1) { return signature1(arg0); // signature: Complex } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test2(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature2(arg0); // signature: BigNumber } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test3(arg0)) { // type: Unit if (arguments.length === 1) { return signature3(arg0); // signature: Unit } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test4(arg0)) { // type: Array if (arguments.length === 1) { return signature4(arg0); // signature: Array } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test5(arg0)) { // type: Matrix if (arguments.length === 1) { return signature4(arg0); // signature: Matrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test6(arg0)) { // type: Fraction (convert to BigNumber) if (arguments.length === 1) { return signature2(convert0(arg0)); // signature: Fraction } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test7(arg0)) { // type: string (convert to number) if (arguments.length === 1) { return signature0(convert1(arg0)); // signature: string } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test8(arg0)) { // type: boolean (convert to number) if (arguments.length === 1) { return signature0(convert2(arg0)); // signature: boolean } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test9(arg0)) { // type: null (convert to number) if (arguments.length === 1) { return signature0(convert3(arg0)); // signature: null } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'number,Complex,BigNumber,Unit,Array,Matrix'); }
...
* Calculate the hyperbolic secant of a value,
* defined as `sech(x) = 1 / cosh(x)`.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.sech(x)
*
* Examples:
*
* // sech(x) = 1/ cosh(x)
* math.sech(0.5); // returns 0.886818883970074
* 1 / math.cosh(0.5); // returns 0.886818883970074
*
...
function sign(arg0) { "use strict"; var name = 'sign'; if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature0(arg0); // signature: number } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: Complex if (arguments.length === 1) { return signature1(arg0); // signature: Complex } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test2(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature2(arg0); // signature: BigNumber } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test3(arg0)) { // type: Fraction if (arguments.length === 1) { return signature3(arg0); // signature: Fraction } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test4(arg0)) { // type: Unit if (arguments.length === 1) { return signature4(arg0); // signature: Unit } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test5(arg0)) { // type: Array if (arguments.length === 1) { return signature5(arg0); // signature: Array } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test6(arg0)) { // type: Matrix if (arguments.length === 1) { return signature5(arg0); // signature: Matrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test7(arg0)) { // type: string (convert to number) if (arguments.length === 1) { return signature0(convert0(arg0)); // signature: string } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test8(arg0)) { // type: boolean (convert to number) if (arguments.length === 1) { return signature0(convert1(arg0)); // signature: boolean } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test9(arg0)) { // type: null (convert to number) if (arguments.length === 1) { return signature0(convert2(arg0)); // signature: null } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'number,Complex,BigNumber,Fraction,Unit,Array,Matrix'); }
...
* - -1 when x < 0
* - 0 when x == 0
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.sign(x)
*
* Examples:
*
* math.sign(3.5); // returns 1
* math.sign(-4.2); // returns -1
* math.sign(0); // returns 0
*
...
function simplify(arg0, arg1) { "use strict"; var name = 'simplify'; if (test0(arg0)) { // type: string if (arguments.length === 1) { return signature0(arg0); // signature: string } if (test1(arg1)) { // type: Array if (arguments.length === 2) { return signature1(arg0, arg1); // signature: string, Array } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: Matrix (convert to Array) if (arguments.length === 2) { return signature1(arg0, convert0(arg1)); // signature: string, Matrix } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'Array'); } if (test3(arg0)) { // type: Node if (arguments.length === 1) { return signature2(arg0); // signature: Node } if (test1(arg1)) { // type: Array if (arguments.length === 2) { return signature3(arg0, arg1); // signature: Node, Array } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: Matrix (convert to Array) if (arguments.length === 2) { return signature3(arg0, convert0(arg1)); // signature: Node, Matrix } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'Array'); } if (test4(arg0)) { // type: number (convert to string) if (arguments.length === 1) { return signature0(convert1(arg0)); // signature: number } if (test1(arg1)) { // type: Array if (arguments.length === 2) { return signature1(convert1(arg0), arg1); // signature: number, Array } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: Matrix (convert to Array) if (arguments.length === 2) { return signature1(convert1(arg0), convert0(arg1)); // signature: number, Matrix } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'Array'); } if (test5(arg0)) { // type: boolean (convert to string) if (arguments.length === 1) { return signature0(convert2(arg0)); // signature: boolean } if (test1(arg1)) { // type: Array if (arguments.length === 2) { return signature1(convert2(arg0), arg1); // signature: boolean, Array } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: Matrix (convert to Array) if (arguments.length === 2) { return signature1(convert2(arg0), convert0(arg1)); // signature: boolean, Matrix } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'Array'); } if (test6(arg0)) { // type: null (convert to string) if (arguments.length === 1) { return signature0(convert3(arg0)); // signature: null } if (test1(arg1)) { // type: Array if (arguments.length === 2) { return signature1(convert3(arg0), arg1); // signature: null, Array } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: Matrix (convert to Array) if (arguments.length === 2) { return signature1(convert3(arg0), convert0(arg1)); // signature: null, Matrix } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'Array'); } throw createError(name, arguments.length, 0, arg ...
...
* Syntax:
*
* simplify(expr)
* simplify(expr, rules)
*
* Examples:
*
* math.simplify('2 * 1 * x ^ (2 - 1)'); // Node {2 * x}
* var f = math.parse('2 * 1 * x ^ (2 - 1)');
* math.simplify(f); // Node {2 * x}
*
* See also:
*
* derivative, parse, eval
*
...
function sin(arg0) { "use strict"; var name = 'sin'; if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature0(arg0); // signature: number } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: Complex if (arguments.length === 1) { return signature1(arg0); // signature: Complex } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test2(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature2(arg0); // signature: BigNumber } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test3(arg0)) { // type: Unit if (arguments.length === 1) { return signature3(arg0); // signature: Unit } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test4(arg0)) { // type: Array if (arguments.length === 1) { return signature4(arg0); // signature: Array } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test5(arg0)) { // type: Matrix if (arguments.length === 1) { return signature4(arg0); // signature: Matrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test6(arg0)) { // type: Fraction (convert to BigNumber) if (arguments.length === 1) { return signature2(convert0(arg0)); // signature: Fraction } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test7(arg0)) { // type: string (convert to number) if (arguments.length === 1) { return signature0(convert1(arg0)); // signature: string } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test8(arg0)) { // type: boolean (convert to number) if (arguments.length === 1) { return signature0(convert2(arg0)); // signature: boolean } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test9(arg0)) { // type: null (convert to number) if (arguments.length === 1) { return signature0(convert3(arg0)); // signature: null } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'number,Complex,BigNumber,Unit,Array,Matrix'); }
...
res = 1; // 0! is per definition 1
}
return res;
}
if (n < 0.5) {
return Math.PI / (Math.sin(Math.PI * n) * gamma(1-n));
}
if (n >= 171.35) {
return Infinity; // will overflow
}
if (n > 85.0) { // Extended Stirling Approx
...
function sinh(arg0) { "use strict"; var name = 'sinh'; if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature0(arg0); // signature: number } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: Complex if (arguments.length === 1) { return signature1(arg0); // signature: Complex } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test2(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature2(arg0); // signature: BigNumber } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test3(arg0)) { // type: Unit if (arguments.length === 1) { return signature3(arg0); // signature: Unit } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test4(arg0)) { // type: Array if (arguments.length === 1) { return signature4(arg0); // signature: Array } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test5(arg0)) { // type: Matrix if (arguments.length === 1) { return signature4(arg0); // signature: Matrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test6(arg0)) { // type: Fraction (convert to BigNumber) if (arguments.length === 1) { return signature2(convert0(arg0)); // signature: Fraction } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test7(arg0)) { // type: string (convert to number) if (arguments.length === 1) { return signature0(convert1(arg0)); // signature: string } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test8(arg0)) { // type: boolean (convert to number) if (arguments.length === 1) { return signature0(convert2(arg0)); // signature: boolean } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test9(arg0)) { // type: null (convert to number) if (arguments.length === 1) { return signature0(convert3(arg0)); // signature: null } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'number,Complex,BigNumber,Unit,Array,Matrix'); }
...
*
* math.csch(x)
*
* Examples:
*
* // csch(x) = 1/ sinh(x)
* math.csch(0.5); // returns 1.9190347513349437
* 1 / math.sinh(0.5); // returns 1.9190347513349437
*
* See also:
*
* sinh, sech, coth
*
* @param {number | Complex | Unit | Array | Matrix} x Function input
* @return {number | Complex | Array | Matrix} Hyperbolic cosecant of x
...
function size(arg0) { "use strict"; var name = 'size'; if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature0(arg0); // signature: number } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: Complex if (arguments.length === 1) { return signature0(arg0); // signature: Complex } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test2(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature0(arg0); // signature: BigNumber } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test3(arg0)) { // type: Unit if (arguments.length === 1) { return signature0(arg0); // signature: Unit } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test4(arg0)) { // type: string if (arguments.length === 1) { return signature1(arg0); // signature: string } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test5(arg0)) { // type: Array if (arguments.length === 1) { return signature2(arg0); // signature: Array } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test6(arg0)) { // type: Matrix if (arguments.length === 1) { return signature3(arg0); // signature: Matrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test7(arg0)) { // type: boolean if (arguments.length === 1) { return signature0(arg0); // signature: boolean } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test8(arg0)) { // type: null if (arguments.length === 1) { return signature0(arg0); // signature: null } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test9(arg0)) { // type: Fraction (convert to BigNumber) if (arguments.length === 1) { return signature0(convert0(arg0)); // signature: Fraction } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'number,Complex,BigNumber,Unit,string,Array,Matrix,boolean,null'); }
...
};
if (!Array.isArray(array) || !Array.isArray(sizes)) {
throw new TypeError('Array expected');
}
if (sizes.length === 0) {
throw new DimensionError(0, product(exports.size(array)), '!=');
}
try {
newArray = _reshape(flatArray, sizes);
} catch (e) {
if (e instanceof DimensionError) {
throw new DimensionError(
...
function slu(arg0, arg1, arg2) { "use strict"; var name = 'slu'; if (test0(arg0)) { // type: SparseMatrix if (test1(arg1)) { // type: number if (test1(arg2)) { // type: number if (arguments.length === 3) { return signature0(arg0, arg1, arg2); // signature: SparseMatrix, number, number } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } if (test2(arg2)) { // type: string (convert to number) if (arguments.length === 3) { return signature0(arg0, arg1, convert0(arg2)); // signature: SparseMatrix, number, string } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } if (test3(arg2)) { // type: boolean (convert to number) if (arguments.length === 3) { return signature0(arg0, arg1, convert1(arg2)); // signature: SparseMatrix, number, boolean } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } if (test4(arg2)) { // type: null (convert to number) if (arguments.length === 3) { return signature0(arg0, arg1, convert2(arg2)); // signature: SparseMatrix, number, null } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } throw createError(name, arguments.length, 2, arguments[2], 'number'); } if (test2(arg1)) { // type: string (convert to number) if (test1(arg2)) { // type: number if (arguments.length === 3) { return signature0(arg0, convert0(arg1), arg2); // signature: SparseMatrix, string, number } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } if (test2(arg2)) { // type: string (convert to number) if (arguments.length === 3) { return signature0(arg0, convert0(arg1), convert0(arg2)); // signature: SparseMatrix, string, string } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } if (test3(arg2)) { // type: boolean (convert to number) if (arguments.length === 3) { return signature0(arg0, convert0(arg1), convert1(arg2)); // signature: SparseMatrix, string, boolean } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } if (test4(arg2)) { // type: null (convert to number) if (arguments.length === 3) { return signature0(arg0, convert0(arg1), convert2(arg2)); // signature: SparseMatrix, string, null } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } throw createError(name, arguments.length, 2, arguments[2], 'number'); } if (test3(arg1)) { // type: boolean (convert to number) if (test1(arg2)) { // type: number if (arguments.length === 3) { return signature0(arg0, convert1(arg1), arg2); // signature: SparseMatrix, boolean, number } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } if (test2(arg2)) { // type: string (convert to number) if (arguments.length === 3) { return signature0(arg0, convert1(arg1), convert0(arg2)); // signature: SparseMatrix, boolean, string } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } if (test3(arg2)) { // type: boolean (convert to number) if (arguments.length === 3) { return signature0(arg0, convert1(arg1), convert1(arg2)); // signature: SparseMatrix, boolean, boolean } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } if (test4(ar ...
n/a
function smaller(arg0, arg1) { "use strict"; var name = 'smaller'; if (test0(arg0)) { // type: number if (test0(arg1)) { // type: number if (arguments.length === 2) { return signature0(arg0, arg1); // signature: number, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test1(arg1)) { // type: Complex if (arguments.length === 2) { return signature1(convert0(arg0), arg1); // signature: number, Complex } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature2(convert1(arg0), arg1); // signature: number, BigNumber } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: Fraction if (arguments.length === 2) { return signature3(convert2(arg0), arg1); // signature: number, Fraction } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test4(arg1)) { // type: string (convert to number) if (arguments.length === 2) { return signature0(arg0, convert3(arg1)); // signature: number, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test5(arg1)) { // type: boolean (convert to number) if (arguments.length === 2) { return signature0(arg0, convert4(arg1)); // signature: number, boolean } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test6(arg1)) { // type: null (convert to number) if (arguments.length === 2) { return signature0(arg0, convert5(arg1)); // signature: number, null } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } } if (test1(arg0)) { // type: Complex if (test1(arg1)) { // type: Complex if (arguments.length === 2) { return signature1(arg0, arg1); // signature: Complex, Complex } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test0(arg1)) { // type: number (convert to Complex) if (arguments.length === 2) { return signature1(arg0, convert0(arg1)); // signature: Complex, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: BigNumber (convert to Complex) if (arguments.length === 2) { return signature1(arg0, convert6(arg1)); // signature: Complex, BigNumber } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: Fraction (convert to Complex) if (arguments.length === 2) { return signature1(arg0, convert7(arg1)); // signature: Complex, Fraction } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test4(arg1)) { // type: string (convert to Complex) if (arguments.length === 2) { return signature1(arg0, convert8(arg1)); // signature: Complex, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } } if (test2(arg0)) { // type: BigNumber if (test1(arg1)) { // type: Complex if (arguments.length === 2) { return signature1(convert6(arg0), arg1); // signature: BigNumber, Complex } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature2(arg0, arg1); // signature: BigNumber, Big ...
...
*
* Syntax:
*
* math.smallerEq(x, y)
*
* Examples:
*
* math.smaller(1 + 2, 3); // returns false
* math.smallerEq(1 + 2, 3); // returns true
*
* See also:
*
* equal, unequal, smaller, larger, largerEq, compare
*
* @param {number | BigNumber | Fraction | boolean | Unit | string | Array | Matrix} x First value to compare
...
function smallerEq(arg0, arg1) { "use strict"; var name = 'smallerEq'; if (test0(arg0)) { // type: number if (test0(arg1)) { // type: number if (arguments.length === 2) { return signature0(arg0, arg1); // signature: number, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test1(arg1)) { // type: Complex if (arguments.length === 2) { return signature1(convert0(arg0), arg1); // signature: number, Complex } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature2(convert1(arg0), arg1); // signature: number, BigNumber } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: Fraction if (arguments.length === 2) { return signature3(convert2(arg0), arg1); // signature: number, Fraction } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test4(arg1)) { // type: string (convert to number) if (arguments.length === 2) { return signature0(arg0, convert3(arg1)); // signature: number, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test5(arg1)) { // type: boolean (convert to number) if (arguments.length === 2) { return signature0(arg0, convert4(arg1)); // signature: number, boolean } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test6(arg1)) { // type: null (convert to number) if (arguments.length === 2) { return signature0(arg0, convert5(arg1)); // signature: number, null } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } } if (test1(arg0)) { // type: Complex if (test1(arg1)) { // type: Complex if (arguments.length === 2) { return signature1(arg0, arg1); // signature: Complex, Complex } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test0(arg1)) { // type: number (convert to Complex) if (arguments.length === 2) { return signature1(arg0, convert0(arg1)); // signature: Complex, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: BigNumber (convert to Complex) if (arguments.length === 2) { return signature1(arg0, convert6(arg1)); // signature: Complex, BigNumber } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: Fraction (convert to Complex) if (arguments.length === 2) { return signature1(arg0, convert7(arg1)); // signature: Complex, Fraction } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test4(arg1)) { // type: string (convert to Complex) if (arguments.length === 2) { return signature1(arg0, convert8(arg1)); // signature: Complex, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } } if (test2(arg0)) { // type: BigNumber if (test1(arg1)) { // type: Complex if (arguments.length === 2) { return signature1(convert6(arg0), arg1); // signature: BigNumber, Complex } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature2(arg0, arg1); // signature: BigNumber, ...
...
* The function returns true when x is smaller than y or the relative
* difference between x and y is smaller than the configured epsilon. The
* function cannot be used to compare values smaller than approximately 2.22e-16.
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.smallerEq(x, y)
*
* Examples:
*
* math.smaller(1 + 2, 3); // returns false
* math.smallerEq(1 + 2, 3); // returns true
*
* See also:
...
function sort(arg0, arg1) { "use strict"; var name = 'sort'; if (test0(arg0)) { // type: Array if (arguments.length === 1) { return signature0(arg0); // signature: Array } if (test1(arg1)) { // type: string if (arguments.length === 2) { return signature1(arg0, arg1); // signature: Array, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: function if (arguments.length === 2) { return signature2(arg0, arg1); // signature: Array, function } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: number (convert to string) if (arguments.length === 2) { return signature1(arg0, convert0(arg1)); // signature: Array, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test4(arg1)) { // type: boolean (convert to string) if (arguments.length === 2) { return signature1(arg0, convert1(arg1)); // signature: Array, boolean } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test5(arg1)) { // type: null (convert to string) if (arguments.length === 2) { return signature1(arg0, convert2(arg1)); // signature: Array, null } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'string,function'); } if (test6(arg0)) { // type: Matrix if (arguments.length === 1) { return signature3(arg0); // signature: Matrix } if (test1(arg1)) { // type: string if (arguments.length === 2) { return signature4(arg0, arg1); // signature: Matrix, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: function if (arguments.length === 2) { return signature5(arg0, arg1); // signature: Matrix, function } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: number (convert to string) if (arguments.length === 2) { return signature4(arg0, convert0(arg1)); // signature: Matrix, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test4(arg1)) { // type: boolean (convert to string) if (arguments.length === 2) { return signature4(arg0, convert1(arg1)); // signature: Matrix, boolean } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test5(arg1)) { // type: null (convert to string) if (arguments.length === 2) { return signature4(arg0, convert2(arg1)); // signature: Matrix, null } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'string,function'); } throw createError(name, arguments.length, 0, arguments[0], 'Array,Matrix'); }
...
};
/**
* Sort the items in a matrix.
*
* Syntax:
*
* math.sort(x)
* math.sort(x, compare)
*
* Examples:
*
* math.sort([5, 10, 1]); // returns [1, 5, 10]
* math.sort(['C', 'B', 'A', 'D']); // returns ['A', 'B', 'C
', 'D']
*
...
function sparse(arg0, arg1) { "use strict"; var name = 'sparse'; if (arguments.length === 0) { return signature0(); // signature: } if (test0(arg0)) { // type: string if (arguments.length === 1) { return signature1(arg0); // signature: string } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: Array if (arguments.length === 1) { return signature2(arg0); // signature: Array } if (test0(arg1)) { // type: string if (arguments.length === 2) { return signature3(arg0, arg1); // signature: Array, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: number (convert to string) if (arguments.length === 2) { return signature3(arg0, convert0(arg1)); // signature: Array, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: boolean (convert to string) if (arguments.length === 2) { return signature3(arg0, convert1(arg1)); // signature: Array, boolean } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test4(arg1)) { // type: null (convert to string) if (arguments.length === 2) { return signature3(arg0, convert2(arg1)); // signature: Array, null } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'string'); } if (test5(arg0)) { // type: Matrix if (arguments.length === 1) { return signature2(arg0); // signature: Matrix } if (test0(arg1)) { // type: string if (arguments.length === 2) { return signature3(arg0, arg1); // signature: Matrix, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: number (convert to string) if (arguments.length === 2) { return signature3(arg0, convert0(arg1)); // signature: Matrix, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: boolean (convert to string) if (arguments.length === 2) { return signature3(arg0, convert1(arg1)); // signature: Matrix, boolean } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test4(arg1)) { // type: null (convert to string) if (arguments.length === 2) { return signature3(arg0, convert2(arg1)); // signature: Matrix, null } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'string'); } if (test2(arg0)) { // type: number (convert to string) if (arguments.length === 1) { return signature1(convert0(arg0)); // signature: number } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test3(arg0)) { // type: boolean (convert to string) if (arguments.length === 1) { return signature1(convert1(arg0)); // signature: boolean } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test4(arg0)) { // type: null (convert to string) if (arguments.length === 1) { return signature1(convert2(arg0)); // signature: null } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'string,Array,Matrix'); }
n/a
function splitUnit(arg0, arg1) { "use strict"; var name = 'splitUnit'; if (test0(arg0)) { // type: Unit if (test1(arg1)) { // type: Array if (arguments.length === 2) { return signature0(arg0, arg1); // signature: Unit, Array } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: Matrix (convert to Array) if (arguments.length === 2) { return signature0(arg0, convert0(arg1)); // signature: Unit, Matrix } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'Array'); } throw createError(name, arguments.length, 0, arguments[0], 'Unit'); }
...
* Returns an array of units whose sum is equal to this unit
* @memberof Unit
* @param {Array} [parts] An array of strings or valueless units.
*
* Example:
*
* var u = new Unit(1, 'm');
* u.splitUnit(['feet', 'inch']);
* [ 3 feet, 3.3700787401575 inch ]
*
* @return {Array} An array of units.
*/
Unit.prototype.splitUnit = function(parts) {
var x = this.clone();
...
function sqrt(arg0) { "use strict"; var name = 'sqrt'; if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature0(arg0); // signature: number } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: Complex if (arguments.length === 1) { return signature1(arg0); // signature: Complex } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test2(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature2(arg0); // signature: BigNumber } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test3(arg0)) { // type: Unit if (arguments.length === 1) { return signature3(arg0); // signature: Unit } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test4(arg0)) { // type: Array if (arguments.length === 1) { return signature4(arg0); // signature: Array } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test5(arg0)) { // type: Matrix if (arguments.length === 1) { return signature4(arg0); // signature: Matrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test6(arg0)) { // type: Fraction (convert to BigNumber) if (arguments.length === 1) { return signature2(convert0(arg0)); // signature: Fraction } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test7(arg0)) { // type: string (convert to number) if (arguments.length === 1) { return signature0(convert1(arg0)); // signature: string } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test8(arg0)) { // type: boolean (convert to number) if (arguments.length === 1) { return signature0(convert2(arg0)); // signature: boolean } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test9(arg0)) { // type: null (convert to number) if (arguments.length === 1) { return signature0(convert3(arg0)); // signature: null } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'number,Complex,BigNumber,Unit,Array,Matrix'); }
...
// load math.js
var math = require('mathjs');
// functions and constants
math.round(math.e, 3); // 2.718
math.atan2(3, -3) / math.pi; // 0.75
math.log(1000, 10); // 3
math.sqrt(-4); // 2i
math.pow([[-1, 2], [3, 1]], 2); // [[7, 0], [0, 7]]
math.derivative('x^2 + x', 'x'); // 2 * x + 1
// expressions
math.eval('12 / (2.3 + 0.7)'); // 4
math.eval('5.08 cm to inch'); // 2 inch
math.eval('sin(45 deg) ^ 2'); // 0.5
...
function square(arg0) { "use strict"; var name = 'square'; if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature0(arg0); // signature: number } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: Complex if (arguments.length === 1) { return signature1(arg0); // signature: Complex } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test2(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature2(arg0); // signature: BigNumber } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test3(arg0)) { // type: Fraction if (arguments.length === 1) { return signature3(arg0); // signature: Fraction } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test4(arg0)) { // type: Unit if (arguments.length === 1) { return signature4(arg0); // signature: Unit } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test5(arg0)) { // type: Array if (arguments.length === 1) { return signature5(arg0); // signature: Array } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test6(arg0)) { // type: Matrix if (arguments.length === 1) { return signature5(arg0); // signature: Matrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test7(arg0)) { // type: string (convert to number) if (arguments.length === 1) { return signature0(convert0(arg0)); // signature: string } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test8(arg0)) { // type: boolean (convert to number) if (arguments.length === 1) { return signature0(convert1(arg0)); // signature: boolean } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test9(arg0)) { // type: null (convert to number) if (arguments.length === 1) { return signature0(convert2(arg0)); // signature: null } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'number,Complex,BigNumber,Fraction,Unit,Array,Matrix'); }
...
* Syntax:
*
* math.sqrt(x)
*
* Examples:
*
* math.sqrt(25); // returns 5
* math.square(5); // returns 25
* math.sqrt(-4); // returns Complex 2i
*
* See also:
*
* square, multiply, cube, cbrt
*
* @param {number | BigNumber | Complex | Array | Matrix | Unit} x
...
function squeeze(arg0) { "use strict"; var name = 'squeeze'; if (test0(arg0)) { // type: Array if (arguments.length === 1) { return signature0(arg0); // signature: Array } } if (test1(arg0)) { // type: Matrix if (arguments.length === 1) { return signature1(arg0); // signature: Matrix } } // type: any if (arguments.length === 1) { return signature2(arg0); // signature: any } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } throw createError(name, arguments.length, 0, arguments[0], 'Array,Matrix,any'); }
...
* @param {Array} y Second vector
* @returns {Array} Returns the cross product of x and y
* @private
*/
function _cross(x, y) {
var highestDimension = Math.max(array.size(x).length, array.size(y).length);
x = array.squeeze(x);
y = array.squeeze(y);
var xSize = array.size(x);
var ySize = array.size(y);
if (xSize.length != 1 || ySize.length != 1 || xSize[0] != 3 || ySize[0] != 3) {
throw new RangeError('Vectors with length 3 expected ' +
...
function std(arg0, arg1) { "use strict"; var name = 'std'; if (test0(arg0)) { // type: Array if (arguments.length === 1) { return signature0(arg0); // signature: Array } if (test1(arg1)) { // type: string if (arguments.length === 2) { return signature0(arg0, arg1); // signature: Array, string } } if (test2(arg1)) { // type: number (convert to string) if (arguments.length === 2) { return signature0(arg0, convert0(arg1)); // signature: Array, number } } if (test3(arg1)) { // type: boolean (convert to string) if (arguments.length === 2) { return signature0(arg0, convert1(arg1)); // signature: Array, boolean } } if (test4(arg1)) { // type: null (convert to string) if (arguments.length === 2) { return signature0(arg0, convert2(arg1)); // signature: Array, null } } } if (test5(arg0)) { // type: Matrix if (arguments.length === 1) { return signature0(arg0); // signature: Matrix } if (test1(arg1)) { // type: string if (arguments.length === 2) { return signature0(arg0, arg1); // signature: Matrix, string } } if (test2(arg1)) { // type: number (convert to string) if (arguments.length === 2) { return signature0(arg0, convert0(arg1)); // signature: Matrix, number } } if (test3(arg1)) { // type: boolean (convert to string) if (arguments.length === 2) { return signature0(arg0, convert1(arg1)); // signature: Matrix, boolean } } if (test4(arg1)) { // type: null (convert to string) if (arguments.length === 2) { return signature0(arg0, convert2(arg1)); // signature: Matrix, null } } } if (arguments.length > 0) { var varArgs = []; for (var i = 0; i < arguments.length; i++) { varArgs.push(arguments[i]); } return signature1(varArgs); // signature: ...any } throw createError(name, arguments.length, 0, arguments[0], 'Array,Matrix,any'); }
...
*
* - 'unbiased' (default) The sum of squared errors is divided by (n - 1)
* - 'uncorrected' The sum of squared errors is divided by n
* - 'biased' The sum of squared errors is divided by (n + 1)
*
* Syntax:
*
* math.std(a, b, c, ...)
* math.std(A)
* math.std(A, normalization)
*
* Examples:
*
* math.std(2, 4, 6); // returns 2
* math.std([2, 4, 6, 8]); // returns 2.581988897471611
...
function stirlingS2(arg0, arg1) { "use strict"; var name = 'stirlingS2'; if (test0(arg0)) { // type: number if (test0(arg1)) { // type: number if (arguments.length === 2) { return signature0(arg0, arg1); // signature: number, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test1(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature0(arg0, arg1); // signature: number, BigNumber } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: Fraction (convert to BigNumber) if (arguments.length === 2) { return signature0(arg0, convert0(arg1)); // signature: number, Fraction } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: string (convert to number) if (arguments.length === 2) { return signature0(arg0, convert1(arg1)); // signature: number, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test4(arg1)) { // type: boolean (convert to number) if (arguments.length === 2) { return signature0(arg0, convert2(arg1)); // signature: number, boolean } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test5(arg1)) { // type: null (convert to number) if (arguments.length === 2) { return signature0(arg0, convert3(arg1)); // signature: number, null } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'number,BigNumber'); } if (test1(arg0)) { // type: BigNumber if (test0(arg1)) { // type: number if (arguments.length === 2) { return signature0(arg0, arg1); // signature: BigNumber, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test1(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature0(arg0, arg1); // signature: BigNumber, BigNumber } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: Fraction (convert to BigNumber) if (arguments.length === 2) { return signature0(arg0, convert0(arg1)); // signature: BigNumber, Fraction } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: string (convert to number) if (arguments.length === 2) { return signature0(arg0, convert1(arg1)); // signature: BigNumber, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test4(arg1)) { // type: boolean (convert to number) if (arguments.length === 2) { return signature0(arg0, convert2(arg1)); // signature: BigNumber, boolean } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test5(arg1)) { // type: null (convert to number) if (arguments.length === 2) { return signature0(arg0, convert3(arg1)); // signature: BigNumber, null } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'number,BigNumber'); } if (test2(arg0)) { // type: Fraction (convert to BigNumber) if (test0(arg1)) { // type: number if (arguments.length === 2) { return signature0(convert0(arg0), arg1); // signature: Fraction, number } if (arguments.length > 2) { throw createErr ...
...
* stirlingS2 only takes integer arguments.
* The following condition must be enforced: k <= n.
*
* If n = k or k = 1, then s(n,k) = 1
*
* Syntax:
*
* math.stirlingS2(n, k)
*
* Examples:
*
* math.stirlingS2(5, 3); //returns 25
*
* See also:
*
...
function string(arg0) { "use strict"; var name = 'string'; if (arguments.length === 0) { return signature0(); // signature: } if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature1(arg0); // signature: number } } if (test1(arg0)) { // type: string if (arguments.length === 1) { return signature2(arg0); // signature: string } } if (test2(arg0)) { // type: Array if (arguments.length === 1) { return signature3(arg0); // signature: Array } } if (test3(arg0)) { // type: Matrix if (arguments.length === 1) { return signature3(arg0); // signature: Matrix } } if (test4(arg0)) { // type: boolean if (arguments.length === 1) { return signature4(arg0); // signature: boolean } } if (test5(arg0)) { // type: null if (arguments.length === 1) { return signature5(arg0); // signature: null } } // type: any if (arguments.length === 1) { return signature6(arg0); // signature: any } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } throw createError(name, arguments.length, 0, arguments[0], 'number,string,Array,Matrix,boolean,null,any'); }
...
function factory (type, config, load, typed) {
/**
* Create a string or convert any object into a string.
* Elements of Arrays and Matrices are processed element wise.
*
* Syntax:
*
* math.string(value)
*
* Examples:
*
* math.string(4.2); // returns string '4.2'
* math.string(math.complex(3, 2); // returns string '3 + 2i'
*
* var u = math.unit(5, 'km');
...
function subset(arg0, arg1, arg2, arg3) { "use strict"; var name = 'subset'; if (test0(arg0)) { // type: string if (test1(arg1)) { // type: Index if (arguments.length === 2) { return signature0(arg0, arg1); // signature: string, Index } if (test0(arg2)) { // type: string if (arguments.length === 3) { return signature1(arg0, arg1, arg2); // signature: string, Index, string } if (test0(arg3)) { // type: string if (arguments.length === 4) { return signature1(arg0, arg1, arg2, arg3); // signature: string, Index, string, string } if (arguments.length > 4) { throw createError(name, arguments.length, 4, arguments[4]); } } if (test2(arg3)) { // type: number (convert to string) if (arguments.length === 4) { return signature1(arg0, arg1, arg2, convert0(arg3)); // signature: string, Index, string, number } if (arguments.length > 4) { throw createError(name, arguments.length, 4, arguments[4]); } } if (test3(arg3)) { // type: boolean (convert to string) if (arguments.length === 4) { return signature1(arg0, arg1, arg2, convert1(arg3)); // signature: string, Index, string, boolean } if (arguments.length > 4) { throw createError(name, arguments.length, 4, arguments[4]); } } if (test4(arg3)) { // type: null (convert to string) if (arguments.length === 4) { return signature1(arg0, arg1, arg2, convert2(arg3)); // signature: string, Index, string, null } if (arguments.length > 4) { throw createError(name, arguments.length, 4, arguments[4]); } } throw createError(name, arguments.length, 3, arguments[3], 'string'); } if (test2(arg2)) { // type: number (convert to string) if (arguments.length === 3) { return signature1(arg0, arg1, convert0(arg2)); // signature: string, Index, number } if (test0(arg3)) { // type: string if (arguments.length === 4) { return signature1(arg0, arg1, convert0(arg2), arg3); // signature: string, Index, number, string } if (arguments.length > 4) { throw createError(name, arguments.length, 4, arguments[4]); } } if (test2(arg3)) { // type: number (convert to string) if (arguments.length === 4) { return signature1(arg0, arg1, convert0(arg2), convert0(arg3)); // signature: string, Index, number, number } if (arguments.length > 4) { throw createError(name, arguments.length, 4, arguments[4]); } } if (test3(arg3)) { // type: boolean (convert to string) if (arguments.length === 4) { return signature1(arg0, arg1, convert0(arg2), convert1(arg3)); // signature: string, Index, number, boolean } if (arguments.length > 4) { throw createError(name, arguments.length, 4, arguments[4]); } } if (test4(arg3)) { // type: null (convert to string) if (arguments.length === 4) { return signature1(arg0, arg1, convert0(arg2), convert2(arg3)); // signature: string, Index, number, null } if (arguments.length > 4) { throw createError(name, arguments.length, 4, arguments[4]); } } throw createError(name, arguments.length, 3, arguments[3], 'string'); } if (test3(arg2)) { // type: boolean (convert to string) if (arguments.length === 3) { return signature1(arg0, arg1, convert1(arg2)); // signature: string, Index, boolean } if (test0(arg3)) { // type: string if (arguments.length === 4) { return signature1(arg0, arg1, convert1(arg2), arg3); // signature: string, Index, boolean, string } if (arguments.length > 4) { ...
...
function factory (type, config, load, typed) {
var matrix = load(require('../../type/matrix/function/matrix'));
/**
* Get or set a subset of a matrix or string.
*
* Syntax:
* math.subset(value, index) // retrieve a subset
* math.subset(value, index, replacement [, defaultValue]) // replace a subset
*
* Examples:
*
* // get a subset
* var d = [[1, 2], [3, 4]];
* math.subset(d, math.index(1, 0)); // returns 3
...
function subtract(arg0, arg1) { "use strict"; var name = 'subtract'; if (test0(arg0)) { // type: number if (test0(arg1)) { // type: number if (arguments.length === 2) { return signature0(arg0, arg1); // signature: number, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test1(arg1)) { // type: Complex if (arguments.length === 2) { return signature1(convert0(arg0), arg1); // signature: number, Complex } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature2(convert1(arg0), arg1); // signature: number, BigNumber } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: Fraction if (arguments.length === 2) { return signature3(convert2(arg0), arg1); // signature: number, Fraction } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test4(arg1)) { // type: string (convert to number) if (arguments.length === 2) { return signature0(arg0, convert3(arg1)); // signature: number, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test5(arg1)) { // type: boolean (convert to number) if (arguments.length === 2) { return signature0(arg0, convert4(arg1)); // signature: number, boolean } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test6(arg1)) { // type: null (convert to number) if (arguments.length === 2) { return signature0(arg0, convert5(arg1)); // signature: number, null } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } } if (test1(arg0)) { // type: Complex if (test1(arg1)) { // type: Complex if (arguments.length === 2) { return signature1(arg0, arg1); // signature: Complex, Complex } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test0(arg1)) { // type: number (convert to Complex) if (arguments.length === 2) { return signature1(arg0, convert0(arg1)); // signature: Complex, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: BigNumber (convert to Complex) if (arguments.length === 2) { return signature1(arg0, convert6(arg1)); // signature: Complex, BigNumber } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: Fraction (convert to Complex) if (arguments.length === 2) { return signature1(arg0, convert7(arg1)); // signature: Complex, Fraction } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test4(arg1)) { // type: string (convert to Complex) if (arguments.length === 2) { return signature1(arg0, convert8(arg1)); // signature: Complex, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } } if (test2(arg0)) { // type: BigNumber if (test1(arg1)) { // type: Complex if (arguments.length === 2) { return signature1(convert6(arg0), arg1); // signature: BigNumber, Complex } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature2(arg0, arg1); // signature: BigNumber, B ...
...
/**
* Subtract two values, `x - y`.
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.subtract(x, y)
*
* Examples:
*
* math.subtract(5.3, 2); // returns number 3.3
*
* var a = math.complex(2, 3);
* var b = math.complex(4, 1);
...
function sum(arg0, arg1) { "use strict"; var name = 'sum'; if (test0(arg0)) { // type: Array if (arguments.length === 1) { return signature0(arg0); // signature: Array } if (test1(arg1)) { // type: number if (arguments.length === 2) { return signature1(arg0, arg1); // signature: Array, number } } if (test2(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature1(arg0, arg1); // signature: Array, BigNumber } } if (test3(arg1)) { // type: Fraction (convert to BigNumber) if (arguments.length === 2) { return signature1(arg0, convert0(arg1)); // signature: Array, Fraction } } if (test4(arg1)) { // type: string (convert to number) if (arguments.length === 2) { return signature1(arg0, convert1(arg1)); // signature: Array, string } } if (test5(arg1)) { // type: boolean (convert to number) if (arguments.length === 2) { return signature1(arg0, convert2(arg1)); // signature: Array, boolean } } if (test6(arg1)) { // type: null (convert to number) if (arguments.length === 2) { return signature1(arg0, convert3(arg1)); // signature: Array, null } } } if (test7(arg0)) { // type: Matrix if (arguments.length === 1) { return signature0(arg0); // signature: Matrix } if (test1(arg1)) { // type: number if (arguments.length === 2) { return signature1(arg0, arg1); // signature: Matrix, number } } if (test2(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature1(arg0, arg1); // signature: Matrix, BigNumber } } if (test3(arg1)) { // type: Fraction (convert to BigNumber) if (arguments.length === 2) { return signature1(arg0, convert0(arg1)); // signature: Matrix, Fraction } } if (test4(arg1)) { // type: string (convert to number) if (arguments.length === 2) { return signature1(arg0, convert1(arg1)); // signature: Matrix, string } } if (test5(arg1)) { // type: boolean (convert to number) if (arguments.length === 2) { return signature1(arg0, convert2(arg1)); // signature: Matrix, boolean } } if (test6(arg1)) { // type: null (convert to number) if (arguments.length === 2) { return signature1(arg0, convert3(arg1)); // signature: Matrix, null } } } if (arguments.length > 0) { var varArgs = []; for (var i = 0; i < arguments.length; i++) { varArgs.push(arguments[i]); } return signature2(varArgs); // signature: ...any } throw createError(name, arguments.length, 0, arguments[0], 'Array,Matrix,any'); }
...
/**
* Compute the sum of a matrix or a list with values.
* In case of a (multi dimensional) array or matrix, the sum of all
* elements will be calculated.
*
* Syntax:
*
* math.sum(a, b, c, ...)
* math.sum(A)
*
* Examples:
*
* math.sum(2, 1, 4, 3); // returns 10
* math.sum([2, 1, 4, 3]); // returns 10
* math.sum([[2, 5], [4, 3], [1, 7]]); // returns 22
...
function tan(arg0) { "use strict"; var name = 'tan'; if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature0(arg0); // signature: number } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: Complex if (arguments.length === 1) { return signature1(arg0); // signature: Complex } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test2(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature2(arg0); // signature: BigNumber } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test3(arg0)) { // type: Unit if (arguments.length === 1) { return signature3(arg0); // signature: Unit } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test4(arg0)) { // type: Array if (arguments.length === 1) { return signature4(arg0); // signature: Array } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test5(arg0)) { // type: Matrix if (arguments.length === 1) { return signature4(arg0); // signature: Matrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test6(arg0)) { // type: Fraction (convert to BigNumber) if (arguments.length === 1) { return signature2(convert0(arg0)); // signature: Fraction } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test7(arg0)) { // type: string (convert to number) if (arguments.length === 1) { return signature0(convert1(arg0)); // signature: string } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test8(arg0)) { // type: boolean (convert to number) if (arguments.length === 1) { return signature0(convert2(arg0)); // signature: boolean } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test9(arg0)) { // type: null (convert to number) if (arguments.length === 1) { return signature0(convert3(arg0)); // signature: null } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'number,Complex,BigNumber,Unit,Array,Matrix'); }
...
* Syntax:
*
* math.atan(x)
*
* Examples:
*
* math.atan(0.5); // returns number 0.4636476090008061
* math.atan(math.tan(1.5)); // returns number 1.5
*
* math.atan(2); // returns Complex 1.5707963267948966 -1.3169578969248166 i
*
* See also:
*
* tan, asin, acos
*
...
function tanh(arg0) { "use strict"; var name = 'tanh'; if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature0(arg0); // signature: number } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: Complex if (arguments.length === 1) { return signature1(arg0); // signature: Complex } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test2(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature2(arg0); // signature: BigNumber } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test3(arg0)) { // type: Unit if (arguments.length === 1) { return signature3(arg0); // signature: Unit } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test4(arg0)) { // type: Array if (arguments.length === 1) { return signature4(arg0); // signature: Array } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test5(arg0)) { // type: Matrix if (arguments.length === 1) { return signature4(arg0); // signature: Matrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test6(arg0)) { // type: Fraction (convert to BigNumber) if (arguments.length === 1) { return signature2(convert0(arg0)); // signature: Fraction } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test7(arg0)) { // type: string (convert to number) if (arguments.length === 1) { return signature0(convert1(arg0)); // signature: string } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test8(arg0)) { // type: boolean (convert to number) if (arguments.length === 1) { return signature0(convert2(arg0)); // signature: boolean } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test9(arg0)) { // type: null (convert to number) if (arguments.length === 1) { return signature0(convert3(arg0)); // signature: null } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'number,Complex,BigNumber,Unit,Array,Matrix'); }
...
*
* math.coth(x)
*
* Examples:
*
* // coth(x) = 1 / tanh(x)
* math.coth(2); // returns 1.0373147207275482
* 1 / math.tanh(2); // returns 1.0373147207275482
*
* See also:
*
* sinh, tanh, cosh
*
* @param {number | Complex | Unit | Array | Matrix} x Function input
* @return {number | Complex | Array | Matrix} Hyperbolic cotangent of x
...
function to(arg0, arg1) { "use strict"; var name = 'to'; if (test0(arg0)) { // type: Unit if (test0(arg1)) { // type: Unit if (arguments.length === 2) { return signature0(arg0, arg1); // signature: Unit, Unit } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test1(arg1)) { // type: string if (arguments.length === 2) { return signature0(arg0, arg1); // signature: Unit, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: number (convert to string) if (arguments.length === 2) { return signature0(arg0, convert0(arg1)); // signature: Unit, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: boolean (convert to string) if (arguments.length === 2) { return signature0(arg0, convert1(arg1)); // signature: Unit, boolean } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test4(arg1)) { // type: null (convert to string) if (arguments.length === 2) { return signature0(arg0, convert2(arg1)); // signature: Unit, null } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } } if (test5(arg0)) { // type: Array if (test5(arg1)) { // type: Array if (arguments.length === 2) { return signature1(arg0, arg1); // signature: Array, Array } } if (test6(arg1)) { // type: Matrix if (arguments.length === 2) { return signature2(arg0, arg1); // signature: Array, Matrix } } // type: any if (arguments.length === 2) { return signature3(arg0, arg1); // signature: Array, any } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test6(arg0)) { // type: Matrix if (test5(arg1)) { // type: Array if (arguments.length === 2) { return signature4(arg0, arg1); // signature: Matrix, Array } } if (test6(arg1)) { // type: Matrix if (arguments.length === 2) { return signature5(arg0, arg1); // signature: Matrix, Matrix } } // type: any if (arguments.length === 2) { return signature6(arg0, arg1); // signature: Matrix, any } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } // type: any if (test5(arg1)) { // type: Array if (arguments.length === 2) { return signature7(arg0, arg1); // signature: any, Array } } if (test6(arg1)) { // type: Matrix if (arguments.length === 2) { return signature8(arg0, arg1); // signature: any, Matrix } } throw createError(name, arguments.length, 1, arguments[1], 'Array,Matrix'); throw createError(name, arguments.length, 0, arguments[0], 'Unit,Array,Matrix,any'); }
...
*
* Examples:
*
* math.string(4.2); // returns string '4.2'
* math.string(math.complex(3, 2); // returns string '3 + 2i'
*
* var u = math.unit(5, 'km');
* math.string(u.to('m')); // returns string '5000 m'
*
* math.string([true, false]); // returns ['true', 'false']
*
* See also:
*
* bignumber, boolean, complex, index, matrix, number, unit
*
...
function trace(arg0) { "use strict"; var name = 'trace'; if (test0(arg0)) { // type: Array if (arguments.length === 1) { return signature0(arg0); // signature: Array } } if (test1(arg0)) { // type: Matrix if (arguments.length === 1) { return signature1(arg0); // signature: Matrix } } // type: any if (arguments.length === 1) { return signature2(arg0); // signature: any } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } throw createError(name, arguments.length, 0, arguments[0], 'Array,Matrix,any'); }
...
/**
* Calculate the trace of a matrix: the sum of the elements on the main
* diagonal of a square matrix.
*
* Syntax:
*
* math.trace(x)
*
* Examples:
*
* math.trace([[1, 2], [3, 4]]); // returns 5
*
* var A = [
* [1, 2, 3],
...
function transpose(arg0) { "use strict"; var name = 'transpose'; if (test0(arg0)) { // type: Array if (arguments.length === 1) { return signature0(arg0); // signature: Array } } if (test1(arg0)) { // type: Matrix if (arguments.length === 1) { return signature1(arg0); // signature: Matrix } } // type: any if (arguments.length === 1) { return signature2(arg0); // signature: any } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } throw createError(name, arguments.length, 0, arguments[0], 'Array,Matrix,any'); }
...
* Transpose a matrix. All values of the matrix are reflected over its
* main diagonal. Only applicable to two dimensional matrices containing
* a vector (i.e. having size `[1,n]` or `[n,1]`). One dimensional
* vectors and scalars return the input unchanged.
*
* Syntax:
*
* math.transpose(x)
*
* Examples:
*
* var A = [[1, 2, 3], [4, 5, 6]];
* math.transpose(A); // returns [[1, 4], [2, 5], [3, 6]]
*
* See also:
...
function Decimal(v) { var e, i, t, x = this; // Decimal called without new. if (!(x instanceof Decimal)) return new Decimal(v); // Retain a reference to this Decimal constructor, and shadow Decimal.prototype.constructor // which points to Object. x.constructor = Decimal; // Duplicate. if (v instanceof Decimal) { x.s = v.s; x.e = v.e; x.d = (v = v.d) ? v.slice() : v; return; } t = typeof v; if (t === 'number') { if (v === 0) { x.s = 1 / v < 0 ? -1 : 1; x.e = 0; x.d = [0]; return; } if (v < 0) { v = -v; x.s = -1; } else { x.s = 1; } // Fast path for small integers. if (v === ~~v && v < 1e7) { for (e = 0, i = v; i >= 10; i /= 10) e++; x.e = e; x.d = [v]; return; // Infinity, NaN. } else if (v * 0 !== 0) { if (!v) x.s = NaN; x.e = NaN; x.d = null; return; } return parseDecimal(x, v.toString()); } else if (t !== 'string') { throw Error(invalidArgument + v); } // Minus sign? if (v.charCodeAt(0) === 45) { v = v.slice(1); x.s = -1; } else { x.s = 1; } return isDecimal.test(v) ? parseDecimal(x, v) : parseOther(x, v); }
n/a
function Chain(value) { if (!(this instanceof Chain)) { throw new SyntaxError('Constructor must be called with the new operator'); } if (value && value.isChain) { this.value = value.value; } else { this.value = value; } }
n/a
function Complex(a, b) { if (!(this instanceof Complex)) { return new Complex(a, b); } parse(a, b); // mutates P this["re"] = P["re"]; this["im"] = P["im"]; }
n/a
function DenseMatrix(data, datatype) { if (!(this instanceof DenseMatrix)) throw new SyntaxError('Constructor must be called with the new operator'); if (datatype && !isString(datatype)) throw new Error('Invalid datatype: ' + datatype); if (data && data.isMatrix === true) { // check data is a DenseMatrix if (data.type === 'DenseMatrix') { // clone data & size this._data = object.clone(data._data); this._size = object.clone(data._size); this._datatype = datatype || data._datatype; } else { // build data from existing matrix this._data = data.toArray(); this._size = data.size(); this._datatype = datatype || data._datatype; } } else if (data && isArray(data.data) && isArray(data.size)) { // initialize fields from JSON representation this._data = data.data; this._size = data.size; this._datatype = datatype || data.datatype; } else if (isArray(data)) { // replace nested Matrices with Arrays this._data = preprocess(data); // get the dimensions of the array this._size = array.size(this._data); // verify the dimensions of the array, TODO: compute size while processing array array.validate(this._data, this._size); // data type unknown this._datatype = datatype; } else if (data) { // unsupported type throw new TypeError('Unsupported type of data (' + util.types.type(data) + ')'); } else { // nothing provided this._data = []; this._size = [0]; this._datatype = datatype; } }
n/a
function FibonacciHeap() { if (!(this instanceof FibonacciHeap)) throw new SyntaxError('Constructor must be called with the new operator'); // initialize fields this._minimum = null; this._size = 0; }
n/a
function Fraction(a, b) { if (!(this instanceof Fraction)) { return new Fraction(a, b); } parse(a, b); if (Fraction['REDUCE']) { a = gcd(P["d"], P["n"]); // Abuse a } else { a = 1; } this["s"] = P["s"]; this["n"] = P["n"] / a; this["d"] = P["d"] / a; }
n/a
function Help(doc) { if (!(this instanceof Help)) { throw new SyntaxError('Constructor must be called with the new operator'); } if (!doc) throw new Error('Argument "doc" missing'); this.doc = doc; }
n/a
function ImmutableDenseMatrix(data, datatype) { if (!(this instanceof ImmutableDenseMatrix)) throw new SyntaxError('Constructor must be called with the new operator'); if (datatype && !isString(datatype)) throw new Error('Invalid datatype: ' + datatype); if ((data && data.isMatrix === true) || isArray(data)) { // use DenseMatrix implementation var matrix = new DenseMatrix(data, datatype); // internal structures this._data = matrix._data; this._size = matrix._size; this._datatype = matrix._datatype; this._min = null; this._max = null; } else if (data && isArray(data.data) && isArray(data.size)) { // initialize fields from JSON representation this._data = data.data; this._size = data.size; this._datatype = data.datatype; this._min = typeof data.min !== 'undefined' ? data.min : null; this._max = typeof data.max !== 'undefined' ? data.max : null; } else if (data) { // unsupported type throw new TypeError('Unsupported type of data (' + util.types.type(data) + ')'); } else { // nothing provided this._data = []; this._size = [0]; this._datatype = datatype; this._min = null; this._max = null; } }
n/a
function Index(ranges) { if (!(this instanceof Index)) { throw new SyntaxError('Constructor must be called with the new operator'); } this._dimensions = []; this._isScalar = true; for (var i = 0, ii = arguments.length; i < ii; i++) { var arg = arguments[i]; if (arg && (arg.isRange === true)) { this._dimensions.push(arg); this._isScalar = false; } else if (arg && (Array.isArray(arg) || arg.isMatrix === true)) { // create matrix var m = _createImmutableMatrix(arg.valueOf()); this._dimensions.push(m); // size var size = m.size(); // scalar if (size.length !== 1 || size[0] !== 1) { this._isScalar = false; } } else if (typeof arg === 'number') { this._dimensions.push(_createImmutableMatrix([arg])); } else if (typeof arg === 'string') { // object property (arguments.count should be 1) this._dimensions.push(arg); } // TODO: implement support for wildcard '*' else { throw new TypeError('Dimension must be an Array, Matrix, number, string, or Range'); } } }
n/a
function Matrix() { if (!(this instanceof Matrix)) { throw new SyntaxError('Constructor must be called with the new operator'); } }
n/a
function Range(start, end, step) { if (!(this instanceof Range)) { throw new SyntaxError('Constructor must be called with the new operator'); } if (start != null) { if (start.isBigNumber === true) start = start.toNumber(); else if (typeof start !== 'number') throw new TypeError('Parameter start must be a number'); } if (end != null) { if (end.isBigNumber === true) end = end.toNumber(); else if (typeof end !== 'number') throw new TypeError('Parameter end must be a number'); } if (step != null) { if (step.isBigNumber === true) step = step.toNumber(); else if (typeof step !== 'number') throw new TypeError('Parameter step must be a number'); } this.start = (start != null) ? parseFloat(start) : 0; this.end = (end != null) ? parseFloat(end) : 0; this.step = (step != null) ? parseFloat(step) : 1; }
n/a
function ResultSet(entries) { if (!(this instanceof ResultSet)) { throw new SyntaxError('Constructor must be called with the new operator'); } this.entries = entries || []; }
n/a
function Spa() { if (!(this instanceof Spa)) throw new SyntaxError('Constructor must be called with the new operator'); // allocate vector, TODO use typed arrays this._values = []; this._heap = new type.FibonacciHeap(); }
n/a
function SparseMatrix(data, datatype) { if (!(this instanceof SparseMatrix)) throw new SyntaxError('Constructor must be called with the new operator'); if (datatype && !isString(datatype)) throw new Error('Invalid datatype: ' + datatype); if (data && data.isMatrix === true) { // create from matrix _createFromMatrix(this, data, datatype); } else if (data && isArray(data.index) && isArray(data.ptr) && isArray(data.size)) { // initialize fields this._values = data.values; this._index = data.index; this._ptr = data.ptr; this._size = data.size; this._datatype = datatype || data.datatype; } else if (isArray(data)) { // create from array _createFromArray(this, data, datatype); } else if (data) { // unsupported type throw new TypeError('Unsupported type of data (' + util.types.type(data) + ')'); } else { // nothing provided this._values = []; this._index = []; this._ptr = [0]; this._size = [0, 0]; this._datatype = datatype; } }
n/a
function Unit(value, name) { if (!(this instanceof Unit)) { throw new Error('Constructor must be called with the new operator'); } if (!(value === undefined || isNumeric(value) || value.isComplex)) { throw new TypeError('First parameter in Unit constructor must be number, BigNumber, Fraction, Complex, or undefined'); } if (name != undefined && (typeof name !== 'string' || name == '')) { throw new TypeError('Second parameter in Unit constructor must be a string'); } if (name != undefined) { var u = Unit.parse(name); this.units = u.units; this.dimensions = u.dimensions; } else { this.units = [ { unit: UNIT_NONE, prefix: PREFIXES.NONE, // link to a list with supported prefixes power: 0 } ]; this.dimensions = []; for(var i=0; i<BASE_DIMENSIONS.length; i++) { this.dimensions[i] = 0; } } this.value = (value != undefined) ? this._normalize(value) : null; this.fixPrefix = false; // if true, function format will not search for the // best prefix but leave it as initially provided. // fixPrefix is set true by the method Unit.to // The justification behind this is that if the constructor is explicitly called, // the caller wishes the units to be returned exactly as he supplied. this.isUnitListSimplified = true; }
n/a
function typed(arg0, arg1) { "use strict"; var name = 'typed'; if (test0(arg0)) { // type: string if (test1(arg1)) { // type: Object if (arguments.length === 2) { return signature0(arg0, arg1); // signature: string, Object } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'Object'); } if (test2(arg0)) { // type: ...Function var varArgs = [arg0]; for (var i = 1; i < arguments.length; i++) { if (test2(arguments[i])) { varArgs.push(arguments[i]); } else { throw createError(name, arguments.length, i, arguments[i], 'Function'); } } return signature1(varArgs); // signature: ...Function } if (test1(arg0)) { // type: Object if (arguments.length === 1) { return signature2(arg0); // signature: Object } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'string,Function,Object'); }
n/a
function _typeof(arg0) { "use strict"; var name = '_typeof'; // type: any if (arguments.length === 1) { return signature0(arg0); // signature: any } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } throw createError(name, arguments.length, 0, arguments[0], 'any'); }
...
/**
* Determine the type of a variable.
*
* Function `typeof` recognizes the following types of objects:
*
* Object | Returns | Example
* ---------------------- | ------------- | ------------------------------------------
* null | `'null'` | `math.typeof(null)`
* number | `'number'` | `math.typeof(3.5)`
* boolean | `'boolean'` | `math.typeof (true)`
* string | `'string'` | `math.typeof ('hello world')`
* Array | `'Array'` | `math.typeof ([1, 2, 3])`
* Date | `'Date'` | `math.typeof (new Date())`
* Function | `'Function'` | `math.typeof (function () {})`
* Object | `'Object'` | `math.typeof ({a: 2, b: 3})`
...
function unaryMinus(arg0) { "use strict"; var name = 'unaryMinus'; if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature0(arg0); // signature: number } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: Complex if (arguments.length === 1) { return signature1(arg0); // signature: Complex } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test2(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature2(arg0); // signature: BigNumber } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test3(arg0)) { // type: Fraction if (arguments.length === 1) { return signature3(arg0); // signature: Fraction } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test4(arg0)) { // type: Unit if (arguments.length === 1) { return signature4(arg0); // signature: Unit } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test5(arg0)) { // type: Array if (arguments.length === 1) { return signature5(arg0); // signature: Array } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test6(arg0)) { // type: Matrix if (arguments.length === 1) { return signature5(arg0); // signature: Matrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test7(arg0)) { // type: string (convert to number) if (arguments.length === 1) { return signature0(convert0(arg0)); // signature: string } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test8(arg0)) { // type: boolean (convert to number) if (arguments.length === 1) { return signature0(convert1(arg0)); // signature: boolean } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test9(arg0)) { // type: null (convert to number) if (arguments.length === 1) { return signature0(convert2(arg0)); // signature: null } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'number,Complex,BigNumber,Fraction,Unit,Array,Matrix'); }
...
*
* For matrices, the function is evaluated element wise. Boolean values and
* strings will be converted to a number. For complex numbers, both real and
* complex value are inverted.
*
* Syntax:
*
* math.unaryMinus(x)
*
* Examples:
*
* math.unaryMinus(3.5); // returns -3.5
* math.unaryMinus(-4.2); // returns 4.2
*
* See also:
...
function unaryPlus(arg0) { "use strict"; var name = 'unaryPlus'; if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature0(arg0); // signature: number } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: Complex if (arguments.length === 1) { return signature1(arg0); // signature: Complex } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test2(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature2(arg0); // signature: BigNumber } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test3(arg0)) { // type: Fraction if (arguments.length === 1) { return signature3(arg0); // signature: Fraction } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test4(arg0)) { // type: Unit if (arguments.length === 1) { return signature4(arg0); // signature: Unit } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test5(arg0)) { // type: string if (arguments.length === 1) { return signature5(arg0); // signature: string } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test6(arg0)) { // type: Array if (arguments.length === 1) { return signature6(arg0); // signature: Array } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test7(arg0)) { // type: Matrix if (arguments.length === 1) { return signature6(arg0); // signature: Matrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test8(arg0)) { // type: boolean if (arguments.length === 1) { return signature5(arg0); // signature: boolean } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test9(arg0)) { // type: null if (arguments.length === 1) { return signature5(arg0); // signature: null } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'number,Complex,BigNumber,Fraction,Unit,string,Array,Matrix,boolean ,null'); }
...
* Unary plus operation.
* Boolean values and strings will be converted to a number, numeric values will be returned as is.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.unaryPlus(x)
*
* Examples:
*
* math.unaryPlus(3.5); // returns 3.5
* math.unaryPlus(1); // returns 1
*
* See also:
...
function unequal(arg0, arg1) { "use strict"; var name = 'unequal'; if (test0(arg0)) { // type: Array if (test0(arg1)) { // type: Array if (arguments.length === 2) { return signature0(arg0, arg1); // signature: Array, Array } } if (test1(arg1)) { // type: Matrix if (arguments.length === 2) { return signature1(arg0, arg1); // signature: Array, Matrix } } // type: any if (arguments.length === 2) { return signature2(arg0, arg1); // signature: Array, any } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test1(arg0)) { // type: Matrix if (test0(arg1)) { // type: Array if (arguments.length === 2) { return signature3(arg0, arg1); // signature: Matrix, Array } } if (test1(arg1)) { // type: Matrix if (arguments.length === 2) { return signature4(arg0, arg1); // signature: Matrix, Matrix } } // type: any if (arguments.length === 2) { return signature5(arg0, arg1); // signature: Matrix, any } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } // type: any if (test0(arg1)) { // type: Array if (arguments.length === 2) { return signature6(arg0, arg1); // signature: any, Array } } if (test1(arg1)) { // type: Matrix if (arguments.length === 2) { return signature7(arg0, arg1); // signature: any, Matrix } } // type: any if (arguments.length === 2) { return signature8(arg0, arg1); // signature: any, any } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } throw createError(name, arguments.length, 1, arguments[1], 'Array,Matrix,any'); throw createError(name, arguments.length, 0, arguments[0], 'Array,Matrix,any'); }
...
*
* Values `null` and `undefined` are compared strictly, thus `null` is unequal
* with everything except `null`, and `undefined` is unequal with everying
* except. `undefined`.
*
* Syntax:
*
* math.unequal(x, y)
*
* Examples:
*
* math.unequal(2 + 2, 3); // returns true
* math.unequal(2 + 2, 4); // returns false
*
* var a = math.unit('50 cm');
...
function unit(arg0, arg1) { "use strict"; var name = 'unit'; if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature0(convert0(arg0)); // signature: number } if (test1(arg1)) { // type: string if (arguments.length === 2) { return signature1(arg0, arg1); // signature: number, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test0(arg1)) { // type: number (convert to string) if (arguments.length === 2) { return signature1(arg0, convert0(arg1)); // signature: number, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: boolean (convert to string) if (arguments.length === 2) { return signature1(arg0, convert1(arg1)); // signature: number, boolean } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: null (convert to string) if (arguments.length === 2) { return signature1(arg0, convert2(arg1)); // signature: number, null } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'string'); } if (test4(arg0)) { // type: Complex if (test1(arg1)) { // type: string if (arguments.length === 2) { return signature1(arg0, arg1); // signature: Complex, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test0(arg1)) { // type: number (convert to string) if (arguments.length === 2) { return signature1(arg0, convert0(arg1)); // signature: Complex, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: boolean (convert to string) if (arguments.length === 2) { return signature1(arg0, convert1(arg1)); // signature: Complex, boolean } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: null (convert to string) if (arguments.length === 2) { return signature1(arg0, convert2(arg1)); // signature: Complex, null } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'string'); } if (test5(arg0)) { // type: BigNumber if (test1(arg1)) { // type: string if (arguments.length === 2) { return signature1(arg0, arg1); // signature: BigNumber, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test0(arg1)) { // type: number (convert to string) if (arguments.length === 2) { return signature1(arg0, convert0(arg1)); // signature: BigNumber, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: boolean (convert to string) if (arguments.length === 2) { return signature1(arg0, convert1(arg1)); // signature: BigNumber, boolean } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: null (convert to string) if (arguments.length === 2) { return signature1(arg0, convert2(arg1)); // signature: BigNumber, null } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'string'); } if (test6(arg0)) { // type: Fraction if (test1(arg1)) { // type: string if (argument ...
...
*
* Examples:
*
* math.number(2); // returns number 2
* math.number('7.2'); // returns number 7.2
* math.number(true); // returns number 1
* math.number([true, false, true, true]); // returns [1, 0, 1, 1]
* math.number(math.unit('52cm'), 'm'); // returns 0.52
*
* See also:
*
* bignumber, boolean, complex, index, matrix, string, unit
*
* @param {string | number | BigNumber | Fraction | boolean | Array | Matrix | Unit | null} [value] Value to be converted
* @param {Unit | string} [valuelessUnit] A valueless unit, used to convert a unit to a number
...
function usolve(arg0, arg1) { "use strict"; var name = 'usolve'; if (test0(arg0)) { // type: Array if (test0(arg1)) { // type: Array if (arguments.length === 2) { return signature0(arg0, arg1); // signature: Array, Array } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test1(arg1)) { // type: Matrix if (arguments.length === 2) { return signature0(arg0, arg1); // signature: Array, Matrix } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'Array,Matrix'); } if (test2(arg0)) { // type: DenseMatrix if (test0(arg1)) { // type: Array if (arguments.length === 2) { return signature1(arg0, arg1); // signature: DenseMatrix, Array } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test1(arg1)) { // type: Matrix if (arguments.length === 2) { return signature1(arg0, arg1); // signature: DenseMatrix, Matrix } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'Array,Matrix'); } if (test3(arg0)) { // type: SparseMatrix if (test0(arg1)) { // type: Array if (arguments.length === 2) { return signature2(arg0, arg1); // signature: SparseMatrix, Array } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test1(arg1)) { // type: Matrix if (arguments.length === 2) { return signature2(arg0, arg1); // signature: SparseMatrix, Matrix } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'Array,Matrix'); } if (test1(arg0)) { // type: Matrix (convert to Array) if (test0(arg1)) { // type: Array if (arguments.length === 2) { return signature0(convert0(arg0), arg1); // signature: Matrix, Array } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test1(arg1)) { // type: Matrix if (arguments.length === 2) { return signature0(convert0(arg0), arg1); // signature: Matrix, Matrix } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'Array,Matrix'); } throw createError(name, arguments.length, 0, arguments[0], 'Array,DenseMatrix,SparseMatrix'); }
n/a
function variance(arg0, arg1) { "use strict"; var name = 'variance'; if (test0(arg0)) { // type: Array if (arguments.length === 1) { return signature0(arg0); // signature: Array } if (test1(arg1)) { // type: string if (arguments.length === 2) { return signature1(arg0, arg1); // signature: Array, string } } if (test2(arg1)) { // type: number (convert to string) if (arguments.length === 2) { return signature1(arg0, convert0(arg1)); // signature: Array, number } } if (test3(arg1)) { // type: boolean (convert to string) if (arguments.length === 2) { return signature1(arg0, convert1(arg1)); // signature: Array, boolean } } if (test4(arg1)) { // type: null (convert to string) if (arguments.length === 2) { return signature1(arg0, convert2(arg1)); // signature: Array, null } } } if (test5(arg0)) { // type: Matrix if (arguments.length === 1) { return signature0(arg0); // signature: Matrix } if (test1(arg1)) { // type: string if (arguments.length === 2) { return signature1(arg0, arg1); // signature: Matrix, string } } if (test2(arg1)) { // type: number (convert to string) if (arguments.length === 2) { return signature1(arg0, convert0(arg1)); // signature: Matrix, number } } if (test3(arg1)) { // type: boolean (convert to string) if (arguments.length === 2) { return signature1(arg0, convert1(arg1)); // signature: Matrix, boolean } } if (test4(arg1)) { // type: null (convert to string) if (arguments.length === 2) { return signature1(arg0, convert2(arg1)); // signature: Matrix, null } } } if (arguments.length > 0) { var varArgs = []; for (var i = 0; i < arguments.length; i++) { varArgs.push(arguments[i]); } return signature2(varArgs); // signature: ...any } throw createError(name, arguments.length, 0, arguments[0], 'Array,Matrix,any'); }
...
*
* - 'unbiased' (default) The sum of squared errors is divided by (n - 1)
* - 'uncorrected' The sum of squared errors is divided by n
* - 'biased' The sum of squared errors is divided by (n + 1)
*
* Note that older browser may not like the variable name `var`. In that
* case, the function can be called as `math['var'](...)` instead of
* `math.var(...)`.
*
* Syntax:
*
* math.var(a, b, c, ...)
* math.var(A)
* math.var(A, normalization)
*
...
function xgcd(arg0, arg1) { "use strict"; var name = 'xgcd'; if (test0(arg0)) { // type: number if (test0(arg1)) { // type: number if (arguments.length === 2) { return signature0(arg0, arg1); // signature: number, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test1(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature1(convert0(arg0), arg1); // signature: number, BigNumber } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: Fraction (convert to BigNumber) if (arguments.length === 2) { return signature1(convert0(arg0), convert1(arg1)); // signature: number, Fraction } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: string (convert to number) if (arguments.length === 2) { return signature0(arg0, convert2(arg1)); // signature: number, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test4(arg1)) { // type: boolean (convert to number) if (arguments.length === 2) { return signature0(arg0, convert3(arg1)); // signature: number, boolean } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test5(arg1)) { // type: null (convert to number) if (arguments.length === 2) { return signature0(arg0, convert4(arg1)); // signature: number, null } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'number,BigNumber'); } if (test1(arg0)) { // type: BigNumber if (test1(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature1(arg0, arg1); // signature: BigNumber, BigNumber } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test0(arg1)) { // type: number (convert to BigNumber) if (arguments.length === 2) { return signature1(arg0, convert0(arg1)); // signature: BigNumber, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: Fraction (convert to BigNumber) if (arguments.length === 2) { return signature1(arg0, convert1(arg1)); // signature: BigNumber, Fraction } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: string (convert to BigNumber) if (arguments.length === 2) { return signature1(arg0, convert5(arg1)); // signature: BigNumber, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test4(arg1)) { // type: boolean (convert to BigNumber) if (arguments.length === 2) { return signature1(arg0, convert6(arg1)); // signature: BigNumber, boolean } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test5(arg1)) { // type: null (convert to BigNumber) if (arguments.length === 2) { return signature1(arg0, convert7(arg1)); // signature: BigNumber, null } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'BigNumber'); } if (test2(arg0)) { // type: Fraction (convert to BigNumber) if (test1(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature1(convert1(arg0), arg1); // signature: Fraction, BigNumber } if ...
...
/**
* Calculate the extended greatest common divisor for two values.
* See http://en.wikipedia.org/wiki/Extended_Euclidean_algorithm.
*
* Syntax:
*
* math.xgcd(a, b)
*
* Examples:
*
* math.xgcd(8, 12); // returns [4, -1, 1]
* math.gcd(8, 12); // returns 4
* math.xgcd(36163, 21199); // returns [1247, -7, 12]
*
...
function xor(arg0, arg1) { "use strict"; var name = 'xor'; if (test0(arg0)) { // type: number if (test0(arg1)) { // type: number if (arguments.length === 2) { return signature0(arg0, arg1); // signature: number, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test1(arg1)) { // type: Complex if (arguments.length === 2) { return signature1(convert0(arg0), arg1); // signature: number, Complex } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature2(convert1(arg0), arg1); // signature: number, BigNumber } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: Fraction (convert to BigNumber) if (arguments.length === 2) { return signature2(convert1(arg0), convert2(arg1)); // signature: number, Fraction } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test4(arg1)) { // type: string (convert to number) if (arguments.length === 2) { return signature0(arg0, convert3(arg1)); // signature: number, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test5(arg1)) { // type: boolean (convert to number) if (arguments.length === 2) { return signature0(arg0, convert4(arg1)); // signature: number, boolean } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test6(arg1)) { // type: null (convert to number) if (arguments.length === 2) { return signature0(arg0, convert5(arg1)); // signature: number, null } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } } if (test1(arg0)) { // type: Complex if (test1(arg1)) { // type: Complex if (arguments.length === 2) { return signature1(arg0, arg1); // signature: Complex, Complex } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test0(arg1)) { // type: number (convert to Complex) if (arguments.length === 2) { return signature1(arg0, convert0(arg1)); // signature: Complex, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: BigNumber (convert to Complex) if (arguments.length === 2) { return signature1(arg0, convert6(arg1)); // signature: Complex, BigNumber } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: Fraction (convert to Complex) if (arguments.length === 2) { return signature1(arg0, convert7(arg1)); // signature: Complex, Fraction } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test4(arg1)) { // type: string (convert to Complex) if (arguments.length === 2) { return signature1(arg0, convert8(arg1)); // signature: Complex, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } } if (test2(arg0)) { // type: BigNumber if (test1(arg1)) { // type: Complex if (arguments.length === 2) { return signature1(convert6(arg0), arg1); // signature: BigNumber, Complex } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature2(arg0, arg1); // ...
...
/**
* Logical `xor`. Test whether one and only one value is defined with a nonzero/nonempty value.
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.xor(x, y)
*
* Examples:
*
* math.xor(2, 4); // returns false
*
* a = [2, 0, 0];
* b = [2, 7, 0];
...
function zeros(arg0, arg1) { "use strict"; var name = 'zeros'; if (arguments.length === 0) { return signature0(); // signature: } if (test0(arg0)) { // type: Array if (arguments.length === 1) { return signature1(arg0); // signature: Array } if (test1(arg1)) { // type: string if (arguments.length === 2) { return signature2(arg0, arg1); // signature: Array, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: number (convert to string) if (arguments.length === 2) { return signature2(arg0, convert0(arg1)); // signature: Array, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: boolean (convert to string) if (arguments.length === 2) { return signature2(arg0, convert1(arg1)); // signature: Array, boolean } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test4(arg1)) { // type: null (convert to string) if (arguments.length === 2) { return signature2(arg0, convert2(arg1)); // signature: Array, null } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'string'); } if (test5(arg0)) { // type: Matrix if (arguments.length === 1) { return signature3(arg0); // signature: Matrix } if (test1(arg1)) { // type: string if (arguments.length === 2) { return signature2(arg0, arg1); // signature: Matrix, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: number (convert to string) if (arguments.length === 2) { return signature2(arg0, convert0(arg1)); // signature: Matrix, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: boolean (convert to string) if (arguments.length === 2) { return signature2(arg0, convert1(arg1)); // signature: Matrix, boolean } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test4(arg1)) { // type: null (convert to string) if (arguments.length === 2) { return signature2(arg0, convert2(arg1)); // signature: Matrix, null } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'string'); } if (test2(arg0) || test6(arg0) || test1(arg0) || test7(arg0) || test3(arg0) || test3(arg0) || test3(arg0) || test4(arg0) || test4 (arg0) || test4(arg0)) { // type: ...number|BigNumber|string|Fraction|boolean|null var varArgs = [arg0]; for (var i = 1; i < arguments.length; i++) { if (test2(arguments[i]) || test6(arguments[i]) || test1(arguments[i])) { varArgs.push(arguments[i]); } else if (test7(arguments[i])) { varArgs.push(convert3(arguments[i])); } else if (test3(arguments[i])) { varArgs.push(convert4(arguments[i])); } else if (test3(arguments[i])) { varArgs.push(convert5(arguments[i])); } else if (test3(arguments[i])) { varArgs.push(convert1(arguments[i])); } else if (test4(arguments[i])) { varArgs.push(convert6(arguments[i])); } else if (test4(arguments[i])) { varArgs.push(convert2(arguments[i])); } else if (test4(arguments[i])) { varArgs.push(convert7(arguments[i])); } else { throw createError(name, arguments.length, i, arguments[i], 'number,BigNumber,string'); } } return signature4(varArgs); // signature: ...number|BigN ...
...
* math.squeeze(x)
*
* Examples:
*
* math.squeeze([3]); // returns 3
* math.squeeze([[3]]); // returns 3
*
* var A = math.zeros(3, 1); // returns [[0], [0], [0]] (size 3x1)
* math.squeeze(A); // returns [0, 0, 0] (size 3)
*
* var B = math.zeros(1, 3); // returns [[0, 0, 0]] (size 1x3)
* math.squeeze(B); // returns [0, 0, 0] (size 3)
*
* // only inner and outer dimensions are removed
* var C = math.zeros(2, 1, 3); // returns [[[0, 0, 0]], [[0, 0, 0]]] (size 2x1x3)
...
function factory(type, config, load, typed) {
var Node = load(require('./Node'));
var access = load(require('./utils/access'));
var getSafeProperty = load(require('./utils/customs')).getSafeProperty;
/**
* @constructor AccessorNode
* @extends {Node}
* Access an object property or get a matrix subset
*
* @param {Node} object The object from which to retrieve
* a property or subset.
* @param {IndexNode} index IndexNode containing ranges
*/
function AccessorNode(object, index) {
if (!(this instanceof AccessorNode)) {
throw new SyntaxError('Constructor must be called with the new operator');
}
if (!(object && object.isNode)) {
throw new TypeError('Node expected for parameter "object"');
}
if (!(index && index.isIndexNode)) {
throw new TypeError('IndexNode expected for parameter "index"');
}
this.object = object || null;
this.index = index;
// readonly property name
Object.defineProperty(this, 'name', {
get: function () {
if (this.index) {
return (this.index.isObjectProperty())
? this.index.getObjectProperty()
: '';
}
else {
return this.object.name || '';
}
}.bind(this),
set: function () {
throw new Error('Cannot assign a new name, name is read-only');
}
});
}
AccessorNode.prototype = new Node();
AccessorNode.prototype.type = 'AccessorNode';
AccessorNode.prototype.isAccessorNode = true;
/**
* Compile the node to javascript code
* @param {Object} defs Object which can be used to define functions
* or constants globally available for the compiled
* expression
* @param {Object} args Object with local function arguments, the key is
* the name of the argument, and the value is `true`.
* The object may not be mutated, but must be
* extended instead.
* @return {string} js
* @private
*/
AccessorNode.prototype._compile = function (defs, args) {
defs.access = access;
defs.getSafeProperty = getSafeProperty;
var object = this.object._compile(defs, args);
var index = this.index._compile(defs, args);
if (this.index.isObjectProperty()) {
var prop = this.index.getObjectProperty();
return 'getSafeProperty(' + object + ', "' + prop + '")';
}
else if (this.index.needsSize()) {
// if some parameters use the 'end' parameter, we need to calculate the size
return '(function () {' +
' var object = ' + object + ';' +
' var size = math.size(object).valueOf();' +
' return access(object, ' + index + ');' +
'})()';
}
else {
return 'access(' + object + ', ' + index + ')';
}
};
/**
* Execute a callback for each of the child nodes of this node
* @param {function(child: Node, path: string, parent: Node)} callback
*/
AccessorNode.prototype.forEach = function (callback) {
callback(this.object, 'object', this);
callback(this.index, 'index', this);
};
/**
* Create a new AccessorNode having it's childs be the results of calling
* the provided callback function for each of the childs of the original node.
* @param {function(child: Node, path: string, parent: Node): Node} callback
* @returns {AccessorNode} Returns a transformed copy of the node
*/
AccessorNode.prototype.map = function (callback) {
return new AccessorNode(
this._ifNode(callback(this.object, 'object', this)),
this._ifNode(callback(this.index, 'index', this))
);
};
/**
* Create a clone of this node, a shallow copy
* @return {AccessorNode}
*/
AccessorNode.prototype.clone = function () {
return new AccessorNode(this.object, this.index);
};
/**
* Get string representation
* @param {Object} options
* @return {string}
*/
AccessorNode.pr ...
n/a
function factory(type, config, load, typed) {
var Node = load(require('./Node'));
/**
* @constructor ArrayNode
* @extends {Node}
* Holds an 1-dimensional array with items
* @param {Node[]} [items] 1 dimensional array with items
*/
function ArrayNode(items) {
if (!(this instanceof ArrayNode)) {
throw new SyntaxError('Constructor must be called with the new operator');
}
this.items = items || [];
// validate input
if (!Array.isArray(this.items)
|| !this.items.every(function (item) {return item && item.isNode;})) {
throw new TypeError('Array containing Nodes expected');
}
// TODO: deprecated since v3, remove some day
var deprecated = function () {
throw new Error('Property `ArrayNode.nodes` is deprecated, use `ArrayNode.items` instead');
};
Object.defineProperty(this, 'nodes', { get: deprecated, set: deprecated });
}
ArrayNode.prototype = new Node();
ArrayNode.prototype.type = 'ArrayNode';
ArrayNode.prototype.isArrayNode = true;
/**
* Compile the node to javascript code
* @param {Object} defs Object which can be used to define functions
* or constants globally available for the compiled
* expression
* @param {Object} args Object with local function arguments, the key is
* the name of the argument, and the value is `true`.
* The object may not be mutated, but must be
* extended instead.
* @private
*/
ArrayNode.prototype._compile = function (defs, args) {
var asMatrix = (defs.math.config().matrix !== 'Array');
var items = this.items.map(function (node) {
return node._compile(defs, args);
});
return (asMatrix ? 'math.matrix([' : '[') +
items.join(',') +
(asMatrix ? '])' : ']');
};
/**
* Execute a callback for each of the child nodes of this node
* @param {function(child: Node, path: string, parent: Node)} callback
*/
ArrayNode.prototype.forEach = function (callback) {
for (var i = 0; i < this.items.length; i++) {
var node = this.items[i];
callback(node, 'items[' + i + ']', this);
}
};
/**
* Create a new ArrayNode having it's childs be the results of calling
* the provided callback function for each of the childs of the original node.
* @param {function(child: Node, path: string, parent: Node): Node} callback
* @returns {ArrayNode} Returns a transformed copy of the node
*/
ArrayNode.prototype.map = function (callback) {
var items = [];
for (var i = 0; i < this.items.length; i++) {
items[i] = this._ifNode(callback(this.items[i], 'items[' + i + ']', this));
}
return new ArrayNode(items);
};
/**
* Create a clone of this node, a shallow copy
* @return {ArrayNode}
*/
ArrayNode.prototype.clone = function() {
return new ArrayNode(this.items.slice(0));
};
/**
* Get string representation
* @param {Object} options
* @return {string} str
* @override
*/
ArrayNode.prototype._toString = function(options) {
var items = this.items.map(function (node) {
return node.toString(options);
});
return '[' + items.join(', ') + ']';
};
/**
* Get LaTeX representation
* @param {Object} options
* @return {string} str
*/
ArrayNode.prototype._toTex = function(options) {
var s = '\\begin{bmatrix}';
this.items.forEach(function(node) {
if (node.items) {
s += node.items.map(function(childNode) {
return childNode.toTex(options);
}).join('&');
}
else {
s += node.toTex(options);
}
// new line
s += '\\\\';
});
s += '\\end{bmatrix}';
return s;
};
return ArrayNode;
}
n/a
function factory(type, config, load, typed) {
var Node = load(require('./Node'));
var ArrayNode = load(require('./ArrayNode'));
var matrix = load(require('../../type/matrix/function/matrix'));
var assign = load(require('./utils/assign'));
var access = load(require('./utils/access'));
var getSafeProperty = load(require('./utils/customs')).getSafeProperty;
var setSafeProperty = load(require('./utils/customs')).setSafeProperty;
var keywords = require('../keywords');
var operators = require('../operators');
/**
* @constructor AssignmentNode
* @extends {Node}
*
* Define a symbol, like `a=3.2`, update a property like `a.b=3.2`, or
* replace a subset of a matrix like `A[2,2]=42`.
*
* Syntax:
*
* new AssignmentNode(symbol, value)
* new AssignmentNode(object, index, value)
*
* Usage:
*
* new AssignmentNode(new SymbolNode('a'), new ConstantNode(2)); // a=2
* new AssignmentNode(new SymbolNode('a'), new IndexNode('b'), new ConstantNode(2)) // a.b=2
* new AssignmentNode(new SymbolNode('a'), new IndexNode(1, 2), new ConstantNode(3)) // a[1,2]=3
*
* @param {SymbolNode | AccessorNode} object Object on which to assign a value
* @param {IndexNode} [index=null] Index, property name or matrix
* index. Optional. If not provided
* and `object` is a SymbolNode,
* the property is assigned to the
* global scope.
* @param {Node} value The value to be assigned
*/
function AssignmentNode(object, index, value) {
if (!(this instanceof AssignmentNode)) {
throw new SyntaxError('Constructor must be called with the new operator');
}
this.object = object;
this.index = value ? index : null;
this.value = value ? value : index;
// validate input
if (!object || !(object.isSymbolNode || object.isAccessorNode)) {
throw new TypeError('SymbolNode or AccessorNode expected as "object"');
}
if (object && object.isSymbolNode && object.name === 'end') {
throw new Error('Cannot assign to symbol "end"');
}
if (this.index && !this.index.isIndexNode) {
throw new TypeError('IndexNode expected as "index"');
}
if (!this.value || !this.value.isNode) {
throw new TypeError('Node expected as "value"');
}
// readonly property name
Object.defineProperty(this, 'name', {
get: function () {
if (this.index) {
return (this.index.isObjectProperty())
? this.index.getObjectProperty()
: '';
}
else {
return this.object.name || '';
}
}.bind(this),
set: function () {
throw new Error('Cannot assign a new name, name is read-only');
}
});
}
AssignmentNode.prototype = new Node();
AssignmentNode.prototype.type = 'AssignmentNode';
AssignmentNode.prototype.isAssignmentNode = true;
/**
* Compile the node to javascript code
* @param {Object} defs Object which can be used to define functions
* or constants globally available for the compiled
* expression
* @param {Object} args Object with local function arguments, the key is
* the name of the argument, and the value is `true`.
* The object may not be mutated, but must be
* extended instead.
* @private
*/
AssignmentNode.prototype._compile = function (defs, args) {
defs.assign = assign;
defs.access = access;
defs.getSafeProperty = getSafeProperty;
defs.setSafeProperty = setSafeProperty;
var size;
var object = this.object._compile(defs, args);
var index = this.index ? this.index._compile(defs, args) : null;
var value = this.value._compile(defs, args);
if (!this.index) {
// apply a variab ...
n/a
function factory(type, config, load, typed, math) {
var BigNumber = Decimal.clone({precision: config.precision});
/**
* Attach type information
*/
BigNumber.prototype.type = 'BigNumber';
BigNumber.prototype.isBigNumber = true;
/**
* Get a JSON representation of a BigNumber containing
* type information
* @returns {Object} Returns a JSON object structured as:
* `{"mathjs": "BigNumber", "value": "0.2"}`
*/
BigNumber.prototype.toJSON = function () {
return {
mathjs: 'BigNumber',
value: this.toString()
};
};
/**
* Instantiate a BigNumber from a JSON object
* @param {Object} json a JSON object structured as:
* `{"mathjs": "BigNumber", "value": "0.2"}`
* @return {BigNumber}
*/
BigNumber.fromJSON = function (json) {
return new BigNumber(json.value);
};
// listen for changed in the configuration, automatically apply changed precision
math.on('config', function (curr, prev) {
if (curr.precision !== prev.precision) {
BigNumber.config({ precision: curr.precision });
}
});
return BigNumber;
}
n/a
function factory(type, config, load, typed) {
var Node = load(require('./Node'));
var ResultSet = load(require('../../type/resultset/ResultSet'));
/**
* @constructor BlockNode
* @extends {Node}
* Holds a set with blocks
* @param {Array.<{node: Node} | {node: Node, visible: boolean}>} blocks
* An array with blocks, where a block is constructed as an Object
* with properties block, which is a Node, and visible, which is
* a boolean. The property visible is optional and is true by default
*/
function BlockNode(blocks) {
if (!(this instanceof BlockNode)) {
throw new SyntaxError('Constructor must be called with the new operator');
}
// validate input, copy blocks
if (!Array.isArray(blocks)) throw new Error('Array expected');
this.blocks = blocks.map(function (block) {
var node = block && block.node;
var visible = block && block.visible !== undefined ? block.visible : true;
if (!(node && node.isNode)) throw new TypeError('Property "node" must be a Node');
if (typeof visible !== 'boolean') throw new TypeError('Property "visible" must be a boolean');
return {
node: node,
visible: visible
}
});
}
BlockNode.prototype = new Node();
BlockNode.prototype.type = 'BlockNode';
BlockNode.prototype.isBlockNode = true;
/**
* Compile the node to javascript code
* @param {Object} defs Object which can be used to define functions
* or constants globally available for the compiled
* expression
* @param {Object} args Object with local function arguments, the key is
* the name of the argument, and the value is `true`.
* The object may not be mutated, but must be
* extended instead.
* @return {string} js
* @private
*/
BlockNode.prototype._compile = function (defs, args) {
defs.ResultSet = ResultSet;
var blocks = this.blocks.map(function (param) {
var js = param.node._compile(defs, args);
if (param.visible) {
return 'results.push(' + js + ');';
}
else {
return js + ';';
}
});
return '(function () {' +
'var results = [];' +
blocks.join('') +
'return new ResultSet(results);' +
'})()';
};
/**
* Execute a callback for each of the child blocks of this node
* @param {function(child: Node, path: string, parent: Node)} callback
*/
BlockNode.prototype.forEach = function (callback) {
for (var i = 0; i < this.blocks.length; i++) {
callback(this.blocks[i].node, 'blocks[' + i + '].node', this);
}
};
/**
* Create a new BlockNode having it's childs be the results of calling
* the provided callback function for each of the childs of the original node.
* @param {function(child: Node, path: string, parent: Node): Node} callback
* @returns {BlockNode} Returns a transformed copy of the node
*/
BlockNode.prototype.map = function (callback) {
var blocks = [];
for (var i = 0; i < this.blocks.length; i++) {
var block = this.blocks[i];
var node = this._ifNode(callback(block.node, 'blocks[' + i + '].node', this));
blocks[i] = {
node: node,
visible: block.visible
};
}
return new BlockNode(blocks);
};
/**
* Create a clone of this node, a shallow copy
* @return {BlockNode}
*/
BlockNode.prototype.clone = function () {
var blocks = this.blocks.map(function (block) {
return {
node: block.node,
visible: block.visible
};
});
return new BlockNode(blocks);
};
/**
* Get string representation
* @param {Object} options
* @return {string} str
* @override
*/
BlockNode.prototype._toString = function (options) {
return this.blocks.map(function (param) {
return param.node.toString(options) + (param.visible ? '' : ';');
}).join('\n');
};
/**
* Get LaTeX represent ...
n/a
function factory(type, config, load, typed, math) {
/**
* @constructor Chain
* Wrap any value in a chain, allowing to perform chained operations on
* the value.
*
* All methods available in the math.js library can be called upon the chain,
* and then will be evaluated with the value itself as first argument.
* The chain can be closed by executing chain.done(), which will return
* the final value.
*
* The Chain has a number of special functions:
* - done() Finalize the chained operation and return the
* chain's value.
* - valueOf() The same as done()
* - toString() Returns a string representation of the chain's value.
*
* @param {*} [value]
*/
function Chain (value) {
if (!(this instanceof Chain)) {
throw new SyntaxError('Constructor must be called with the new operator');
}
if (value && value.isChain) {
this.value = value.value;
}
else {
this.value = value;
}
}
/**
* Attach type information
*/
Chain.prototype.type = 'Chain';
Chain.prototype.isChain = true;
/**
* Close the chain. Returns the final value.
* Does the same as method valueOf()
* @returns {*} value
*/
Chain.prototype.done = function () {
return this.value;
};
/**
* Close the chain. Returns the final value.
* Does the same as method done()
* @returns {*} value
*/
Chain.prototype.valueOf = function () {
return this.value;
};
/**
* Get a string representation of the value in the chain
* @returns {string}
*/
Chain.prototype.toString = function () {
return format(this.value);
};
/**
* Create a proxy method for the chain
* @param {string} name
* @param {Function} fn The function to be proxied
* If fn is no function, it is silently ignored.
* @private
*/
function createProxy(name, fn) {
if (typeof fn === 'function') {
Chain.prototype[name] = chainify(fn);
}
}
/**
* Create a proxy method for the chain
* @param {string} name
* @param {function} resolver The function resolving with the
* function to be proxied
* @private
*/
function createLazyProxy(name, resolver) {
lazy(Chain.prototype, name, function outerResolver() {
var fn = resolver();
if (typeof fn === 'function') {
return chainify(fn);
}
return undefined; // if not a function, ignore
});
}
/**
* Make a function chainable
* @param {function} fn
* @return {Function} chain function
* @private
*/
function chainify (fn) {
return function () {
var args = [this.value]; // `this` will be the context of a Chain instance
for (var i = 0; i < arguments.length; i++) {
args[i + 1] = arguments[i];
}
return new Chain(fn.apply(fn, args));
}
}
/**
* Create a proxy for a single method, or an object with multiple methods.
* Example usage:
*
* Chain.createProxy('add', function add (x, y) {...});
* Chain.createProxy({
* add: function add (x, y) {...},
* subtract: function subtract (x, y) {...}
* }
*
* @param {string | Object} arg0 A name (string), or an object with
* functions
* @param {*} [arg1] A function, when arg0 is a name
*/
Chain.createProxy = function (arg0, arg1) {
if (typeof arg0 === 'string') {
// createProxy(name, value)
createProxy(arg0, arg1);
}
else {
// createProxy(values)
for (var prop in arg0) {
if (arg0.hasOwnProperty(prop)) {
createProxy(prop, arg0[prop]);
}
}
}
};
// create proxy for everything that is in math.js
Chain.createProxy(math);
// register on the import event, automatically add a proxy for every imported function.
math.on('import', function (name, resolver, path) {
if (path === undefined) {
// an imported function (not a data type or something special) ...
n/a
function factory(type, config, load, typed, math) {
/**
* Attach type information
*/
Complex.prototype.type = 'Complex';
Complex.prototype.isComplex = true;
/**
* Get a JSON representation of the complex number
* @returns {Object} Returns a JSON object structured as:
* `{"mathjs": "Complex", "re": 2, "im": 3}`
*/
Complex.prototype.toJSON = function () {
return {
mathjs: 'Complex',
re: this.re,
im: this.im
};
};
/*
* Return the value of the complex number in polar notation
* The angle phi will be set in the interval of [-pi, pi].
* @return {{r: number, phi: number}} Returns and object with properties r and phi.
*/
Complex.prototype.toPolar = function () {
return {
r: this.abs(),
phi: this.arg()
};
};
/**
* Get a string representation of the complex number,
* with optional formatting options.
* @param {Object | number | Function} [options] Formatting options. See
* lib/utils/number:format for a
* description of the available
* options.
* @return {string} str
*/
Complex.prototype.format = function (options) {
var str = '';
var im = this.im;
var re = this.re;
var strRe = format(this.re, options);
var strIm = format(this.im, options);
// round either re or im when smaller than the configured precision
var precision = isNumber(options) ? options : options ? options.precision : null;
if (precision !== null) {
var epsilon = Math.pow(10, -precision);
if (Math.abs(re / im) < epsilon) {
re = 0;
}
if (Math.abs(im / re) < epsilon) {
im = 0;
}
}
if (im == 0) {
// real value
str = strRe;
} else if (re == 0) {
// purely complex value
if (im == 1) {
str = 'i';
} else if (im == -1) {
str = '-i';
} else {
str = strIm + 'i';
}
} else {
// complex value
if (im > 0) {
if (im == 1) {
str = strRe + ' + i';
} else {
str = strRe + ' + ' + strIm + 'i';
}
} else {
if (im == -1) {
str = strRe + ' - i';
} else {
str = strRe + ' - ' + strIm.substring(1) + 'i';
}
}
}
return str;
};
/**
* Create a complex number from polar coordinates
*
* Usage:
*
* Complex.fromPolar(r: number, phi: number) : Complex
* Complex.fromPolar({r: number, phi: number}) : Complex
*
* @param {*} args...
* @return {Complex}
*/
Complex.fromPolar = function (args) {
switch (arguments.length) {
case 1:
var arg = arguments[0];
if (typeof arg === 'object') {
return Complex(arg);
}
throw new TypeError('Input has to be an object with r and phi keys.');
case 2:
var r = arguments[0],
phi = arguments[1];
if (isNumber(r)) {
if (phi && phi.isUnit && phi.hasBase('ANGLE')) {
// convert unit to a number in radians
phi = phi.toNumber('rad');
}
if (isNumber(phi)) {
return new Complex({r: r, phi: phi});
}
throw new TypeError('Phi is not a number nor an angle unit.');
} else {
throw new TypeError('Radius r is not a number.');
}
default:
throw new SyntaxError('Wrong number of arguments in function fromPolar');
}
};
Complex.prototype.valueOf = Complex.prototype.toString;
/**
* Create a Complex number from a JSON object
* @param {Object} json A JSON Object structured as
* {"mathjs": "Complex", "re": 2, "im": 3}
* All properties are optional, default values
* for `re` and `im` are 0.
* @return {Complex} Returns a new Complex number
*/
Complex.fromJSON = function (json) {
return new C ...
n/a
function factory(type, config, load, typed) {
var Node = load(require('./Node'));
/**
* A lazy evaluating conditional operator: 'condition ? trueExpr : falseExpr'
*
* @param {Node} condition Condition, must result in a boolean
* @param {Node} trueExpr Expression evaluated when condition is true
* @param {Node} falseExpr Expression evaluated when condition is true
*
* @constructor ConditionalNode
* @extends {Node}
*/
function ConditionalNode(condition, trueExpr, falseExpr) {
if (!(this instanceof ConditionalNode)) {
throw new SyntaxError('Constructor must be called with the new operator');
}
if (!(condition && condition.isNode)) throw new TypeError('Parameter condition must be a Node');
if (!(trueExpr && trueExpr.isNode)) throw new TypeError('Parameter trueExpr must be a Node');
if (!(falseExpr && falseExpr.isNode)) throw new TypeError('Parameter falseExpr must be a Node');
this.condition = condition;
this.trueExpr = trueExpr;
this.falseExpr = falseExpr;
}
ConditionalNode.prototype = new Node();
ConditionalNode.prototype.type = 'ConditionalNode';
ConditionalNode.prototype.isConditionalNode = true;
/**
* Compile the node to javascript code
* @param {Object} defs Object which can be used to define functions
* or constants globally available for the compiled
* expression
* @param {Object} args Object with local function arguments, the key is
* the name of the argument, and the value is `true`.
* The object may not be mutated, but must be
* extended instead.
* @return {string} js
* @private
*/
ConditionalNode.prototype._compile = function (defs, args) {
/**
* Test whether a condition is met
* @param {*} condition
* @returns {boolean} true if condition is true or non-zero, else false
*/
defs.testCondition = function (condition) {
if (typeof condition === 'number'
|| typeof condition === 'boolean'
|| typeof condition === 'string') {
return condition ? true : false;
}
if (condition) {
if (condition.isBigNumber === true) {
return condition.isZero() ? false : true;
}
if (condition.isComplex === true) {
return (condition.re || condition.im) ? true : false;
}
if (condition.isUnit === true) {
return condition.value ? true : false;
}
}
if (condition === null || condition === undefined) {
return false;
}
throw new TypeError('Unsupported type of condition "' + defs.math['typeof'](condition) + '"');
};
return (
'testCondition(' + this.condition._compile(defs, args) + ') ? ' +
'( ' + this.trueExpr._compile(defs, args) + ') : ' +
'( ' + this.falseExpr._compile(defs, args) + ')'
);
};
/**
* Execute a callback for each of the child nodes of this node
* @param {function(child: Node, path: string, parent: Node)} callback
*/
ConditionalNode.prototype.forEach = function (callback) {
callback(this.condition, 'condition', this);
callback(this.trueExpr, 'trueExpr', this);
callback(this.falseExpr, 'falseExpr', this);
};
/**
* Create a new ConditionalNode having it's childs be the results of calling
* the provided callback function for each of the childs of the original node.
* @param {function(child: Node, path: string, parent: Node): Node} callback
* @returns {ConditionalNode} Returns a transformed copy of the node
*/
ConditionalNode.prototype.map = function (callback) {
return new ConditionalNode(
this._ifNode(callback(this.condition, 'condition', this)),
this._ifNode(callback(this.trueExpr, 'trueExpr', this)),
this._ifNode(callback(this.falseExpr, 'falseExpr', this))
);
};
/**
* Create a clone of this node, a shallow copy
* @return {ConditionalNode}
*/
ConditionalNode.prototyp ...
n/a
function factory(type, config, load, typed) {
var Node = load(require('./Node'));
/**
* A ConstantNode holds a constant value like a number or string. A ConstantNode
* stores a stringified version of the value and uses this to compile to
* JavaScript.
*
* In case of a stringified number as input, this may be compiled to a BigNumber
* when the math instance is configured for BigNumbers.
*
* Usage:
*
* // stringified values with type
* new ConstantNode('2.3', 'number');
* new ConstantNode('true', 'boolean');
* new ConstantNode('hello', 'string');
*
* // non-stringified values, type will be automatically detected
* new ConstantNode(2.3);
* new ConstantNode('hello');
*
* @param {string | number | boolean | null | undefined} value
* When valueType is provided, value must contain
* an uninterpreted string representing the value.
* When valueType is undefined, value can be a
* number, string, boolean, null, or undefined, and
* the type will be determined automatically.
* @param {string} [valueType] The type of value. Choose from 'number', 'string',
* 'boolean', 'undefined', 'null'
* @constructor ConstantNode
* @extends {Node}
*/
function ConstantNode(value, valueType) {
if (!(this instanceof ConstantNode)) {
throw new SyntaxError('Constructor must be called with the new operator');
}
if (valueType) {
if (typeof valueType !== 'string') {
throw new TypeError('String expected for parameter "valueType"');
}
if (typeof value !== 'string') {
throw new TypeError('String expected for parameter "value"');
}
this.value = value;
this.valueType = valueType;
}
else {
// stringify the value and determine the type
this.value = value + '';
this.valueType = getType(value);
}
if (!SUPPORTED_TYPES[this.valueType]) {
throw new TypeError('Unsupported type of value "' + this.valueType + '"');
}
}
var SUPPORTED_TYPES = {
'number': true,
'string': true,
'boolean': true,
'undefined': true,
'null': true
};
ConstantNode.prototype = new Node();
ConstantNode.prototype.type = 'ConstantNode';
ConstantNode.prototype.isConstantNode = true;
/**
* Compile the node to javascript code
* @param {Object} defs Object which can be used to define functions
* or constants globally available for the compiled
* expression
* @param {Object} args Object with local function arguments, the key is
* the name of the argument, and the value is `true`.
* The object may not be mutated, but must be
* extended instead.
* @return {string} js
* @private
*/
ConstantNode.prototype._compile = function (defs, args) {
switch (this.valueType) {
case 'number':
// TODO: replace this with using config.number
var numConfig = defs.math.config().number;
if (numConfig === 'BigNumber') {
return 'math.bignumber("' + this.value + '")';
}
else if (numConfig === 'Fraction') {
return 'math.fraction("' + this.value + '")';
}
else {
// remove leading zeros like '003.2' which are not allowed by JavaScript
return this.value.replace(/^(0*)[0-9]/, function (match, zeros) {
return match.substring(zeros.length);
});
}
case 'string':
return '"' + this.value + '"';
case 'boolean':
return this.value;
case 'undefined':
return this.value;
case 'null':
return this.value;
default:
// TODO: move this error to the constructor?
throw new TypeError('Unsupported type of constant "' + this.valueType + '"'); ...
n/a
function factory(type, config, load, typed) {
var Matrix = load(require('./Matrix')); // force loading Matrix (do not use via type.Matrix)
/**
* Dense Matrix implementation. A regular, dense matrix, supporting multi-dimensional matrices. This is the default matrix type
.
* @class DenseMatrix
*/
function DenseMatrix(data, datatype) {
if (!(this instanceof DenseMatrix))
throw new SyntaxError('Constructor must be called with the new operator');
if (datatype && !isString(datatype))
throw new Error('Invalid datatype: ' + datatype);
if (data && data.isMatrix === true) {
// check data is a DenseMatrix
if (data.type === 'DenseMatrix') {
// clone data & size
this._data = object.clone(data._data);
this._size = object.clone(data._size);
this._datatype = datatype || data._datatype;
}
else {
// build data from existing matrix
this._data = data.toArray();
this._size = data.size();
this._datatype = datatype || data._datatype;
}
}
else if (data && isArray(data.data) && isArray(data.size)) {
// initialize fields from JSON representation
this._data = data.data;
this._size = data.size;
this._datatype = datatype || data.datatype;
}
else if (isArray(data)) {
// replace nested Matrices with Arrays
this._data = preprocess(data);
// get the dimensions of the array
this._size = array.size(this._data);
// verify the dimensions of the array, TODO: compute size while processing array
array.validate(this._data, this._size);
// data type unknown
this._datatype = datatype;
}
else if (data) {
// unsupported type
throw new TypeError('Unsupported type of data (' + util.types.type(data) + ')');
}
else {
// nothing provided
this._data = [];
this._size = [0];
this._datatype = datatype;
}
}
DenseMatrix.prototype = new Matrix();
/**
* Attach type information
*/
DenseMatrix.prototype.type = 'DenseMatrix';
DenseMatrix.prototype.isDenseMatrix = true;
/**
* Get the storage format used by the matrix.
*
* Usage:
* var format = matrix.storage() // retrieve storage format
*
* @memberof DenseMatrix
* @return {string} The storage format.
*/
DenseMatrix.prototype.storage = function () {
return 'dense';
};
/**
* Get the datatype of the data stored in the matrix.
*
* Usage:
* var format = matrix.datatype() // retrieve matrix datatype
*
* @memberof DenseMatrix
* @return {string} The datatype.
*/
DenseMatrix.prototype.datatype = function () {
return this._datatype;
};
/**
* Create a new DenseMatrix
* @memberof DenseMatrix
* @param {Array} data
* @param {string} [datatype]
*/
DenseMatrix.prototype.create = function (data, datatype) {
return new DenseMatrix(data, datatype);
};
/**
* Get a subset of the matrix, or replace a subset of the matrix.
*
* Usage:
* var subset = matrix.subset(index) // retrieve subset
* var value = matrix.subset(index, replacement) // replace subset
*
* @memberof DenseMatrix
* @param {Index} index
* @param {Array | DenseMatrix | *} [replacement]
* @param {*} [defaultValue=0] Default value, filled in on new entries when
* the matrix is resized. If not provided,
* new matrix elements will be filled with zeros.
*/
DenseMatrix.prototype.subset = function (index, replacement, defaultValue) {
switch (arguments.length) {
case 1:
return _get(this, index);
// intentional fall through
case 2:
case 3:
return _set(this, index, replacement, defaultValue);
default:
throw new SyntaxError('Wrong number of arguments');
}
};
/**
* Get a single element from the matrix.
* @memberof DenseMatrix
* @param { ...
n/a
function factory(type, config, load, typed) {
var smaller = load(require('../../function/relational/smaller'));
var larger = load(require('../../function/relational/larger'));
var oneOverLogPhi = 1.0 / Math.log((1.0 + Math.sqrt(5.0)) / 2.0);
/**
* Fibonacci Heap implementation, used interally for Matrix math.
* @class FibonacciHeap
* @constructor FibonacciHeap
*/
function FibonacciHeap() {
if (!(this instanceof FibonacciHeap))
throw new SyntaxError('Constructor must be called with the new operator');
// initialize fields
this._minimum = null;
this._size = 0;
}
/**
* Attach type information
*/
FibonacciHeap.prototype.type = 'FibonacciHeap';
FibonacciHeap.prototype.isFibonacciHeap = true;
/**
* Inserts a new data element into the heap. No heap consolidation is
* performed at this time, the new node is simply inserted into the root
* list of this heap. Running time: O(1) actual.
* @memberof FibonacciHeap
*/
FibonacciHeap.prototype.insert = function (key, value) {
// create node
var node = {
key: key,
value: value,
degree: 0
};
// check we have a node in the minimum
if (this._minimum) {
// minimum node
var minimum = this._minimum;
// update left & right of node
node.left = minimum;
node.right = minimum.right;
minimum.right = node;
node.right.left = node;
// update minimum node in heap if needed
if (smaller(key, minimum.key)) {
// node has a smaller key, use it as minimum
this._minimum = node;
}
}
else {
// set left & right
node.left = node;
node.right = node;
// this is the first node
this._minimum = node;
}
// increment number of nodes in heap
this._size++;
// return node
return node;
};
/**
* Returns the number of nodes in heap. Running time: O(1) actual.
* @memberof FibonacciHeap
*/
FibonacciHeap.prototype.size = function () {
return this._size;
};
/**
* Removes all elements from this heap.
* @memberof FibonacciHeap
*/
FibonacciHeap.prototype.clear = function () {
this._minimum = null;
this._size = 0;
};
/**
* Returns true if the heap is empty, otherwise false.
* @memberof FibonacciHeap
*/
FibonacciHeap.prototype.isEmpty = function () {
return !!this._minimum;
};
/**
* Extracts the node with minimum key from heap. Amortized running
* time: O(log n).
* @memberof FibonacciHeap
*/
FibonacciHeap.prototype.extractMinimum = function () {
// node to remove
var node = this._minimum;
// check we have a minimum
if (node === null)
return node;
// current minimum
var minimum = this._minimum;
// get number of children
var numberOfChildren = node.degree;
// pointer to the first child
var x = node.child;
// for each child of node do...
while (numberOfChildren > 0) {
// store node in right side
var tempRight = x.right;
// remove x from child list
x.left.right = x.right;
x.right.left = x.left;
// add x to root list of heap
x.left = minimum;
x.right = minimum.right;
minimum.right = x;
x.right.left = x;
// set Parent[x] to null
x.parent = null;
x = tempRight;
numberOfChildren--;
}
// remove node from root list of heap
node.left.right = node.right;
node.right.left = node.left;
// update minimum
if (node == node.right) {
// empty
minimum = null;
}
else {
// update minimum
minimum = node.right;
// we need to update the pointer to the root with minimum key
minimum = _findMinimumNode(minimum, this._size);
}
// decrement size of heap
this._size--;
// update minimum
this._minimum = minimum;
// return node
return node;
};
/**
* Removes a node from the heap given the reference to the node. The trees
* in the heap will be consolidated, if necessary. This operation may ...
n/a
function factory(type, config, load, typed) { return Fraction; }
n/a
function factory(type, config, load, typed) {
var Node = load(require('./Node'));
var setSafeProperty = load(require('./utils/customs')).setSafeProperty;
/**
* @constructor FunctionAssignmentNode
* @extends {Node}
* Function assignment
*
* @param {string} name Function name
* @param {string[] | Array.<{name: string, type: string}>} params
* Array with function parameter names, or an
* array with objects containing the name
* and type of the parameter
* @param {Node} expr The function expression
*/
function FunctionAssignmentNode(name, params, expr) {
if (!(this instanceof FunctionAssignmentNode)) {
throw new SyntaxError('Constructor must be called with the new operator');
}
// validate input
if (typeof name !== 'string') throw new TypeError('String expected for parameter "name"');
if (!Array.isArray(params)) throw new TypeError('Array containing strings or objects expected for parameter "params"');
if (!(expr && expr.isNode)) throw new TypeError('Node expected for parameter "expr"');
if (name in keywords) throw new Error('Illegal function name, "' + name + '" is a reserved keyword');
this.name = name;
this.params = params.map(function (param) {
return param && param.name || param;
});
this.types = params.map(function (param) {
return param && param.type || 'any'
});
this.expr = expr;
}
FunctionAssignmentNode.prototype = new Node();
FunctionAssignmentNode.prototype.type = 'FunctionAssignmentNode';
FunctionAssignmentNode.prototype.isFunctionAssignmentNode = true;
/**
* Compile the node to javascript code
* @param {Object} defs Object which can be used to define functions
* or constants globally available for the compiled
* expression
* @param {Object} args Object with local function arguments, the key is
* the name of the argument, and the value is `true`.
* The object may not be mutated, but must be
* extended instead.
* @return {string} js
* @private
*/
FunctionAssignmentNode.prototype._compile = function (defs, args) {
defs.typed = typed;
defs.setSafeProperty = setSafeProperty;
// we extend the original args and add the args to the child object
var childArgs = Object.create(args);
this.params.forEach(function (variable) {
childArgs[variable] = true;
});
// compile the function expression with the child args
var jsExpr = this.expr._compile(defs, childArgs);
return 'setSafeProperty(scope, "' + this.name + '", ' +
' (function () {' +
' var fn = typed("' + this.name + '", {' +
' "' + this.types.join(',') + '": function (' + this.params.join(',') + ') {' +
' return ' + jsExpr + '' +
' }' +
' });' +
' fn.syntax = "' + this.name + '(' + this.params.join(', ') + ')";' +
' return fn;' +
' })())';
};
/**
* Execute a callback for each of the child nodes of this node
* @param {function(child: Node, path: string, parent: Node)} callback
*/
FunctionAssignmentNode.prototype.forEach = function (callback) {
callback(this.expr, 'expr', this);
};
/**
* Create a new FunctionAssignmentNode having it's childs be the results of calling
* the provided callback function for each of the childs of the original node.
* @param {function(child: Node, path: string, parent: Node): Node} callback
* @returns {FunctionAssignmentNode} Returns a transformed copy of the node
*/
FunctionAssignmentNode.prototype.map = function (callback) {
var expr = this._ifNode(callback(this.expr, 'expr', this));
return new FunctionAssignmentNode(this.name, this.params.slice(0), expr);
};
/**
* Create a clone of this node, a shallow copy
* @return {FunctionAssignm ...
n/a
function factory(type, config, load, typed, math) {
var Node = load(require('./Node'));
var SymbolNode = load(require('./SymbolNode'));
var validateSafeMethod = load(require('./utils/customs')).validateSafeMethod;
/**
* @constructor FunctionNode
* @extends {./Node}
* invoke a list with arguments on a node
* @param {./Node | string} fn Node resolving with a function on which to invoke
* the arguments, typically a SymboNode or AccessorNode
* @param {./Node[]} args
*/
function FunctionNode(fn, args) {
if (!(this instanceof FunctionNode)) {
throw new SyntaxError('Constructor must be called with the new operator');
}
if (typeof fn === 'string') {
fn = new SymbolNode(fn);
}
// validate input
if (!fn || !fn.isNode) throw new TypeError('Node expected as parameter "fn"');
if (!Array.isArray(args)
|| !args.every(function (arg) {return arg && arg.isNode;})) {
throw new TypeError('Array containing Nodes expected for parameter "args"');
}
this.fn = fn;
this.args = args || [];
// readonly property name
Object.defineProperty(this, 'name', {
get: function () {
return this.fn.name || '';
}.bind(this),
set: function () {
throw new Error('Cannot assign a new name, name is read-only');
}
});
// TODO: deprecated since v3, remove some day
var deprecated = function () {
throw new Error('Property `FunctionNode.object` is deprecated, use `FunctionNode.fn` instead');
};
Object.defineProperty(this, 'object', { get: deprecated, set: deprecated });
}
FunctionNode.prototype = new Node();
FunctionNode.prototype.type = 'FunctionNode';
FunctionNode.prototype.isFunctionNode = true;
/**
* Compile the node to javascript code
* @param {Object} defs Object which can be used to define functions
* or constants globally available for the compiled
* expression
* @param {Object} args Object with local function arguments, the key is
* the name of the argument, and the value is `true`.
* The object may not be mutated, but must be
* extended instead.
* @return {string} js
* @private
*/
FunctionNode.prototype._compile = function (defs, args) {
// compile fn and arguments
var jsFn = this.fn._compile(defs, args);
var jsArgs = this.args.map(function (arg) {
return arg._compile(defs, args);
});
var jsScope = this._compileScope(defs, args);
var argsName;
if (this.fn.isSymbolNode) {
// we can statically determine whether the function has an rawArgs property
var name = this.fn.name;
var fn = defs.math[name];
var isRaw = (typeof fn === 'function') && (fn.rawArgs == true);
if (isRaw) {
// pass unevaluated parameters (nodes) to the function
argsName = this._getUniqueArgumentsName(defs);
defs[argsName] = this.args;
return jsFn + '(' + argsName + ', math, ' + jsScope + ')';
}
else {
// "regular" evaluation
return jsFn + '(' + jsArgs.join(', ') + ')';
}
}
else if (this.fn.isAccessorNode && this.fn.index.isObjectProperty()) {
// execute the function with the right context: the object of the AccessorNode
argsName = this._getUniqueArgumentsName(defs);
defs[argsName] = this.args;
defs.validateSafeMethod = validateSafeMethod
var jsObject = this.fn.object._compile(defs, args);
var prop = this.fn.index.getObjectProperty();
return '(function () {' +
'var object = ' + jsObject + ';' +
'validateSafeMethod(object, "' + prop + '");' +
'return (object["' + prop + '"] && object["' + prop + '"].rawArgs) ' +
' ? object["' + prop + '"](' + argsName + ', math, ' + jsScope + ')' +
' : object["' + prop + '"](' + jsArgs.join(', ') + ')' +
'})()';
}
else { // this.fn.isAcce ...
n/a
function factory(type, config, load, typed) {
var parser = load(require('./function/parser'))();
/**
* Documentation object
* @param {Object} doc Object containing properties:
* {string} name
* {string} category
* {string} description
* {string[]} syntax
* {string[]} examples
* {string[]} seealso
* @constructor
*/
function Help(doc) {
if (!(this instanceof Help)) {
throw new SyntaxError('Constructor must be called with the new operator');
}
if (!doc) throw new Error('Argument "doc" missing');
this.doc = doc;
}
/**
* Attach type information
*/
Help.prototype.type = 'Help';
Help.prototype.isHelp = true;
/**
* Generate a string representation of the Help object
* @return {string} Returns a string
* @private
*/
Help.prototype.toString = function () {
var doc = this.doc || {};
var desc = '\n';
if (doc.name) {
desc += 'Name: ' + doc.name + '\n\n';
}
if (doc.category) {
desc += 'Category: ' + doc.category + '\n\n';
}
if (doc.description) {
desc += 'Description:\n ' + doc.description + '\n\n';
}
if (doc.syntax) {
desc += 'Syntax:\n ' + doc.syntax.join('\n ') + '\n\n';
}
if (doc.examples) {
desc += 'Examples:\n';
for (var i = 0; i < doc.examples.length; i++) {
var expr = doc.examples[i];
desc += ' ' + expr + '\n';
var res;
try {
res = parser.eval(expr);
}
catch (e) {
res = e;
}
if (res && !res.isHelp) {
desc += ' ' + string.format(res, {precision: 14}) + '\n';
}
}
desc += '\n';
}
if (doc.seealso) {
desc += 'See also: ' + doc.seealso.join(', ') + '\n';
}
return desc;
};
/**
* Export the help object to JSON
*/
Help.prototype.toJSON = function () {
var obj = object.clone(this.doc);
obj.mathjs = 'Help';
return obj;
};
/**
* Instantiate a Help object from a JSON object
* @param {Object} json
* @returns {Help} Returns a new Help object
*/
Help.fromJSON = function (json) {
var doc = {};
for (var prop in json) {
if (prop !== 'mathjs') { // ignore mathjs field
doc[prop] = json[prop];
}
}
return new Help(doc);
};
/**
* Returns a string representation of the Help object
*/
Help.prototype.valueOf = Help.prototype.toString;
return Help;
}
n/a
function factory(type, config, load) {
var DenseMatrix = load(require('./DenseMatrix'));
var smaller = load(require('../../function/relational/smaller'));
function ImmutableDenseMatrix(data, datatype) {
if (!(this instanceof ImmutableDenseMatrix))
throw new SyntaxError('Constructor must be called with the new operator');
if (datatype && !isString(datatype))
throw new Error('Invalid datatype: ' + datatype);
if ((data && data.isMatrix === true) || isArray(data)) {
// use DenseMatrix implementation
var matrix = new DenseMatrix(data, datatype);
// internal structures
this._data = matrix._data;
this._size = matrix._size;
this._datatype = matrix._datatype;
this._min = null;
this._max = null;
}
else if (data && isArray(data.data) && isArray(data.size)) {
// initialize fields from JSON representation
this._data = data.data;
this._size = data.size;
this._datatype = data.datatype;
this._min = typeof data.min !== 'undefined' ? data.min : null;
this._max = typeof data.max !== 'undefined' ? data.max : null;
}
else if (data) {
// unsupported type
throw new TypeError('Unsupported type of data (' + util.types.type(data) + ')');
}
else {
// nothing provided
this._data = [];
this._size = [0];
this._datatype = datatype;
this._min = null;
this._max = null;
}
}
ImmutableDenseMatrix.prototype = new DenseMatrix();
/**
* Attach type information
*/
ImmutableDenseMatrix.prototype.type = 'ImmutableDenseMatrix';
ImmutableDenseMatrix.prototype.isImmutableDenseMatrix = true;
/**
* Get a subset of the matrix, or replace a subset of the matrix.
*
* Usage:
* var subset = matrix.subset(index) // retrieve subset
* var value = matrix.subset(index, replacement) // replace subset
*
* @param {Index} index
* @param {Array | ImmutableDenseMatrix | *} [replacement]
* @param {*} [defaultValue=0] Default value, filled in on new entries when
* the matrix is resized. If not provided,
* new matrix elements will be filled with zeros.
*/
ImmutableDenseMatrix.prototype.subset = function (index) {
switch (arguments.length) {
case 1:
// use base implementation
var m = DenseMatrix.prototype.subset.call(this, index);
// check result is a matrix
if (m.isMatrix) {
// return immutable matrix
return new ImmutableDenseMatrix({
data: m._data,
size: m._size,
datatype: m._datatype
});
}
return m;
// intentional fall through
case 2:
case 3:
throw new Error('Cannot invoke set subset on an Immutable Matrix instance');
default:
throw new SyntaxError('Wrong number of arguments');
}
};
/**
* Replace a single element in the matrix.
* @param {Number[]} index Zero-based index
* @param {*} value
* @param {*} [defaultValue] Default value, filled in on new entries when
* the matrix is resized. If not provided,
* new matrix elements will be left undefined.
* @return {ImmutableDenseMatrix} self
*/
ImmutableDenseMatrix.prototype.set = function () {
throw new Error('Cannot invoke set on an Immutable Matrix instance');
};
/**
* Resize the matrix to the given size. Returns a copy of the matrix when
* `copy=true`, otherwise return the matrix itself (resize in place).
*
* @param {Number[]} size The new size the matrix should have.
* @param {*} [defaultValue=0] Default value, filled in on new entries.
* If not provided, the matrix elements will
* be filled with zeros.
* @param {boolean} [copy] Return a resized copy of the matrix
*
* @return {Matrix} ...
n/a
function factory(type, config, load, typed) {
var Node = load(require('./Node'));
var RangeNode = load(require('./RangeNode'));
var SymbolNode = load(require('./SymbolNode'));
var Range = load(require('../../type/matrix/Range'));
var isArray = Array.isArray;
/**
* @constructor IndexNode
* @extends Node
*
* Describes a subset of a matrix or an object property.
* Cannot be used on its own, needs to be used within an AccessorNode or
* AssignmentNode.
*
* @param {Node[]} dimensions
* @param {boolean} [dotNotation=false] Optional property describing whether
* this index was written using dot
* notation like `a.b`, or using bracket
* notation like `a["b"]` (default).
* Used to stringify an IndexNode.
*/
function IndexNode(dimensions, dotNotation) {
if (!(this instanceof IndexNode)) {
throw new SyntaxError('Constructor must be called with the new operator');
}
this.dimensions = dimensions;
this.dotNotation = dotNotation || false;
// validate input
if (!isArray(dimensions)
|| !dimensions.every(function (range) {return range && range.isNode;})) {
throw new TypeError('Array containing Nodes expected for parameter "dimensions"');
}
if (this.dotNotation && !this.isObjectProperty()) {
throw new Error('dotNotation only applicable for object properties');
}
// TODO: deprecated since v3, remove some day
var deprecated = function () {
throw new Error('Property `IndexNode.object` is deprecated, use `IndexNode.fn` instead');
};
Object.defineProperty(this, 'object', { get: deprecated, set: deprecated });
}
IndexNode.prototype = new Node();
IndexNode.prototype.type = 'IndexNode';
IndexNode.prototype.isIndexNode = true;
/**
* Compile all range nodes
*
* When some of the dimensions has `end` defined, the IndexNode requires
* a variable `size` to be defined in the current closure, and must contain
* the size of the matrix that's being handled. To check whether the `size`
* variable is needed, call IndexNode.needsSize().
*
* @param {Object} defs Object which can be used to define functions
* or constants globally available for the
* compiled expression
* @param {Object} args Object with local function arguments, the key is
* the name of the argument, and the value is `true`.
* The object may not be mutated, but must be
* extended instead.
* @return {string} code
*/
IndexNode.prototype._compile = function (defs, args) {
// args can be mutated by IndexNode, when dimensions use `end`
var childArgs = Object.create(args);
// helper function to create a Range from start, step and end
defs.range = function (start, end, step) {
return new Range(
(start && start.isBigNumber === true) ? start.toNumber() : start,
(end && end.isBigNumber === true) ? end.toNumber() : end,
(step && step.isBigNumber === true) ? step.toNumber() : step
);
};
// TODO: implement support for bignumber (currently bignumbers are silently
// reduced to numbers when changing the value to zero-based)
// TODO: Optimization: when the range values are ConstantNodes,
// we can beforehand resolve the zero-based value
// optimization for a simple object property
var dimensions = this.dimensions.map(function (range, i) {
if (range && range.isRangeNode) {
if (range.needsEnd()) {
childArgs.end = true;
// resolve end and create range
return '(function () {' +
'var end = size[' + i + ']; ' +
'return range(' +
range.start._compile(defs, childArgs) + ', ' +
range. ...
n/a
function factory(type, config, load, typed) {
/**
* @constructor Matrix
*
* A Matrix is a wrapper around an Array. A matrix can hold a multi dimensional
* array. A matrix can be constructed as:
* var matrix = math.matrix(data)
*
* Matrix contains the functions to resize, get and set values, get the size,
* clone the matrix and to convert the matrix to a vector, array, or scalar.
* Furthermore, one can iterate over the matrix using map and forEach.
* The internal Array of the Matrix can be accessed using the function valueOf.
*
* Example usage:
* var matrix = math.matrix([[1, 2], [3, 4]]);
* matix.size(); // [2, 2]
* matrix.resize([3, 2], 5);
* matrix.valueOf(); // [[1, 2], [3, 4], [5, 5]]
* matrix.subset([1,2]) // 3 (indexes are zero-based)
*
*/
function Matrix() {
if (!(this instanceof Matrix)) {
throw new SyntaxError('Constructor must be called with the new operator');
}
}
/**
* Attach type information
*/
Matrix.prototype.type = 'Matrix';
Matrix.prototype.isMatrix = true;
/**
* Get the Matrix storage constructor for the given format.
*
* @param {string} format The Matrix storage format.
*
* @return {Function} The Matrix storage constructor.
*/
Matrix.storage = function (format) {
// check storage format is a string
if (!isString(format)) {
throw new TypeError('format must be a string value');
}
// get storage format constructor
var constructor = Matrix._storage[format];
if (!constructor) {
throw new SyntaxError('Unsupported matrix storage format: ' + format);
}
// return storage constructor
return constructor;
};
// a map with all constructors for all storage types
Matrix._storage = {};
/**
* Get the storage format used by the matrix.
*
* Usage:
* var format = matrix.storage() // retrieve storage format
*
* @return {string} The storage format.
*/
Matrix.prototype.storage = function () {
// must be implemented by each of the Matrix implementations
throw new Error('Cannot invoke storage on a Matrix interface');
};
/**
* Get the datatype of the data stored in the matrix.
*
* Usage:
* var format = matrix.datatype() // retrieve matrix datatype
*
* @return {string} The datatype.
*/
Matrix.prototype.datatype = function () {
// must be implemented by each of the Matrix implementations
throw new Error('Cannot invoke datatype on a Matrix interface');
};
/**
* Create a new Matrix With the type of the current matrix instance
* @param {Array | Object} data
* @param {string} [datatype]
*/
Matrix.prototype.create = function (data, datatype) {
throw new Error('Cannot invoke create on a Matrix interface');
};
/**
* Get a subset of the matrix, or replace a subset of the matrix.
*
* Usage:
* var subset = matrix.subset(index) // retrieve subset
* var value = matrix.subset(index, replacement) // replace subset
*
* @param {Index} index
* @param {Array | Matrix | *} [replacement]
* @param {*} [defaultValue=0] Default value, filled in on new entries when
* the matrix is resized. If not provided,
* new matrix elements will be filled with zeros.
*/
Matrix.prototype.subset = function (index, replacement, defaultValue) {
// must be implemented by each of the Matrix implementations
throw new Error('Cannot invoke subset on a Matrix interface');
};
/**
* Get a single element from the matrix.
* @param {number[]} index Zero-based index
* @return {*} value
*/
Matrix.prototype.get = function (index) {
// must be implemented by each of the Matrix implementations
throw new Error('Cannot invoke get on a Matrix interface');
};
/**
* Replace a single element in the matrix.
* @param {num ...
n/a
function factory(type) {
/**
* Create an index. An Index can store ranges and sets for multiple dimensions.
* Matrix.get, Matrix.set, and math.subset accept an Index as input.
*
* Usage:
* var index = new Index(range1, range2, matrix1, array1, ...);
*
* Where each parameter can be any of:
* A number
* A string (containing a name of an object property)
* An instance of Range
* An Array with the Set values
* A Matrix with the Set values
*
* The parameters start, end, and step must be integer numbers.
*
* @class Index
* @Constructor Index
* @param {...*} ranges
*/
function Index(ranges) {
if (!(this instanceof Index)) {
throw new SyntaxError('Constructor must be called with the new operator');
}
this._dimensions = [];
this._isScalar = true;
for (var i = 0, ii = arguments.length; i < ii; i++) {
var arg = arguments[i];
if (arg && (arg.isRange === true)) {
this._dimensions.push(arg);
this._isScalar = false;
}
else if (arg && (Array.isArray(arg) || arg.isMatrix === true)) {
// create matrix
var m = _createImmutableMatrix(arg.valueOf());
this._dimensions.push(m);
// size
var size = m.size();
// scalar
if (size.length !== 1 || size[0] !== 1) {
this._isScalar = false;
}
}
else if (typeof arg === 'number') {
this._dimensions.push(_createImmutableMatrix([arg]));
}
else if (typeof arg === 'string') {
// object property (arguments.count should be 1)
this._dimensions.push(arg);
}
// TODO: implement support for wildcard '*'
else {
throw new TypeError('Dimension must be an Array, Matrix, number, string, or Range');
}
}
}
/**
* Attach type information
*/
Index.prototype.type = 'Index';
Index.prototype.isIndex = true;
function _createImmutableMatrix(arg) {
// loop array elements
for (var i = 0, l = arg.length; i < l; i++) {
if (typeof arg[i] !== 'number' || !isInteger(arg[i])) {
throw new TypeError('Index parameters must be positive integer numbers');
}
}
// create matrix
return new type.ImmutableDenseMatrix(arg);
}
/**
* Create a clone of the index
* @memberof Index
* @return {Index} clone
*/
Index.prototype.clone = function () {
var index = new Index();
index._dimensions = clone(this._dimensions);
index._isScalar = this._isScalar;
return index;
};
/**
* Create an index from an array with ranges/numbers
* @memberof Index
* @param {Array.<Array | number>} ranges
* @return {Index} index
* @private
*/
Index.create = function (ranges) {
var index = new Index();
Index.apply(index, ranges);
return index;
};
/**
* Retrieve the size of the index, the number of elements for each dimension.
* @memberof Index
* @returns {number[]} size
*/
Index.prototype.size = function () {
var size = [];
for (var i = 0, ii = this._dimensions.length; i < ii; i++) {
var d = this._dimensions[i];
size[i] = (typeof d === 'string') ? 1 : d.size()[0];
}
return size;
};
/**
* Get the maximum value for each of the indexes ranges.
* @memberof Index
* @returns {number[]} max
*/
Index.prototype.max = function () {
var values = [];
for (var i = 0, ii = this._dimensions.length; i < ii; i++) {
var range = this._dimensions[i];
values[i] = (typeof range === 'string') ? range : range.max();
}
return values;
};
/**
* Get the minimum value for each of the indexes ranges.
* @memberof Index
* @returns {number[]} min
*/
Index.prototype.min = function () {
var values = [];
for (var i = 0, ii = this._dimensions.length; i < ii; i++) {
var range = this._dimensions[i];
values[i] = (typeof range === 'string') ? range : range.min();
}
return values;
};
/**
* Loop over each of the ranges of the index
* ...
n/a
function factory(type, config, load, typed, math) {
/**
* Node
*/
function Node() {
if (!(this instanceof Node)) {
throw new SyntaxError('Constructor must be called with the new operator');
}
}
/**
* Evaluate the node
* @param {Object} [scope] Scope to read/write variables
* @return {*} Returns the result
*/
Node.prototype.eval = function(scope) {
return this.compile().eval(scope);
};
Node.prototype.type = 'Node';
Node.prototype.isNode = true;
Node.prototype.comment = '';
/**
* Compile the node to javascript code
* @return {{eval: function}} expr Returns an object with a function 'eval',
* which can be invoked as expr.eval([scope]),
* where scope is an optional object with
* variables.
*/
Node.prototype.compile = function () {
// TODO: calling compile(math) is deprecated since version 2.0.0. Remove this warning some day
if (arguments.length > 0) {
throw new Error('Calling compile(math) is deprecated. Call the function as compile() instead.');
}
// definitions globally available inside the closure of the compiled expressions
var defs = {
math: math.expression.mathWithTransform,
args: {}, // can be filled with names of FunctionAssignment arguments
_validateScope: _validateScope
};
// will be used to put local function arguments
var args = {};
var code = this._compile(defs, args);
var defsCode = Object.keys(defs).map(function (name) {
return ' var ' + name + ' = defs["' + name + '"];';
});
var factoryCode =
defsCode.join(' ') +
'return {' +
' "eval": function (scope) {' +
' if (scope) _validateScope(scope);' +
' scope = scope || {};' +
' return ' + code + ';' +
' }' +
'};';
var factory = new Function('defs', factoryCode);
return factory(defs);
};
/**
* Compile the node to javascript code
* @param {Object} defs Object which can be used to define functions
* and constants globally available inside the closure
* of the compiled expression
* @param {Object} args Object with local function arguments, the key is
* the name of the argument, and the value is `true`.
* The object may not be mutated, but must be
* extended instead.
* @return {string} js
* @private
*/
Node.prototype._compile = function (defs, args) {
// must be implemented by each of the Node implementations
throw new Error('Cannot compile a Node interface');
};
/**
* Execute a callback for each of the child nodes of this node
* @param {function(child: Node, path: string, parent: Node)} callback
*/
Node.prototype.forEach = function (callback) {
// must be implemented by each of the Node implementations
throw new Error('Cannot run forEach on a Node interface');
};
/**
* Create a new Node having it's childs be the results of calling
* the provided callback function for each of the childs of the original node.
* @param {function(child: Node, path: string, parent: Node): Node} callback
* @returns {OperatorNode} Returns a transformed copy of the node
*/
Node.prototype.map = function (callback) {
// must be implemented by each of the Node implementations
throw new Error('Cannot run map on a Node interface');
};
/**
* Validate whether an object is a Node, for use with map
* @param {Node} node
* @returns {Node} Returns the input if it's a node, else throws an Error
* @protected
*/
Node.prototype._ifNode = function (node) {
if (!(node && node.isNode)) {
throw new TypeError('Callback function must return a Node');
}
return node;
};
/**
* Recursively traverse all nodes in a node tree. Executes given callback for
* this node and each of its ...
n/a
function factory(type, config, load, typed) {
var Node = load(require('./Node'));
/**
* @constructor ObjectNode
* @extends {Node}
* Holds an object with keys/values
* @param {Object.<string, Node>} [properties] array with key/value pairs
*/
function ObjectNode(properties) {
if (!(this instanceof ObjectNode)) {
throw new SyntaxError('Constructor must be called with the new operator');
}
this.properties = properties || {};
// validate input
if (properties) {
if (!(typeof properties === 'object') || Object.keys(properties).some(function (key) {
return !properties[key] || !properties[key].isNode;
})) {
throw new TypeError('Object containing Nodes expected');
}
}
}
ObjectNode.prototype = new Node();
ObjectNode.prototype.type = 'ObjectNode';
ObjectNode.prototype.isObjectNode = true;
/**
* Compile the node to javascript code
* @param {Object} defs Object which can be used to define functions
* or constants globally available for the compiled
* expression
* @param {Object} args Object with local function arguments, the key is
* the name of the argument, and the value is `true`.
* The object may not be mutated, but must be
* extended instead.
* @return {string} code
* @private
*/
ObjectNode.prototype._compile = function (defs, args) {
var entries = [];
for (var key in this.properties) {
if (this.properties.hasOwnProperty(key)) {
entries.push('"' + key + '": ' + this.properties[key]._compile(defs, args));
}
}
return '{' + entries.join(', ') + '}';
};
/**
* Execute a callback for each of the child nodes of this node
* @param {function(child: Node, path: string, parent: Node)} callback
*/
ObjectNode.prototype.forEach = function (callback) {
for (var key in this.properties) {
if (this.properties.hasOwnProperty(key)) {
callback(this.properties[key], 'properties["' + key + '"]', this);
}
}
};
/**
* Create a new ObjectNode having it's childs be the results of calling
* the provided callback function for each of the childs of the original node.
* @param {function(child: Node, path: string, parent: Node): Node} callback
* @returns {ObjectNode} Returns a transformed copy of the node
*/
ObjectNode.prototype.map = function (callback) {
var properties = {};
for (var key in this.properties) {
if (this.properties.hasOwnProperty(key)) {
properties[key] = this._ifNode(callback(this.properties[key], 'properties["' + key + '"]', this));
}
}
return new ObjectNode(properties);
};
/**
* Create a clone of this node, a shallow copy
* @return {ObjectNode}
*/
ObjectNode.prototype.clone = function() {
var properties = {};
for (var key in this.properties) {
if (this.properties.hasOwnProperty(key)) {
properties[key] = this.properties[key];
}
}
return new ObjectNode(properties);
};
/**
* Get string representation
* @param {Object} options
* @return {string} str
* @override
*/
ObjectNode.prototype._toString = function(options) {
var entries = [];
for (var key in this.properties) {
if (this.properties.hasOwnProperty(key)) {
entries.push('"' + key + '": ' + this.properties[key].toString(options));
}
}
return '{' + entries.join(', ') + '}';
};
/**
* Get LaTeX representation
* @param {Object} options
* @return {string} str
*/
ObjectNode.prototype._toTex = function(options) {
var entries = [];
for (var key in this.properties) {
if (this.properties.hasOwnProperty(key)) {
entries.push("\\mathbf{" + key + ':} & ' + this.properties[key].toTex(options) + "\\\\");
}
}
return '\\left\\{\\begin{array}{ll}' + entries.join('\n') + '\\end{array}\\right\\}';
};
return ObjectNode;
}
n/a
function factory(type, config, load, typed, math) {
var Node = load(require('./Node'));
var ConstantNode = load(require('./ConstantNode'));
var SymbolNode = load(require('./SymbolNode'));
var FunctionNode = load(require('./FunctionNode'));
/**
* @constructor OperatorNode
* @extends {Node}
* An operator with two arguments, like 2+3
*
* @param {string} op Operator name, for example '+'
* @param {string} fn Function name, for example 'add'
* @param {Node[]} args Operator arguments
* @param {boolean} [implicit] Is this an implicit multiplication?
*/
function OperatorNode(op, fn, args, implicit) {
if (!(this instanceof OperatorNode)) {
throw new SyntaxError('Constructor must be called with the new operator');
}
//validate input
if (typeof op !== 'string') {
throw new TypeError('string expected for parameter "op"');
}
if (typeof fn !== 'string') {
throw new TypeError('string expected for parameter "fn"');
}
if (!Array.isArray(args)
|| !args.every(function (node) {return node && node.isNode;})) {
throw new TypeError('Array containing Nodes expected for parameter "args"');
}
this.implicit = (implicit === true);
this.op = op;
this.fn = fn;
this.args = args || [];
}
OperatorNode.prototype = new Node();
OperatorNode.prototype.type = 'OperatorNode';
OperatorNode.prototype.isOperatorNode = true;
/**
* Compile the node to javascript code
* @param {Object} defs Object which can be used to define functions
* or constants globally available for the compiled
* expression
* @param {Object} args Object with local function arguments, the key is
* the name of the argument, and the value is `true`.
* The object may not be mutated, but must be
* extended instead.
* @return {string} js
* @private
*/
OperatorNode.prototype._compile = function (defs, args) {
if (!defs.math[this.fn]) {
throw new Error('Function ' + this.fn + ' missing in provided namespace "math"');
}
var jsArgs = this.args.map(function (arg) {
return arg._compile(defs, args);
});
return 'math.' + this.fn + '(' + jsArgs.join(', ') + ')';
};
/**
* Execute a callback for each of the child nodes of this node
* @param {function(child: Node, path: string, parent: Node)} callback
*/
OperatorNode.prototype.forEach = function (callback) {
for (var i = 0; i < this.args.length; i++) {
callback(this.args[i], 'args[' + i + ']', this);
}
};
/**
* Create a new OperatorNode having it's childs be the results of calling
* the provided callback function for each of the childs of the original node.
* @param {function(child: Node, path: string, parent: Node): Node} callback
* @returns {OperatorNode} Returns a transformed copy of the node
*/
OperatorNode.prototype.map = function (callback) {
var args = [];
for (var i = 0; i < this.args.length; i++) {
args[i] = this._ifNode(callback(this.args[i], 'args[' + i + ']', this));
}
return new OperatorNode(this.op, this.fn, args);
};
/**
* Create a clone of this node, a shallow copy
* @return {OperatorNode}
*/
OperatorNode.prototype.clone = function () {
return new OperatorNode(this.op, this.fn, this.args.slice(0), this.implicit);
};
/**
* Calculate which parentheses are necessary. Gets an OperatorNode
* (which is the root of the tree) and an Array of Nodes
* (this.args) and returns an array where 'true' means that an argument
* has to be enclosed in parentheses whereas 'false' means the opposite.
*
* @param {OperatorNode} root
* @param {string} parenthesis
* @param {Node[]} args
* @param {boolean} latex
* @return {boolean[]}
* @private
*/
function calculateNecessaryParentheses(root, parenthesis, args, latex) {
//precedence of the root OperatorNode ...
n/a
function factory(type, config, load, typed) {
var Node = load(require('./Node'));
/**
* @constructor ParenthesisNode
* @extends {Node}
* A parenthesis node describes manual parenthesis from the user input
* @param {Node} content
* @extends {Node}
*/
function ParenthesisNode(content) {
if (!(this instanceof ParenthesisNode)) {
throw new SyntaxError('Constructor must be called with the new operator');
}
// validate input
if (!(content && content.isNode)) {
throw new TypeError('Node expected for parameter "content"');
}
this.content = content;
}
ParenthesisNode.prototype = new Node();
ParenthesisNode.prototype.type = 'ParenthesisNode';
ParenthesisNode.prototype.isParenthesisNode = true;
/**
* Compile the node to javascript code
* @param {Object} defs Object which can be used to define functions
* or constants globally available for the compiled
* expression
* @param {Object} args Object with local function arguments, the key is
* the name of the argument, and the value is `true`.
* The object may not be mutated, but must be
* extended instead.
* @return {string} js
* @private
*/
ParenthesisNode.prototype._compile = function (defs, args) {
return this.content._compile(defs, args);
};
/**
* Get the content of the current Node.
* @return {Node} content
* @override
**/
ParenthesisNode.prototype.getContent = function () {
return this.content.getContent();
};
/**
* Execute a callback for each of the child nodes of this node
* @param {function(child: Node, path: string, parent: Node)} callback
*/
ParenthesisNode.prototype.forEach = function (callback) {
callback(this.content, 'content', this);
};
/**
* Create a new ParenthesisNode having it's childs be the results of calling
* the provided callback function for each of the childs of the original node.
* @param {function(child: Node, path: string, parent: Node) : Node} callback
* @returns {ParenthesisNode} Returns a clone of the node
*/
ParenthesisNode.prototype.map = function (callback) {
var content = callback(this.content, 'content', this);
return new ParenthesisNode(content);
};
/**
* Create a clone of this node, a shallow copy
* @return {ParenthesisNode}
*/
ParenthesisNode.prototype.clone = function() {
return new ParenthesisNode(this.content);
};
/**
* Get string representation
* @param {Object} options
* @return {string} str
* @override
*/
ParenthesisNode.prototype._toString = function(options) {
if ((!options) || (options && !options.parenthesis) || (options && options.parenthesis === 'keep')) {
return '(' + this.content.toString(options) + ')';
}
return this.content.toString(options);
};
/**
* Get LaTeX representation
* @param {Object} options
* @return {string} str
* @override
*/
ParenthesisNode.prototype._toTex = function(options) {
if ((!options) || (options && !options.parenthesis) || (options && options.parenthesis === 'keep')) {
return '\\left(' + this.content.toTex(options) + '\\right)';
}
return this.content.toTex(options);
};
return ParenthesisNode;
}
n/a
function factory(type, config, load, typed, math) {
var _parse = load(require('./parse'));
var customs = load(require('./node/utils/customs'));
/**
* @constructor Parser
* Parser contains methods to evaluate or parse expressions, and has a number
* of convenience methods to get, set, and remove variables from memory. Parser
* keeps a scope containing variables in memory, which is used for all
* evaluations.
*
* Methods:
* var result = parser.eval(expr); // evaluate an expression
* var value = parser.get(name); // retrieve a variable from the parser
* var values = parser.getAll(); // retrieve all defined variables
* parser.set(name, value); // set a variable in the parser
* parser.remove(name); // clear a variable from the
* // parsers scope
* parser.clear(); // clear the parsers scope
*
* Example usage:
* var parser = new Parser();
* // Note: there is a convenience method which can be used instead:
* // var parser = new math.parser();
*
* // evaluate expressions
* parser.eval('sqrt(3^2 + 4^2)'); // 5
* parser.eval('sqrt(-4)'); // 2i
* parser.eval('2 inch in cm'); // 5.08 cm
* parser.eval('cos(45 deg)'); // 0.7071067811865476
*
* // define variables and functions
* parser.eval('x = 7 / 2'); // 3.5
* parser.eval('x + 3'); // 6.5
* parser.eval('function f(x, y) = x^y'); // f(x, y)
* parser.eval('f(2, 3)'); // 8
*
* // get and set variables and functions
* var x = parser.get('x'); // 7
* var f = parser.get('f'); // function
* var g = f(3, 2); // 9
* parser.set('h', 500);
* var i = parser.eval('h / 2'); // 250
* parser.set('hello', function (name) {
* return 'hello, ' + name + '!';
* });
* parser.eval('hello("user")'); // "hello, user!"
*
* // clear defined functions and variables
* parser.clear();
*
*/
function Parser() {
if (!(this instanceof Parser)) {
throw new SyntaxError(
'Constructor must be called with the new operator');
}
this.scope = {};
}
/**
* Attach type information
*/
Parser.prototype.type = 'Parser';
Parser.prototype.isParser = true;
/**
* Parse an expression and return the parsed function node.
* The node tree can be compiled via `code = node.compile(math)`,
* and the compiled code can be executed as `code.eval([scope])`
* @param {string} expr
* @return {Node} node
* @throws {Error}
*/
Parser.prototype.parse = function (expr) {
throw new Error('Parser.parse is deprecated. Use math.parse instead.');
};
/**
* Parse and compile an expression, return the compiled javascript code.
* The node can be evaluated via code.eval([scope])
* @param {string} expr
* @return {{eval: function}} code
* @throws {Error}
*/
Parser.prototype.compile = function (expr) {
throw new Error('Parser.compile is deprecated. Use math.compile instead.');
};
/**
* Parse and evaluate the given expression
* @param {string} expr A string containing an expression, for example "2+3"
* @return {*} result The result, or undefined when the expression was empty
* @throws {Error}
*/
Parser.prototype.eval = function (expr) {
// TODO: validate arguments
return _parse(expr)
.compile()
.eval(this.scope);
};
/**
* Get a variable (a function or variable) by name from the parsers scope.
* Returns undefined when not found
* @param {string} name
* @return {* | undefined} value
*/
Parser.prototype.get = function (name) {
// TODO: validate arguments
return name in this.scope
? customs.getSafeProperty(this.scope, name)
: undefined;
};
/**
* Get a map with all de ...
n/a
function factory(type, config, load, typed) {
/**
* Create a range. A range has a start, step, and end, and contains functions
* to iterate over the range.
*
* A range can be constructed as:
* var range = new Range(start, end);
* var range = new Range(start, end, step);
*
* To get the result of the range:
* range.forEach(function (x) {
* console.log(x);
* });
* range.map(function (x) {
* return math.sin(x);
* });
* range.toArray();
*
* Example usage:
* var c = new Range(2, 6); // 2:1:5
* c.toArray(); // [2, 3, 4, 5]
* var d = new Range(2, -3, -1); // 2:-1:-2
* d.toArray(); // [2, 1, 0, -1, -2]
*
* @class Range
* @constructor Range
* @param {number} start included lower bound
* @param {number} end excluded upper bound
* @param {number} [step] step size, default value is 1
*/
function Range(start, end, step) {
if (!(this instanceof Range)) {
throw new SyntaxError('Constructor must be called with the new operator');
}
if (start != null) {
if (start.isBigNumber === true)
start = start.toNumber();
else if (typeof start !== 'number')
throw new TypeError('Parameter start must be a number');
}
if (end != null) {
if (end.isBigNumber === true)
end = end.toNumber();
else if (typeof end !== 'number')
throw new TypeError('Parameter end must be a number');
}
if (step != null) {
if (step.isBigNumber === true)
step = step.toNumber();
else if (typeof step !== 'number')
throw new TypeError('Parameter step must be a number');
}
this.start = (start != null) ? parseFloat(start) : 0;
this.end = (end != null) ? parseFloat(end) : 0;
this.step = (step != null) ? parseFloat(step) : 1;
}
/**
* Attach type information
*/
Range.prototype.type = 'Range';
Range.prototype.isRange = true;
/**
* Parse a string into a range,
* The string contains the start, optional step, and end, separated by a colon.
* If the string does not contain a valid range, null is returned.
* For example str='0:2:11'.
* @memberof Range
* @param {string} str
* @return {Range | null} range
*/
Range.parse = function (str) {
if (typeof str !== 'string') {
return null;
}
var args = str.split(':');
var nums = args.map(function (arg) {
return parseFloat(arg);
});
var invalid = nums.some(function (num) {
return isNaN(num);
});
if (invalid) {
return null;
}
switch (nums.length) {
case 2:
return new Range(nums[0], nums[1]);
case 3:
return new Range(nums[0], nums[2], nums[1]);
default:
return null;
}
};
/**
* Create a clone of the range
* @return {Range} clone
*/
Range.prototype.clone = function () {
return new Range(this.start, this.end, this.step);
};
/**
* Retrieve the size of the range.
* Returns an array containing one number, the number of elements in the range.
* @memberof Range
* @returns {number[]} size
*/
Range.prototype.size = function () {
var len = 0,
start = this.start,
step = this.step,
end = this.end,
diff = end - start;
if (number.sign(step) == number.sign(diff)) {
len = Math.ceil((diff) / step);
}
else if (diff == 0) {
len = 0;
}
if (isNaN(len)) {
len = 0;
}
return [len];
};
/**
* Calculate the minimum value in the range
* @memberof Range
* @return {number | undefined} min
*/
Range.prototype.min = function () {
var size = this.size()[0];
if (size > 0) {
if (this.step > 0) {
// positive step
return this.start;
}
else {
// negative step
return this.start + (size - 1) * this.step;
}
}
else {
return undefined;
}
};
/**
* Calculate the maximum value ...
n/a
function factory(type, config, load, typed) {
var Node = load(require('./Node'));
/**
* @constructor RangeNode
* @extends {Node}
* create a range
* @param {Node} start included lower-bound
* @param {Node} end included upper-bound
* @param {Node} [step] optional step
*/
function RangeNode(start, end, step) {
if (!(this instanceof RangeNode)) {
throw new SyntaxError('Constructor must be called with the new operator');
}
// validate inputs
if (!(start && start.isNode)) throw new TypeError('Node expected');
if (!(end && end.isNode)) throw new TypeError('Node expected');
if (step && !(step && step.isNode)) throw new TypeError('Node expected');
if (arguments.length > 3) throw new Error('Too many arguments');
this.start = start; // included lower-bound
this.end = end; // included upper-bound
this.step = step || null; // optional step
}
RangeNode.prototype = new Node();
RangeNode.prototype.type = 'RangeNode';
RangeNode.prototype.isRangeNode = true;
/**
* Check whether the RangeNode needs the `end` symbol to be defined.
* This end is the size of the Matrix in current dimension.
* @return {boolean}
*/
RangeNode.prototype.needsEnd = function () {
// find all `end` symbols in this RangeNode
var endSymbols = this.filter(function (node) {
return (node && node.isSymbolNode) && (node.name == 'end');
});
return endSymbols.length > 0;
};
/**
* Compile the node to javascript code
*
* When the range has a symbol `end` defined, the RangeNode requires
* a variable `end` to be defined in the current closure, which must contain
* the length of the of the matrix that's being handled in the range's
* dimension. To check whether the `end` variable is needed, call
* RangeNode.needsEnd().
*
* @param {Object} defs Object which can be used to define functions
* or constants globally available for the compiled
* expression
* @param {Object} args Object with local function arguments, the key is
* the name of the argument, and the value is `true`.
* The object may not be mutated, but must be
* extended instead.
* @return {string} js
* @private
*/
RangeNode.prototype._compile = function (defs, args) {
return 'math.range(' +
this.start._compile(defs, args) + ', ' +
this.end._compile(defs, args) +
(this.step ? (', ' + this.step._compile(defs, args)) : '') +
')';
};
/**
* Execute a callback for each of the child nodes of this node
* @param {function(child: Node, path: string, parent: Node)} callback
*/
RangeNode.prototype.forEach = function (callback) {
callback(this.start, 'start', this);
callback(this.end, 'end', this);
if (this.step) {
callback(this.step, 'step', this);
}
};
/**
* Create a new RangeNode having it's childs be the results of calling
* the provided callback function for each of the childs of the original node.
* @param {function(child: Node, path: string, parent: Node): Node} callback
* @returns {RangeNode} Returns a transformed copy of the node
*/
RangeNode.prototype.map = function (callback) {
return new RangeNode(
this._ifNode(callback(this.start, 'start', this)),
this._ifNode(callback(this.end, 'end', this)),
this.step && this._ifNode(callback(this.step, 'step', this))
);
};
/**
* Create a clone of this node, a shallow copy
* @return {RangeNode}
*/
RangeNode.prototype.clone = function () {
return new RangeNode(this.start, this.end, this.step && this.step);
};
/**
* Calculate the necessary parentheses
* @param {Node} node
* @param {string} parenthesis
* @return {Object} parentheses
* @private
*/
function calculateNecessaryParentheses(node, parenthesis) {
var precedence = operators.getPrecedence(node, parenthesis);
var paren ...
n/a
function factory(type, config, load, typed) {
/**
* A ResultSet contains a list or results
* @class ResultSet
* @param {Array} entries
* @constructor ResultSet
*/
function ResultSet(entries) {
if (!(this instanceof ResultSet)) {
throw new SyntaxError('Constructor must be called with the new operator');
}
this.entries = entries || [];
}
/**
* Attach type information
*/
ResultSet.prototype.type = 'ResultSet';
ResultSet.prototype.isResultSet = true;
/**
* Returns the array with results hold by this ResultSet
* @memberof ResultSet
* @returns {Array} entries
*/
ResultSet.prototype.valueOf = function () {
return this.entries;
};
/**
* Returns the stringified results of the ResultSet
* @memberof ResultSet
* @returns {string} string
*/
ResultSet.prototype.toString = function () {
return '[' + this.entries.join(', ') + ']';
};
/**
* Get a JSON representation of the ResultSet
* @memberof ResultSet
* @returns {Object} Returns a JSON object structured as:
* `{"mathjs": "ResultSet", "entries": [...]}`
*/
ResultSet.prototype.toJSON = function () {
return {
mathjs: 'ResultSet',
entries: this.entries
};
};
/**
* Instantiate a ResultSet from a JSON object
* @memberof ResultSet
* @param {Object} json A JSON object structured as:
* `{"mathjs": "ResultSet", "entries": [...]}`
* @return {ResultSet}
*/
ResultSet.fromJSON = function (json) {
return new ResultSet(json.entries);
};
return ResultSet;
}
n/a
function factory(type, config, load) {
var add = load(require('../../function/arithmetic/add'));
var equalScalar = load(require('../../function/relational/equalScalar'));
/**
* An ordered Sparse Accumulator is a representation for a sparse vector that includes a dense array
* of the vector elements and an ordered list of non-zero elements.
*/
function Spa() {
if (!(this instanceof Spa))
throw new SyntaxError('Constructor must be called with the new operator');
// allocate vector, TODO use typed arrays
this._values = [];
this._heap = new type.FibonacciHeap();
}
/**
* Attach type information
*/
Spa.prototype.type = 'Spa';
Spa.prototype.isSpa = true;
/**
* Set the value for index i.
*
* @param {number} i The index
* @param {number | BigNumber | Complex} The value at index i
*/
Spa.prototype.set = function (i, v) {
// check we have a value @ i
if (!this._values[i]) {
// insert in heap
var node = this._heap.insert(i, v);
// set the value @ i
this._values[i] = node;
}
else {
// update the value @ i
this._values[i].value = v;
}
};
Spa.prototype.get = function (i) {
var node = this._values[i];
if (node)
return node.value;
return 0;
};
Spa.prototype.accumulate = function (i, v) {
// node @ i
var node = this._values[i];
if (!node) {
// insert in heap
node = this._heap.insert(i, v);
// initialize value
this._values[i] = node;
}
else {
// accumulate value
node.value = add(node.value, v);
}
};
Spa.prototype.forEach = function (from, to, callback) {
// references
var heap = this._heap;
var values = this._values;
// nodes
var nodes = [];
// node with minimum key, save it
var node = heap.extractMinimum();
if (node)
nodes.push(node);
// extract nodes from heap (ordered)
while (node && node.key <= to) {
// check it is in range
if (node.key >= from) {
// check value is not zero
if (!equalScalar(node.value, 0)) {
// invoke callback
callback(node.key, node.value, this);
}
}
// extract next node, save it
node = heap.extractMinimum();
if (node)
nodes.push(node);
}
// reinsert all nodes in heap
for (var i = 0; i < nodes.length; i++) {
// current node
var n = nodes[i];
// insert node in heap
node = heap.insert(n.key, n.value);
// update values
values[node.key] = node;
}
};
Spa.prototype.swap = function (i, j) {
// node @ i and j
var nodei = this._values[i];
var nodej = this._values[j];
// check we need to insert indeces
if (!nodei && nodej) {
// insert in heap
nodei = this._heap.insert(i, nodej.value);
// remove from heap
this._heap.remove(nodej);
// set values
this._values[i] = nodei;
this._values[j] = undefined;
}
else if (nodei && !nodej) {
// insert in heap
nodej = this._heap.insert(j, nodei.value);
// remove from heap
this._heap.remove(nodei);
// set values
this._values[j] = nodej;
this._values[i] = undefined;
}
else if (nodei && nodej) {
// swap values
var v = nodei.value;
nodei.value = nodej.value;
nodej.value = v;
}
};
return Spa;
}
n/a
function factory(type, config, load, typed) {
var Matrix = load(require('./Matrix')); // force loading Matrix (do not use via type.Matrix)
var equalScalar = load(require('../../function/relational/equalScalar'));
/**
* Sparse Matrix implementation. This type implements a Compressed Column Storage format
* for sparse matrices.
* @class SparseMatrix
*/
function SparseMatrix(data, datatype) {
if (!(this instanceof SparseMatrix))
throw new SyntaxError('Constructor must be called with the new operator');
if (datatype && !isString(datatype))
throw new Error('Invalid datatype: ' + datatype);
if (data && data.isMatrix === true) {
// create from matrix
_createFromMatrix(this, data, datatype);
}
else if (data && isArray(data.index) && isArray(data.ptr) && isArray(data.size)) {
// initialize fields
this._values = data.values;
this._index = data.index;
this._ptr = data.ptr;
this._size = data.size;
this._datatype = datatype || data.datatype;
}
else if (isArray(data)) {
// create from array
_createFromArray(this, data, datatype);
}
else if (data) {
// unsupported type
throw new TypeError('Unsupported type of data (' + util.types.type(data) + ')');
}
else {
// nothing provided
this._values = [];
this._index = [];
this._ptr = [0];
this._size = [0, 0];
this._datatype = datatype;
}
}
var _createFromMatrix = function (matrix, source, datatype) {
// check matrix type
if (source.type === 'SparseMatrix') {
// clone arrays
matrix._values = source._values ? object.clone(source._values) : undefined;
matrix._index = object.clone(source._index);
matrix._ptr = object.clone(source._ptr);
matrix._size = object.clone(source._size);
matrix._datatype = datatype || source._datatype;
}
else {
// build from matrix data
_createFromArray(matrix, source.valueOf(), datatype || source._datatype);
}
};
var _createFromArray = function (matrix, data, datatype) {
// initialize fields
matrix._values = [];
matrix._index = [];
matrix._ptr = [];
matrix._datatype = datatype;
// discover rows & columns, do not use math.size() to avoid looping array twice
var rows = data.length;
var columns = 0;
// equal signature to use
var eq = equalScalar;
// zero value
var zero = 0;
if (isString(datatype)) {
// find signature that matches (datatype, datatype)
eq = typed.find(equalScalar, [datatype, datatype]) || equalScalar;
// convert 0 to the same datatype
zero = typed.convert(0, datatype);
}
// check we have rows (empty array)
if (rows > 0) {
// column index
var j = 0;
do {
// store pointer to values index
matrix._ptr.push(matrix._index.length);
// loop rows
for (var i = 0; i < rows; i++) {
// current row
var row = data[i];
// check row is an array
if (isArray(row)) {
// update columns if needed (only on first column)
if (j === 0 && columns < row.length)
columns = row.length;
// check row has column
if (j < row.length) {
// value
var v = row[j];
// check value != 0
if (!eq(v, zero)) {
// store value
matrix._values.push(v);
// index
matrix._index.push(i);
}
}
}
else {
// update columns if needed (only on first column)
if (j === 0 && columns < 1)
columns = 1;
// check value != 0 (row is a scalar)
if (!eq(row, zero)) {
// store value
matrix._values.push(row);
// index
matrix._index.push(i);
}
}
}
// increment index
j++;
}
whil ...
n/a
function factory(type, config, load, typed, math) {
var Node = load(require('./Node'));
var Unit = load(require('../../type/unit/Unit'));
var getSafeProperty = load(require('./utils/customs')).getSafeProperty;
/**
* @constructor SymbolNode
* @extends {Node}
* A symbol node can hold and resolve a symbol
* @param {string} name
* @extends {Node}
*/
function SymbolNode(name) {
if (!(this instanceof SymbolNode)) {
throw new SyntaxError('Constructor must be called with the new operator');
}
// validate input
if (typeof name !== 'string') throw new TypeError('String expected for parameter "name"');
this.name = name;
}
SymbolNode.prototype = new Node();
SymbolNode.prototype.type = 'SymbolNode';
SymbolNode.prototype.isSymbolNode = true;
/**
* Compile the node to javascript code
* @param {Object} defs Object which can be used to define functions
* or constants globally available for the compiled
* expression
* @param {Object} args Object with local function arguments, the key is
* the name of the argument, and the value is `true`.
* The object may not be mutated, but must be
* extended instead.
* @return {string} js
* @private
*/
SymbolNode.prototype._compile = function (defs, args) {
// add a function to the definitions
defs['undef'] = undef;
defs['Unit'] = Unit;
defs.getSafeProperty = getSafeProperty;
if (args[this.name]) {
// this is a FunctionAssignment argument
// (like an x when inside the expression of a function assignment `f(x) = ...`)
return this.name;
}
else if (this.name in defs.math) {
return '("' + this.name + '" in scope ? getSafeProperty(scope, "' + this.name + '") : getSafeProperty(math, "' + this.name
+ '"))';
}
else {
return '(' +
'"' + this.name + '" in scope ? getSafeProperty(scope, "' + this.name + '") : ' +
(Unit.isValuelessUnit(this.name) ?
'new Unit(null, "' + this.name + '")' :
'undef("' + this.name + '")') +
')';
}
};
/**
* Execute a callback for each of the child nodes of this node
* @param {function(child: Node, path: string, parent: Node)} callback
*/
SymbolNode.prototype.forEach = function (callback) {
// nothing to do, we don't have childs
};
/**
* Create a new SymbolNode having it's childs be the results of calling
* the provided callback function for each of the childs of the original node.
* @param {function(child: Node, path: string, parent: Node) : Node} callback
* @returns {SymbolNode} Returns a clone of the node
*/
SymbolNode.prototype.map = function (callback) {
return this.clone();
};
/**
* Throws an error 'Undefined symbol {name}'
* @param {string} name
*/
function undef (name) {
throw new Error('Undefined symbol ' + name);
}
/**
* Create a clone of this node, a shallow copy
* @return {SymbolNode}
*/
SymbolNode.prototype.clone = function() {
return new SymbolNode(this.name);
};
/**
* Get string representation
* @param {Object} options
* @return {string} str
* @override
*/
SymbolNode.prototype._toString = function(options) {
return this.name;
};
/**
* Get LaTeX representation
* @param {Object} options
* @return {string} str
* @override
*/
SymbolNode.prototype._toTex = function(options) {
var isUnit = false;
if ((typeof math[this.name] === 'undefined') && Unit.isValuelessUnit(this.name)) {
isUnit = true;
}
var symbol = latex.toSymbol(this.name, isUnit);
if (symbol[0] === '\\') {
//no space needed if the symbol starts with '\'
return symbol;
}
//the space prevents symbols from breaking stuff like '\cdot' if it's written right before the symbol
return ' ' + symbol;
};
return SymbolNode;
}
n/a
function factory(type, config, load, typed, math) {
var add = load(require('../../function/arithmetic/addScalar'));
var subtract = load(require('../../function/arithmetic/subtract'));
var multiply = load(require('../../function/arithmetic/multiplyScalar'));
var divide = load(require('../../function/arithmetic/divideScalar'));
var pow = load(require('../../function/arithmetic/pow'));
var abs = load(require('../../function/arithmetic/abs'));
var fix = load(require('../../function/arithmetic/fix'));
var equal = load(require('../../function/relational/equal'));
var isNumeric = load(require('../../function/utils/isNumeric'));
var format = load(require('../../function/string/format'));
var getTypeOf = load(require('../../function/utils/typeof'));
var toNumber = load(require('../../type/number'));
var Complex = load(require('../../type/complex/Complex'));
/**
* A unit can be constructed in the following ways:
* var a = new Unit(value, name);
* var b = new Unit(null, name);
* var c = Unit.parse(str);
*
* Example usage:
* var a = new Unit(5, 'cm'); // 50 mm
* var b = Unit.parse('23 kg'); // 23 kg
* var c = math.in(a, new Unit(null, 'm'); // 0.05 m
* var d = new Unit(9.81, "m/s^2"); // 9.81 m/s^2
*
* @class Unit
* @constructor Unit
* @param {number | BigNumber | Fraction | Complex | boolean} [value] A value like 5.2
* @param {string} [name] A unit name like "cm" or "inch", or a derived unit of the form: "u1[^ex1] [u2[^ex2] ...] [/ u3[^ex3
] [u4[^ex4]]]", such as "kg m^2/s^2", where each unit appearing after the forward slash is taken to be in the denominator. "kg m
^2 s^-2" is a synonym and is also acceptable. Any of the units can include a prefix.
*/
function Unit(value, name) {
if (!(this instanceof Unit)) {
throw new Error('Constructor must be called with the new operator');
}
if (!(value === undefined || isNumeric(value) || value.isComplex)) {
throw new TypeError('First parameter in Unit constructor must be number, BigNumber, Fraction, Complex, or undefined');
}
if (name != undefined && (typeof name !== 'string' || name == '')) {
throw new TypeError('Second parameter in Unit constructor must be a string');
}
if (name != undefined) {
var u = Unit.parse(name);
this.units = u.units;
this.dimensions = u.dimensions;
}
else {
this.units = [
{
unit: UNIT_NONE,
prefix: PREFIXES.NONE, // link to a list with supported prefixes
power: 0
}
];
this.dimensions = [];
for(var i=0; i<BASE_DIMENSIONS.length; i++) {
this.dimensions[i] = 0;
}
}
this.value = (value != undefined) ? this._normalize(value) : null;
this.fixPrefix = false; // if true, function format will not search for the
// best prefix but leave it as initially provided.
// fixPrefix is set true by the method Unit.to
// The justification behind this is that if the constructor is explicitly called,
// the caller wishes the units to be returned exactly as he supplied.
this.isUnitListSimplified = true;
}
/**
* Attach type information
*/
Unit.prototype.type = 'Unit';
Unit.prototype.isUnit = true;
// private variables and functions for the Unit parser
var text, index, c;
function skipWhitespace() {
while (c == ' ' || c == '\t') {
next();
}
}
function isDigitDot(c) {
return ((c >= '0' && c <= '9') || c == '.');
}
function isDigit(c) {
return ((c >= '0' && c <= '9'));
}
function next() {
index++;
c = text.charAt(index);
}
function revert(oldIndex) {
index = oldIndex;
c = text.charAt(index);
}
function parseNumber() {
var number = '';
var oldIndex;
oldIndex = index;
if (c == '+') {
next();
}
else if (c == '-') {
number += c;
next();
} ...
n/a
function factory(type, config, load, typed) {
/**
* @constructor UpdateNode
*/
function UpdateNode() {
// TODO: deprecated since v3. Cleanup some day
throw new Error('UpdateNode is deprecated. Use AssignmentNode instead.');
}
return UpdateNode;
}
n/a
function factory(type, config, load, typed) {
/**
* Calculate the absolute value of a number. For matrices, the function is
* evaluated element wise.
*
* Syntax:
*
* math.abs(x)
*
* Examples:
*
* math.abs(3.5); // returns number 3.5
* math.abs(-4.2); // returns number 4.2
*
* math.abs([3, -5, -1, 0, 2]); // returns Array [3, 5, 1, 0, 2]
*
* See also:
*
* sign
*
* @param {number | BigNumber | Fraction | Complex | Array | Matrix | Unit} x
* A number or matrix for which to get the absolute value
* @return {number | BigNumber | Fraction | Complex | Array | Matrix | Unit}
* Absolute value of `x`
*/
var abs = typed('abs', {
'number': Math.abs,
'Complex': function (x) {
return x.abs();
},
'BigNumber': function (x) {
return x.abs();
},
'Fraction': function (x) {
return x.abs();
},
'Array | Matrix': function (x) {
// deep map collection, skip zeros since abs(0) = 0
return deepMap(x, abs, true);
},
'Unit': function(x) {
return x.abs();
}
});
abs.toTex = {1: '\\left|${args[0]}\\right|'};
return abs;
}
n/a
function factory(type, config, load, typed) {
/**
* Calculate the inverse cosine of a value.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.acos(x)
*
* Examples:
*
* math.acos(0.5); // returns number 1.0471975511965979
* math.acos(math.cos(1.5)); // returns number 1.5
*
* math.acos(2); // returns Complex 0 + 1.3169578969248166 i
*
* See also:
*
* cos, atan, asin
*
* @param {number | BigNumber | Complex | Array | Matrix} x Function input
* @return {number | BigNumber | Complex | Array | Matrix} The arc cosine of x
*/
var acos = typed('acos', {
'number': function (x) {
if ((x >= -1 && x <= 1) || config.predictable) {
return Math.acos(x);
}
else {
return new type.Complex(x, 0).acos();
}
},
'Complex': function (x) {
return x.acos();
},
'BigNumber': function (x) {
return x.acos();
},
'Array | Matrix': function (x) {
return deepMap(x, acos);
}
});
acos.toTex = {1: '\\cos^{-1}\\left(${args[0]}\\right)'};
return acos;
}
n/a
function factory(type, config, load, typed) {
/**
* Calculate the hyperbolic arccos of a value,
* defined as `acosh(x) = ln(sqrt(x^2 - 1) + x)`.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.acosh(x)
*
* Examples:
*
* math.acosh(1.5); // returns 0.9624236501192069
*
* See also:
*
* cosh, asinh, atanh
*
* @param {number | Complex | Unit | Array | Matrix} x Function input
* @return {number | Complex | Array | Matrix} Hyperbolic arccosine of x
*/
var acosh = typed('acosh', {
'number': function (x) {
if (x >= 1 || config.predictable) {
return _acosh(x);
}
if (x <= -1) {
return new type.Complex(Math.log(Math.sqrt(x*x - 1) - x), Math.PI);
}
return new type.Complex(x, 0).acosh();
},
'Complex': function (x) {
return x.acosh();
},
'BigNumber': function (x) {
return x.acosh();
},
'Array | Matrix': function (x) {
return deepMap(x, acosh);
}
});
acosh.toTex = {1: '\\cosh^{-1}\\left(${args[0]}\\right)'};
return acosh;
}
n/a
function factory(type, config, load, typed) {
/**
* Calculate the inverse cotangent of a value, defined as `acot(x) = atan(1/x)`.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.acot(x)
*
* Examples:
*
* math.acot(0.5); // returns number 0.4636476090008061
* math.acot(math.cot(1.5)); // returns number 1.5
*
* math.acot(2); // returns Complex 1.5707963267948966 -1.3169578969248166 i
*
* See also:
*
* cot, atan
*
* @param {number | Complex | Array | Matrix} x Function input
* @return {number | Complex | Array | Matrix} The arc cotangent of x
*/
var acot = typed('acot', {
'number': function (x) {
return Math.atan(1 / x);
},
'Complex': function (x) {
return x.acot();
},
'BigNumber': function (x) {
return new type.BigNumber(1).div(x).atan();
},
'Array | Matrix': function (x) {
return deepMap(x, acot);
}
});
acot.toTex = {1: '\\cot^{-1}\\left(${args[0]}\\right)'};
return acot;
}
n/a
function factory(type, config, load, typed) {
/**
* Calculate the hyperbolic arccotangent of a value,
* defined as `acoth(x) = atanh(1/x) = (ln((x+1)/x) + ln(x/(x-1))) / 2`.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.acoth(x)
*
* Examples:
*
* math.acoth(0.5); // returns 0.8047189562170503
*
* See also:
*
* acsch, asech
*
* @param {number | Complex | Array | Matrix} x Function input
* @return {number | Complex | Array | Matrix} Hyperbolic arccotangent of x
*/
var acoth = typed('acoth', {
'number': function (x) {
if (x >= 1 || x <= -1 || config.predictable) {
return isFinite(x) ? (Math.log((x+1)/x) + Math.log(x/(x-1))) / 2 : 0;
}
return new type.Complex(x, 0).acoth();
},
'Complex': function (x) {
return x.acoth();
},
'BigNumber': function (x) {
return new type.BigNumber(1).div(x).atanh();
},
'Array | Matrix': function (x) {
return deepMap(x, acoth);
}
});
acoth.toTex = {1: '\\coth^{-1}\\left(${args[0]}\\right)'};
return acoth;
}
n/a
function factory(type, config, load, typed) {
/**
* Calculate the inverse cosecant of a value, defined as `acsc(x) = asin(1/x)`.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.acsc(x)
*
* Examples:
*
* math.acsc(0.5); // returns number 0.5235987755982989
* math.acsc(math.csc(1.5)); // returns number ~1.5
*
* math.acsc(2); // returns Complex 1.5707963267948966 -1.3169578969248166 i
*
* See also:
*
* csc, asin, asec
*
* @param {number | Complex | Array | Matrix} x Function input
* @return {number | Complex | Array | Matrix} The arc cosecant of x
*/
var acsc = typed('acsc', {
'number': function (x) {
if (x <= -1 || x >= 1 || config.predictable) {
return Math.asin(1 / x);
}
return new type.Complex(x, 0).acsc();
},
'Complex': function (x) {
return x.acsc();
},
'BigNumber': function (x) {
return new type.BigNumber(1).div(x).asin();
},
'Array | Matrix': function (x) {
return deepMap(x, acsc);
}
});
acsc.toTex = {1: '\\csc^{-1}\\left(${args[0]}\\right)'};
return acsc;
}
n/a
function factory(type, config, load, typed) {
/**
* Calculate the hyperbolic arccosecant of a value,
* defined as `acsch(x) = asinh(1/x) = ln(1/x + sqrt(1/x^2 + 1))`.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.acsch(x)
*
* Examples:
*
* math.acsch(0.5); // returns 1.4436354751788103
*
* See also:
*
* asech, acoth
*
* @param {number | Complex | Array | Matrix} x Function input
* @return {number | Complex | Array | Matrix} Hyperbolic arccosecant of x
*/
var acsch = typed('acsch', {
'number': function (x) {
x = 1 / x;
return Math.log(x + Math.sqrt(x*x + 1));
},
'Complex': function (x) {
return x.acsch();
},
'BigNumber': function (x) {
return new type.BigNumber(1).div(x).asinh();
},
'Array | Matrix': function (x) {
return deepMap(x, acsch);
}
});
acsch.toTex = {1: '\\mathrm{csch}^{-1}\\left(${args[0]}\\right)'};
return acsch;
}
n/a
function factory(type, config, load, typed) {
var matrix = load(require('../../type/matrix/function/matrix'));
var addScalar = load(require('./addScalar'));
var latex = require('../../utils/latex.js');
var algorithm01 = load(require('../../type/matrix/utils/algorithm01'));
var algorithm04 = load(require('../../type/matrix/utils/algorithm04'));
var algorithm10 = load(require('../../type/matrix/utils/algorithm10'));
var algorithm13 = load(require('../../type/matrix/utils/algorithm13'));
var algorithm14 = load(require('../../type/matrix/utils/algorithm14'));
/**
* Add two or more values, `x + y`.
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.add(x, y)
* math.add(x, y, z, ...)
*
* Examples:
*
* math.add(2, 3); // returns number 5
* math.add(2, 3, 4); // returns number 9
*
* var a = math.complex(2, 3);
* var b = math.complex(-4, 1);
* math.add(a, b); // returns Complex -2 + 4i
*
* math.add([1, 2, 3], 4); // returns Array [5, 6, 7]
*
* var c = math.unit('5 cm');
* var d = math.unit('2.1 mm');
* math.add(c, d); // returns Unit 52.1 mm
*
* math.add("2.3", "4"); // returns number 6.3
*
* See also:
*
* subtract, sum
*
* @param {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} x First value to add
* @param {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} y Second value to add
* @return {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} Sum of `x` and `y`
*/
var add = typed('add', extend({
// we extend the signatures of addScalar with signatures dealing with matrices
'Matrix, Matrix': function (x, y) {
// result
var c;
// process matrix storage
switch (x.storage()) {
case 'sparse':
switch (y.storage()) {
case 'sparse':
// sparse + sparse
c = algorithm04(x, y, addScalar);
break;
default:
// sparse + dense
c = algorithm01(y, x, addScalar, true);
break;
}
break;
default:
switch (y.storage()) {
case 'sparse':
// dense + sparse
c = algorithm01(x, y, addScalar, false);
break;
default:
// dense + dense
c = algorithm13(x, y, addScalar);
break;
}
break;
}
return c;
},
'Array, Array': function (x, y) {
// use matrix implementation
return add(matrix(x), matrix(y)).valueOf();
},
'Array, Matrix': function (x, y) {
// use matrix implementation
return add(matrix(x), y);
},
'Matrix, Array': function (x, y) {
// use matrix implementation
return add(x, matrix(y));
},
'Matrix, any': function (x, y) {
// result
var c;
// check storage format
switch (x.storage()) {
case 'sparse':
c = algorithm10(x, y, addScalar, false);
break;
default:
c = algorithm14(x, y, addScalar, false);
break;
}
return c;
},
'any, Matrix': function (x, y) {
// result
var c;
// check storage format
switch (y.storage()) {
case 'sparse':
c = algorithm10(y, x, addScalar, true);
break;
default:
c = algorithm14(y, x, addScalar, true);
break;
}
return c;
},
'Array, any': function (x, y) {
// use matrix implementation
return algorithm14(matrix(x), y, addScalar, false).valueOf();
},
'any, Array': function (x, y) {
// use matrix implementation
return algorithm14(matrix(y), x, addScalar, true).valueOf();
},
'any, any': addScalar,
'any, any, ...any': function (x, y, rest) {
var result = add(x, y);
f ...
n/a
function factory(type, config, load, typed) {
/**
* Add two scalar values, `x + y`.
* This function is meant for internal use: it is used by the public function
* `add`
*
* This function does not support collections (Array or Matrix), and does
* not validate the number of of inputs.
*
* @param {number | BigNumber | Fraction | Complex | Unit} x First value to add
* @param {number | BigNumber | Fraction | Complex} y Second value to add
* @return {number | BigNumber | Fraction | Complex | Unit} Sum of `x` and `y`
* @private
*/
var add = typed('add', {
'number, number': function (x, y) {
return x + y;
},
'Complex, Complex': function (x, y) {
return x.add(y);
},
'BigNumber, BigNumber': function (x, y) {
return x.plus(y);
},
'Fraction, Fraction': function (x, y) {
return x.add(y);
},
'Unit, Unit': function (x, y) {
if (x.value == null) throw new Error('Parameter x contains a unit with undefined value');
if (y.value == null) throw new Error('Parameter y contains a unit with undefined value');
if (!x.equalBase(y)) throw new Error('Units do not match');
var res = x.clone();
res.value = add(res.value, y.value);
res.fixPrefix = false;
return res;
}
});
return add;
}
n/a
function factory(type, config, load, typed) {
var latex = require('../../utils/latex');
var matrix = load(require('../../type/matrix/function/matrix'));
var zeros = load(require('../matrix/zeros'));
var not = load(require('./not'));
var isZero = load(require('../utils/isZero'));
var algorithm02 = load(require('../../type/matrix/utils/algorithm02'));
var algorithm06 = load(require('../../type/matrix/utils/algorithm06'));
var algorithm11 = load(require('../../type/matrix/utils/algorithm11'));
var algorithm13 = load(require('../../type/matrix/utils/algorithm13'));
var algorithm14 = load(require('../../type/matrix/utils/algorithm14'));
/**
* Logical `and`. Test whether two values are both defined with a nonzero/nonempty value.
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.and(x, y)
*
* Examples:
*
* math.and(2, 4); // returns true
*
* a = [2, 0, 0];
* b = [3, 7, 0];
* c = 0;
*
* math.and(a, b); // returns [true, false, false]
* math.and(a, c); // returns [false, false, false]
*
* See also:
*
* not, or, xor
*
* @param {number | BigNumber | Complex | Unit | Array | Matrix} x First value to check
* @param {number | BigNumber | Complex | Unit | Array | Matrix} y Second value to check
* @return {boolean | Array | Matrix}
* Returns true when both inputs are defined with a nonzero/nonempty value.
*/
var and = typed('and', {
'number, number': function (x, y) {
return !!(x && y);
},
'Complex, Complex': function (x, y) {
return (x.re !== 0 || x.im !== 0) && (y.re !== 0 || y.im !== 0);
},
'BigNumber, BigNumber': function (x, y) {
return !x.isZero() && !y.isZero() && !x.isNaN() && !y.isNaN();
},
'Unit, Unit': function (x, y) {
return and(x.value, y.value);
},
'Matrix, Matrix': function (x, y) {
// result
var c;
// process matrix storage
switch (x.storage()) {
case 'sparse':
switch (y.storage()) {
case 'sparse':
// sparse & sparse
c = algorithm06(x, y, and, false);
break;
default:
// sparse & dense
c = algorithm02(y, x, and, true);
break;
}
break;
default:
switch (y.storage()) {
case 'sparse':
// dense & sparse
c = algorithm02(x, y, and, false);
break;
default:
// dense & dense
c = algorithm13(x, y, and);
break;
}
break;
}
return c;
},
'Array, Array': function (x, y) {
// use matrix implementation
return and(matrix(x), matrix(y)).valueOf();
},
'Array, Matrix': function (x, y) {
// use matrix implementation
return and(matrix(x), y);
},
'Matrix, Array': function (x, y) {
// use matrix implementation
return and(x, matrix(y));
},
'Matrix, any': function (x, y) {
// check scalar
if (not(y)) {
// return zero matrix
return zeros(x.size(), x.storage());
}
// result
var c;
// check storage format
switch (x.storage()) {
case 'sparse':
c = algorithm11(x, y, and, false);
break;
default:
c = algorithm14(x, y, and, false);
break;
}
return c;
},
'any, Matrix': function (x, y) {
// check scalar
if (not(x)) {
// return zero matrix
return zeros(x.size(), x.storage());
}
// result
var c;
// check storage format
switch (y.storage()) {
case 'sparse':
c = algorithm11(y, x, and, true);
break;
default:
c = algorithm14(y, x, and, true);
break;
}
return c;
},
'Array, any': function (x, y) {
// use matrix implementation
return and(matrix(x), y).val ...
n/a
function factory(type, config, load, typed) {
/**
* Compute the argument of a complex value.
* For a complex number `a + bi`, the argument is computed as `atan2(b, a)`.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.arg(x)
*
* Examples:
*
* var a = math.complex(2, 2);
* math.arg(a) / math.pi; // returns number 0.25
*
* var b = math.complex('2 + 3i');
* math.arg(b); // returns number 0.982793723247329
* math.atan2(3, 2); // returns number 0.982793723247329
*
* See also:
*
* re, im, conj, abs
*
* @param {number | BigNumber | Complex | Array | Matrix} x
* A complex number or array with complex numbers
* @return {number | BigNumber | Array | Matrix} The argument of x
*/
var arg = typed('arg', {
'number': function (x) {
return Math.atan2(0, x);
},
'BigNumber': function (x) {
return type.BigNumber.atan2(0, x);
},
'Complex': function (x) {
return x.arg();
},
// TODO: implement BigNumber support for function arg
'Array | Matrix': function (x) {
return deepMap(x, arg);
}
});
arg.toTex = {1: '\\arg\\left(${args[0]}\\right)'};
return arg;
}
n/a
flatten = function (array) { if (!Array.isArray(array)) { //if not an array, return as is return array; } var flat = []; array.forEach(function callback(value) { if (Array.isArray(value)) { value.forEach(callback); //traverse through sub-arrays recursively } else { flat.push(value); } }); return flat; }
...
* @returns {Array} Array whose data has been formatted to fit the
* specified dimensions
*
* @throws {DimensionError} If the product of the new dimension sizes does
* not equal that of the old ones
*/
exports.reshape = function(array, sizes) {
var flatArray = exports.flatten(array);
var newArray;
var product = function (arr) {
return arr.reduce(function (prev, curr) {
return prev * curr;
});
};
...
function isArray() { [native code] }
...
extra_nodes = (options && options.nodes) ? options.nodes : {};
if (typeof expr === 'string') {
// parse a single expression
expression = expr;
return parseStart();
}
else if (Array.isArray(expr) || expr instanceof type.Matrix) {
// parse an array or matrix with expressions
return deepMap(expr, function (elem) {
if (typeof elem !== 'string') throw new TypeError('String expected');
expression = elem;
return parseStart();
});
...
reshape = function (array, sizes) { var flatArray = exports.flatten(array); var newArray; var product = function (arr) { return arr.reduce(function (prev, curr) { return prev * curr; }); }; if (!Array.isArray(array) || !Array.isArray(sizes)) { throw new TypeError('Array expected'); } if (sizes.length === 0) { throw new DimensionError(0, product(exports.size(array)), '!='); } try { newArray = _reshape(flatArray, sizes); } catch (e) { if (e instanceof DimensionError) { throw new DimensionError( product(sizes), product(exports.size(array)), '!=' ); } throw e; } if (flatArray.length > 0) { throw new DimensionError( product(sizes), product(exports.size(array)), '!=' ); } return newArray; }
...
var matrix = load(require('../../type/matrix/function/matrix'));
/**
* Reshape a multi dimensional array to fit the specified dimensions
*
* Syntax:
*
* math.reshape(x, sizes)
*
* Examples:
*
* math.reshape([1, 2, 3, 4, 5, 6], [2, 3]);
* // returns Array [[1, 2, 3], [4, 5, 6]]
*
* math.reshape([[1, 2], [3, 4]], [1, 4]);
...
resize = function (array, size, defaultValue) { // TODO: add support for scalars, having size=[] ? // check the type of the arguments if (!Array.isArray(array) || !Array.isArray(size)) { throw new TypeError('Array expected'); } if (size.length === 0) { throw new Error('Resizing to scalar is not supported'); } // check whether size contains positive integers size.forEach(function (value) { if (!number.isNumber(value) || !number.isInteger(value) || value < 0) { throw new TypeError('Invalid size, must contain positive integers ' + '(size: ' + string.format(size) + ')'); } }); // recursively resize the array var _defaultValue = (defaultValue !== undefined) ? defaultValue : 0; _resize(array, size, 0, _defaultValue); return array; }
...
// get matrix storage constructor
var F = type.Matrix.storage(format);
// create diagonal matrix (use optimized implementation for storage format)
return F.diagonal(size, one, 0, defaultValue);
}
// create and resize array
var res = array.resize([], size, defaultValue);
// fill in ones on the diagonal
var minimum = rows < cols ? rows : cols;
// fill diagonal
for (var d = 0; d < minimum; d++) {
res[d][d] = one;
}
return res;
...
size = function (x) { var s = []; while (Array.isArray(x)) { s.push(x.length); x = x[0]; } return s; }
...
};
if (!Array.isArray(array) || !Array.isArray(sizes)) {
throw new TypeError('Array expected');
}
if (sizes.length === 0) {
throw new DimensionError(0, product(exports.size(array)), '!=');
}
try {
newArray = _reshape(flatArray, sizes);
} catch (e) {
if (e instanceof DimensionError) {
throw new DimensionError(
...
squeeze = function (array, size) { var s = size || exports.size(array); // squeeze outer dimensions while (Array.isArray(array) && array.length === 1) { array = array[0]; s.shift(); } // find the first dimension to be squeezed var dims = s.length; while (s[dims - 1] === 1) { dims--; } // squeeze inner dimensions if (dims < s.length) { array = _squeeze(array, dims, 0); s.length = dims; } return array; }
...
* @param {Array} y Second vector
* @returns {Array} Returns the cross product of x and y
* @private
*/
function _cross(x, y) {
var highestDimension = Math.max(array.size(x).length, array.size(y).length);
x = array.squeeze(x);
y = array.squeeze(y);
var xSize = array.size(x);
var ySize = array.size(y);
if (xSize.length != 1 || ySize.length != 1 || xSize[0] != 3 || ySize[0] != 3) {
throw new RangeError('Vectors with length 3 expected ' +
...
unsqueeze = function (array, dims, outer, size) { var s = size || exports.size(array); // unsqueeze outer dimensions if (outer) { for (var i = 0; i < outer; i++) { array = [array]; s.unshift(1); } } // unsqueeze inner dimensions array = _unsqueeze(array, dims, 0); while (s.length < dims) { s.push(1); } return array; }
...
}
while (iSize[i] === 1) {
outer++;
i++;
}
// unsqueeze both outer and inner dimensions
submatrix = array.unsqueeze(submatrix, iSize.length, outer, sSize);
}
// check whether the size of the submatrix matches the index size
if (!object.deepEqual(iSize, sSize)) {
throw new DimensionError(iSize, sSize, '>');
}
...
validate = function (array, size) { var isScalar = (size.length == 0); if (isScalar) { // scalar if (Array.isArray(array)) { throw new DimensionError(array.length, 0); } } else { // array _validate(array, size, 0); } }
...
}
else if (isArray(data)) {
// replace nested Matrices with Arrays
this._data = preprocess(data);
// get the dimensions of the array
this._size = array.size(this._data);
// verify the dimensions of the array, TODO: compute size while processing array
array.validate(this._data, this._size);
// data type unknown
this._datatype = datatype;
}
else if (data) {
// unsupported type
throw new TypeError('Unsupported type of data (' + util.types.type(data) + ')');
}
...
validateIndex = function (index, length) { if (!number.isNumber(index) || !number.isInteger(index)) { throw new TypeError('Index must be an integer (value: ' + index + ')'); } if (index < 0 || (typeof length === 'number' && index >= length)) { throw new IndexError(index, length); } }
n/a
function factory(type, config, load, typed) {
/**
* Calculate the inverse secant of a value. Defined as `asec(x) = acos(1/x)`.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.asec(x)
*
* Examples:
*
* math.asec(0.5); // returns 1.0471975511965979
* math.asec(math.sec(1.5)); // returns 1.5
*
* math.asec(2); // returns 0 + 1.3169578969248166 i
*
* See also:
*
* acos, acot, acsc
*
* @param {number | Complex | Array | Matrix} x Function input
* @return {number | Complex | Array | Matrix} The arc secant of x
*/
var asec = typed('asec', {
'number': function (x) {
if (x <= -1 || x >= 1 || config.predictable) {
return Math.acos(1 / x);
}
return new type.Complex(x, 0).asec();
},
'Complex': function (x) {
return x.asec();
},
'BigNumber': function (x) {
return new type.BigNumber(1).div(x).acos();
},
'Array | Matrix': function (x) {
return deepMap(x, asec);
}
});
asec.toTex = {1: '\\sec^{-1}\\left(${args[0]}\\right)'};
return asec;
}
n/a
function factory(type, config, load, typed) {
var acosh = typed.find(load(require('./acosh')), ['Complex']);
/**
* Calculate the hyperbolic arcsecant of a value,
* defined as `asech(x) = acosh(1/x) = ln(sqrt(1/x^2 - 1) + 1/x)`.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.asech(x)
*
* Examples:
*
* math.asech(0.5); // returns 1.3169578969248166
*
* See also:
*
* acsch, acoth
*
* @param {number | Complex | Array | Matrix} x Function input
* @return {number | Complex | Array | Matrix} Hyperbolic arcsecant of x
*/
var asech = typed('asech', {
'number': function (x) {
if ((x <= 1 && x >= -1) || config.predictable) {
x = 1 / x;
var ret = Math.sqrt(x*x - 1);
if (x > 0 || config.predictable) {
return Math.log(ret + x);
}
return new type.Complex(Math.log(ret - x), Math.PI);
}
return new type.Complex(x, 0).asech();
},
'Complex': function (x) {
return x.asech()
},
'BigNumber': function (x) {
return new type.BigNumber(1).div(x).acosh();
},
'Array | Matrix': function (x) {
return deepMap(x, asech);
}
});
asech.toTex = {1: '\\mathrm{sech}^{-1}\\left(${args[0]}\\right)'};
return asech;
}
n/a
function factory(type, config, load, typed) {
/**
* Calculate the inverse sine of a value.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.asin(x)
*
* Examples:
*
* math.asin(0.5); // returns number 0.5235987755982989
* math.asin(math.sin(1.5)); // returns number ~1.5
*
* math.asin(2); // returns Complex 1.5707963267948966 -1.3169578969248166 i
*
* See also:
*
* sin, atan, acos
*
* @param {number | BigNumber | Complex | Array | Matrix} x Function input
* @return {number | BigNumber | Complex | Array | Matrix} The arc sine of x
*/
var asin = typed('asin', {
'number': function (x) {
if ((x >= -1 && x <= 1) || config.predictable) {
return Math.asin(x);
}
else {
return new type.Complex(x, 0).asin();
}
},
'Complex': function (x) {
return x.asin();
},
'BigNumber': function (x) {
return x.asin();
},
'Array | Matrix': function (x) {
// deep map collection, skip zeros since asin(0) = 0
return deepMap(x, asin, true);
}
});
asin.toTex = {1: '\\sin^{-1}\\left(${args[0]}\\right)'};
return asin;
}
n/a
function factory(type, config, load, typed) {
/**
* Calculate the hyperbolic arcsine of a value,
* defined as `asinh(x) = ln(x + sqrt(x^2 + 1))`.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.asinh(x)
*
* Examples:
*
* math.asinh(0.5); // returns 0.48121182505960347
*
* See also:
*
* acosh, atanh
*
* @param {number | Complex | Array | Matrix} x Function input
* @return {number | Complex | Array | Matrix} Hyperbolic arcsine of x
*/
var asinh = typed('asinh', {
'number': Math.asinh || function (x) {
return Math.log(Math.sqrt(x*x + 1) + x);
},
'Complex': function (x) {
return x.asinh();
},
'BigNumber': function (x) {
return x.asinh();
},
'Array | Matrix': function (x) {
// deep map collection, skip zeros since asinh(0) = 0
return deepMap(x, asinh, true);
}
});
asinh.toTex = {1: '\\sinh^{-1}\\left(${args[0]}\\right)'};
return asinh;
}
n/a
function factory(type, config, load, typed) {
/**
* Calculate the inverse tangent of a value.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.atan(x)
*
* Examples:
*
* math.atan(0.5); // returns number 0.4636476090008061
* math.atan(math.tan(1.5)); // returns number 1.5
*
* math.atan(2); // returns Complex 1.5707963267948966 -1.3169578969248166 i
*
* See also:
*
* tan, asin, acos
*
* @param {number | BigNumber | Complex | Array | Matrix} x Function input
* @return {number | BigNumber | Complex | Array | Matrix} The arc tangent of x
*/
var atan = typed('atan', {
'number': function (x) {
return Math.atan(x);
},
'Complex': function (x) {
return x.atan();
},
'BigNumber': function (x) {
return x.atan();
},
'Array | Matrix': function (x) {
// deep map collection, skip zeros since atan(0) = 0
return deepMap(x, atan, true);
}
});
atan.toTex = {1: '\\tan^{-1}\\left(${args[0]}\\right)'};
return atan;
}
n/a
function factory(type, config, load, typed) {
var matrix = load(require('../../type/matrix/function/matrix'));
var algorithm02 = load(require('../../type/matrix/utils/algorithm02'));
var algorithm03 = load(require('../../type/matrix/utils/algorithm03'));
var algorithm09 = load(require('../../type/matrix/utils/algorithm09'));
var algorithm11 = load(require('../../type/matrix/utils/algorithm11'));
var algorithm12 = load(require('../../type/matrix/utils/algorithm12'));
var algorithm13 = load(require('../../type/matrix/utils/algorithm13'));
var algorithm14 = load(require('../../type/matrix/utils/algorithm14'));
/**
* Calculate the inverse tangent function with two arguments, y/x.
* By providing two arguments, the right quadrant of the computed angle can be
* determined.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.atan2(y, x)
*
* Examples:
*
* math.atan2(2, 2) / math.pi; // returns number 0.25
*
* var angle = math.unit(60, 'deg'); // returns Unit 60 deg
* var x = math.cos(angle);
* var y = math.sin(angle);
*
* math.atan(2); // returns Complex 1.5707963267948966 -1.3169578969248166 i
*
* See also:
*
* tan, atan, sin, cos
*
* @param {number | Array | Matrix} y Second dimension
* @param {number | Array | Matrix} x First dimension
* @return {number | Array | Matrix} Four-quadrant inverse tangent
*/
var atan2 = typed('atan2', {
'number, number': Math.atan2,
// Complex numbers doesn't seem to have a reasonable implementation of
// atan2(). Even Matlab removed the support, after they only calculated
// the atan only on base of the real part of the numbers and ignored the imaginary.
'BigNumber, BigNumber': function (y, x) {
return type.BigNumber.atan2(y, x);
},
'Matrix, Matrix': function (x, y) {
// result
var c;
// process matrix storage
switch (x.storage()) {
case 'sparse':
switch (y.storage()) {
case 'sparse':
// sparse .* sparse
c = algorithm09(x, y, atan2, false);
break;
default:
// sparse .* dense
c = algorithm02(y, x, atan2, true);
break;
}
break;
default:
switch (y.storage()) {
case 'sparse':
// dense .* sparse
c = algorithm03(x, y, atan2, false);
break;
default:
// dense .* dense
c = algorithm13(x, y, atan2);
break;
}
break;
}
return c;
},
'Array, Array': function (x, y) {
// use matrix implementation
return atan2(matrix(x), matrix(y)).valueOf();
},
'Array, Matrix': function (x, y) {
// use matrix implementation
return atan2(matrix(x), y);
},
'Matrix, Array': function (x, y) {
// use matrix implementation
return atan2(x, matrix(y));
},
'Matrix, number | BigNumber': function (x, y) {
// result
var c;
// check storage format
switch (x.storage()) {
case 'sparse':
c = algorithm11(x, y, atan2, false);
break;
default:
c = algorithm14(x, y, atan2, false);
break;
}
return c;
},
'number | BigNumber, Matrix': function (x, y) {
// result
var c;
// check storage format
switch (y.storage()) {
case 'sparse':
c = algorithm12(y, x, atan2, true);
break;
default:
c = algorithm14(y, x, atan2, true);
break;
}
return c;
},
'Array, number | BigNumber': function (x, y) {
// use matrix implementation
return algorithm14(matrix(x), y, atan2, false).valueOf();
},
'number | BigNumber, Array': function (x, y) {
// use matrix implementation
return algorithm14(matrix(y), x, atan2, true).valueOf();
}
});
at ...
n/a
function factory(type, config, load, typed) {
/**
* Calculate the hyperbolic arctangent of a value,
* defined as `atanh(x) = ln((1 + x)/(1 - x)) / 2`.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.atanh(x)
*
* Examples:
*
* math.atanh(0.5); // returns 0.5493061443340549
*
* See also:
*
* acosh, asinh
*
* @param {number | Complex | Array | Matrix} x Function input
* @return {number | Complex | Array | Matrix} Hyperbolic arctangent of x
*/
var atanh = typed('atanh', {
'number': function (x) {
if ((x <= 1 && x >= -1) || config.predictable) {
return _atanh(x);
}
return new type.Complex(x, 0).atanh();
},
'Complex': function (x) {
return x.atanh();
},
'BigNumber': function (x) {
return x.atanh();
},
'Array | Matrix': function (x) {
// deep map collection, skip zeros since atanh(0) = 0
return deepMap(x, atanh, true);
}
});
atanh.toTex = {1: '\\tanh^{-1}\\left(${args[0]}\\right)'};
return atanh;
}
n/a
function factory(type, config, load, typed) {
var add = load(require('../arithmetic/add'));
var stirlingS2 = load(require('./stirlingS2'));
var isNegative = load(require('../utils/isNegative'));
var isInteger = load(require('../utils/isInteger'));
/**
* The Bell Numbers count the number of partitions of a set. A partition is a pairwise disjoint subset of S whose union is S.
* bellNumbers only takes integer arguments.
* The following condition must be enforced: n >= 0
*
* Syntax:
*
* math.bellNumbers(n)
*
* Examples:
*
* math.bellNumbers(3); // returns 5;
* math.bellNumbers(8); // returns 4140;
*
* See also:
*
* stirlingS2
*
* @param {Number | BigNumber} n Total number of objects in the set
* @return {Number | BigNumber} B(n)
*/
var bellNumbers = typed('bellNumbers', {
'number | BigNumber': function (n) {
if (!isInteger(n) || isNegative(n)) {
throw new TypeError('Non-negative integer value expected in function bellNumbers');
}
// Sum (k=0, n) S(n,k).
var result = 0;
for(var i = 0; i <= n; i++) {
result = add(result, stirlingS2(n, i));
}
return result;
}
});
bellNumbers.toTex = {1: '\\mathrm{B}_{${args[0]}}'};
return bellNumbers;
}
n/a
function factory(type, config, load, typed) {
var latex = require('../../utils/latex');
var matrix = load(require('../../type/matrix/function/matrix'));
var algorithm02 = load(require('../../type/matrix/utils/algorithm02'));
var algorithm06 = load(require('../../type/matrix/utils/algorithm06'));
var algorithm11 = load(require('../../type/matrix/utils/algorithm11'));
var algorithm13 = load(require('../../type/matrix/utils/algorithm13'));
var algorithm14 = load(require('../../type/matrix/utils/algorithm14'));
/**
* Bitwise AND two values, `x & y`.
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.bitAnd(x, y)
*
* Examples:
*
* math.bitAnd(53, 131); // returns number 1
*
* math.bitAnd([1, 12, 31], 42); // returns Array [0, 8, 10]
*
* See also:
*
* bitNot, bitOr, bitXor, leftShift, rightArithShift, rightLogShift
*
* @param {number | BigNumber | Array | Matrix} x First value to and
* @param {number | BigNumber | Array | Matrix} y Second value to and
* @return {number | BigNumber | Array | Matrix} AND of `x` and `y`
*/
var bitAnd = typed('bitAnd', {
'number, number': function (x, y) {
if (!isInteger(x) || !isInteger(y)) {
throw new Error('Integers expected in function bitAnd');
}
return x & y;
},
'BigNumber, BigNumber': bigBitAnd,
'Matrix, Matrix': function (x, y) {
// result
var c;
// process matrix storage
switch (x.storage()) {
case 'sparse':
switch (y.storage()) {
case 'sparse':
// sparse & sparse
c = algorithm06(x, y, bitAnd, false);
break;
default:
// sparse & dense
c = algorithm02(y, x, bitAnd, true);
break;
}
break;
default:
switch (y.storage()) {
case 'sparse':
// dense & sparse
c = algorithm02(x, y, bitAnd, false);
break;
default:
// dense & dense
c = algorithm13(x, y, bitAnd);
break;
}
break;
}
return c;
},
'Array, Array': function (x, y) {
// use matrix implementation
return bitAnd(matrix(x), matrix(y)).valueOf();
},
'Array, Matrix': function (x, y) {
// use matrix implementation
return bitAnd(matrix(x), y);
},
'Matrix, Array': function (x, y) {
// use matrix implementation
return bitAnd(x, matrix(y));
},
'Matrix, any': function (x, y) {
// result
var c;
// check storage format
switch (x.storage()) {
case 'sparse':
c = algorithm11(x, y, bitAnd, false);
break;
default:
c = algorithm14(x, y, bitAnd, false);
break;
}
return c;
},
'any, Matrix': function (x, y) {
// result
var c;
// check storage format
switch (y.storage()) {
case 'sparse':
c = algorithm11(y, x, bitAnd, true);
break;
default:
c = algorithm14(y, x, bitAnd, true);
break;
}
return c;
},
'Array, any': function (x, y) {
// use matrix implementation
return algorithm14(matrix(x), y, bitAnd, false).valueOf();
},
'any, Array': function (x, y) {
// use matrix implementation
return algorithm14(matrix(y), x, bitAnd, true).valueOf();
}
});
bitAnd.toTex = {
2: '\\left(${args[0]}' + latex.operators['bitAnd'] + '${args[1]}\\right)'
};
return bitAnd;
}
n/a
function factory(type, config, load, typed) {
var latex = require('../../utils/latex');
/**
* Bitwise NOT value, `~x`.
* For matrices, the function is evaluated element wise.
* For units, the function is evaluated on the best prefix base.
*
* Syntax:
*
* math.bitNot(x)
*
* Examples:
*
* math.bitNot(1); // returns number -2
*
* math.bitNot([2, -3, 4]); // returns Array [-3, 2, 5]
*
* See also:
*
* bitAnd, bitOr, bitXor, leftShift, rightArithShift, rightLogShift
*
* @param {number | BigNumber | Array | Matrix} x Value to not
* @return {number | BigNumber | Array | Matrix} NOT of `x`
*/
var bitNot = typed('bitNot', {
'number': function (x) {
if (!isInteger(x)) {
throw new Error('Integer expected in function bitNot');
}
return ~x;
},
'BigNumber': bigBitNot,
'Array | Matrix': function (x) {
return deepMap(x, bitNot);
}
});
bitNot.toTex = {
1: latex.operators['bitNot'] + '\\left(${args[0]}\\right)'
};
return bitNot;
}
n/a
function factory(type, config, load, typed) {
var latex = require('../../utils/latex');
var matrix = load(require('../../type/matrix/function/matrix'));
var algorithm01 = load(require('../../type/matrix/utils/algorithm01'));
var algorithm04 = load(require('../../type/matrix/utils/algorithm04'));
var algorithm10 = load(require('../../type/matrix/utils/algorithm10'));
var algorithm13 = load(require('../../type/matrix/utils/algorithm13'));
var algorithm14 = load(require('../../type/matrix/utils/algorithm14'));
/**
* Bitwise OR two values, `x | y`.
* For matrices, the function is evaluated element wise.
* For units, the function is evaluated on the lowest print base.
*
* Syntax:
*
* math.bitOr(x, y)
*
* Examples:
*
* math.bitOr(1, 2); // returns number 3
*
* math.bitOr([1, 2, 3], 4); // returns Array [5, 6, 7]
*
* See also:
*
* bitAnd, bitNot, bitXor, leftShift, rightArithShift, rightLogShift
*
* @param {number | BigNumber | Array | Matrix} x First value to or
* @param {number | BigNumber | Array | Matrix} y Second value to or
* @return {number | BigNumber | Array | Matrix} OR of `x` and `y`
*/
var bitOr = typed('bitOr', {
'number, number': function (x, y) {
if (!isInteger(x) || !isInteger(y)) {
throw new Error('Integers expected in function bitOr');
}
return x | y;
},
'BigNumber, BigNumber': bigBitOr,
'Matrix, Matrix': function (x, y) {
// result
var c;
// process matrix storage
switch (x.storage()) {
case 'sparse':
switch (y.storage()) {
case 'sparse':
// sparse + sparse
c = algorithm04(x, y, bitOr);
break;
default:
// sparse + dense
c = algorithm01(y, x, bitOr, true);
break;
}
break;
default:
switch (y.storage()) {
case 'sparse':
// dense + sparse
c = algorithm01(x, y, bitOr, false);
break;
default:
c = algorithm13(x, y, bitOr);
break;
}
break;
}
return c;
},
'Array, Array': function (x, y) {
// use matrix implementation
return bitOr(matrix(x), matrix(y)).valueOf();
},
'Array, Matrix': function (x, y) {
// use matrix implementation
return bitOr(matrix(x), y);
},
'Matrix, Array': function (x, y) {
// use matrix implementation
return bitOr(x, matrix(y));
},
'Matrix, any': function (x, y) {
// result
var c;
// check storage format
switch (x.storage()) {
case 'sparse':
c = algorithm10(x, y, bitOr, false);
break;
default:
c = algorithm14(x, y, bitOr, false);
break;
}
return c;
},
'any, Matrix': function (x, y) {
// result
var c;
// check storage format
switch (y.storage()) {
case 'sparse':
c = algorithm10(y, x, bitOr, true);
break;
default:
c = algorithm14(y, x, bitOr, true);
break;
}
return c;
},
'Array, any': function (x, y) {
// use matrix implementation
return algorithm14(matrix(x), y, bitOr, false).valueOf();
},
'any, Array': function (x, y) {
// use matrix implementation
return algorithm14(matrix(y), x, bitOr, true).valueOf();
}
});
bitOr.toTex = {
2: '\\left(${args[0]}' + latex.operators['bitOr'] + '${args[1]}\\right)'
};
return bitOr;
}
n/a
function factory(type, config, load, typed) {
var latex = require('../../utils/latex');
var matrix = load(require('../../type/matrix/function/matrix'));
var algorithm03 = load(require('../../type/matrix/utils/algorithm03'));
var algorithm07 = load(require('../../type/matrix/utils/algorithm07'));
var algorithm12 = load(require('../../type/matrix/utils/algorithm12'));
var algorithm13 = load(require('../../type/matrix/utils/algorithm13'));
var algorithm14 = load(require('../../type/matrix/utils/algorithm14'));
/**
* Bitwise XOR two values, `x ^ y`.
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.bitXor(x, y)
*
* Examples:
*
* math.bitXor(1, 2); // returns number 3
*
* math.bitXor([2, 3, 4], 4); // returns Array [6, 7, 0]
*
* See also:
*
* bitAnd, bitNot, bitOr, leftShift, rightArithShift, rightLogShift
*
* @param {number | BigNumber | Array | Matrix} x First value to xor
* @param {number | BigNumber | Array | Matrix} y Second value to xor
* @return {number | BigNumber | Array | Matrix} XOR of `x` and `y`
*/
var bitXor = typed('bitXor', {
'number, number': function (x, y) {
if (!isInteger(x) || !isInteger(y)) {
throw new Error('Integers expected in function bitXor');
}
return x ^ y;
},
'BigNumber, BigNumber': bigBitXor,
'Matrix, Matrix': function (x, y) {
// result
var c;
// process matrix storage
switch (x.storage()) {
case 'sparse':
switch (y.storage()) {
case 'sparse':
// sparse + sparse
c = algorithm07(x, y, bitXor);
break;
default:
// sparse + dense
c = algorithm03(y, x, bitXor, true);
break;
}
break;
default:
switch (y.storage()) {
case 'sparse':
// dense + sparse
c = algorithm03(x, y, bitXor, false);
break;
default:
// dense + dense
c = algorithm13(x, y, bitXor);
break;
}
break;
}
return c;
},
'Array, Array': function (x, y) {
// use matrix implementation
return bitXor(matrix(x), matrix(y)).valueOf();
},
'Array, Matrix': function (x, y) {
// use matrix implementation
return bitXor(matrix(x), y);
},
'Matrix, Array': function (x, y) {
// use matrix implementation
return bitXor(x, matrix(y));
},
'Matrix, any': function (x, y) {
// result
var c;
// check storage format
switch (x.storage()) {
case 'sparse':
c = algorithm12(x, y, bitXor, false);
break;
default:
c = algorithm14(x, y, bitXor, false);
break;
}
return c;
},
'any, Matrix': function (x, y) {
// result
var c;
// check storage format
switch (y.storage()) {
case 'sparse':
c = algorithm12(y, x, bitXor, true);
break;
default:
c = algorithm14(y, x, bitXor, true);
break;
}
return c;
},
'Array, any': function (x, y) {
// use matrix implementation
return algorithm14(matrix(x), y, bitXor, false).valueOf();
},
'any, Array': function (x, y) {
// use matrix implementation
return algorithm14(matrix(y), x, bitXor, true).valueOf();
}
});
bitXor.toTex = {
2: '\\left(${args[0]}' + latex.operators['bitXor'] + '${args[1]}\\right)'
};
return bitXor;
}
n/a
function factory(type, config, load, typed) {
/**
* Create a boolean or convert a string or number to a boolean.
* In case of a number, `true` is returned for non-zero numbers, and `false` in
* case of zero.
* Strings can be `'true'` or `'false'`, or can contain a number.
* When value is a matrix, all elements will be converted to boolean.
*
* Syntax:
*
* math.boolean(x)
*
* Examples:
*
* math.boolean(0); // returns false
* math.boolean(1); // returns true
* math.boolean(-3); // returns true
* math.boolean('true'); // returns true
* math.boolean('false'); // returns false
* math.boolean([1, 0, 1, 1]); // returns [true, false, true, true]
*
* See also:
*
* bignumber, complex, index, matrix, string, unit
*
* @param {string | number | boolean | Array | Matrix | null} value A value of any type
* @return {boolean | Array | Matrix} The boolean value
*/
var bool = typed('bool', {
'': function () {
return false;
},
'boolean': function (x) {
return x;
},
'number': function (x) {
return !!x;
},
'BigNumber': function (x) {
return !x.isZero();
},
'string': function (x) {
// try case insensitive
var lcase = x.toLowerCase();
if (lcase === 'true') {
return true;
}
else if (lcase === 'false') {
return false;
}
// test whether value is a valid number
var num = Number(x);
if (x != '' && !isNaN(num)) {
return !!num;
}
throw new Error('Cannot convert "' + x + '" to a boolean');
},
'Array | Matrix': function (x) {
return deepMap(x, bool);
}
});
return bool;
}
n/a
function factory(type, config, load, typed) {
var add = load(require('../arithmetic/add'));
var divide = load(require('../arithmetic/divide'));
var multiply = load(require('../arithmetic/multiply'));
var combinations = load(require('../probability/combinations'));
var isNegative = load(require('../utils/isNegative'));
var isInteger = load(require('../utils/isInteger'));
/**
* The Catalan Numbers enumerate combinatorial structures of many different types.
* catalan only takes integer arguments.
* The following condition must be enforced: n >= 0
*
* Syntax:
*
* math.catalan(n)
*
* Examples:
*
* math.catalan(3); // returns 5;
* math.catalan(8); // returns 1430;
*
* See also:
*
* bellNumbers
*
* @param {Number | BigNumber} n nth Catalan number
* @return {Number | BigNumber} Cn(n)
*/
var catalan = typed('catalan', {
'number | BigNumber': function (n) {
if (!isInteger(n) || isNegative(n)) {
throw new TypeError('Non-negative integer value expected in function catalan');
}
return divide(combinations(multiply(n,2), n), add(n,1));
}
});
catalan.toTex = {1: '\\mathrm{C}_{${args[0]}}'};
return catalan;
}
n/a
function factory(type, config, load, typed) {
var unaryMinus = load(require('./unaryMinus'));
var isNegative = load(require('../utils/isNegative'));
var matrix = load(require('../../type/matrix/function/matrix'));
/**
* Calculate the cubic root of a value.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.cbrt(x)
* math.cbrt(x, allRoots)
*
* Examples:
*
* math.cbrt(27); // returns 3
* math.cube(3); // returns 27
* math.cbrt(-64); // returns -4
* math.cbrt(math.unit('27 m^3')); // returns Unit 3 m
* math.cbrt([27, 64, 125]); // returns [3, 4, 5]
*
* var x = math.complex('8i');
* math.cbrt(x); // returns Complex 1.7320508075689 + i
* math.cbrt(x, true); // returns Matrix [
* // 1.7320508075689 + i
* // -1.7320508075689 + i
* // -2i
* // ]
*
* See also:
*
* square, sqrt, cube
*
* @param {number | BigNumber | Complex | Unit | Array | Matrix} x
* Value for which to calculate the cubic root.
* @param {boolean} [allRoots] Optional, false by default. Only applicable
* when `x` is a number or complex number. If true, all complex
* roots are returned, if false (default) the principal root is
* returned.
* @return {number | BigNumber | Complex | Unit | Array | Matrix}
* Returns the cubic root of `x`
*/
var cbrt = typed('cbrt', {
'number': _cbrtNumber,
// note: signature 'number, boolean' is also supported,
// created by typed as it knows how to convert number to Complex
'Complex': _cbrtComplex,
'Complex, boolean': _cbrtComplex,
'BigNumber': function (x) {
return x.cbrt();
},
'Unit': _cbrtUnit,
'Array | Matrix': function (x) {
// deep map collection, skip zeros since cbrt(0) = 0
return deepMap(x, cbrt, true);
}
});
/**
* Calculate the cubic root for a complex number
* @param {Complex} x
* @param {boolean} [allRoots] If true, the function will return an array
* with all three roots. If false or undefined,
* the principal root is returned.
* @returns {Complex | Array.<Complex> | Matrix.<Complex>} Returns the cubic root(s) of x
* @private
*/
function _cbrtComplex(x, allRoots) {
// https://www.wikiwand.com/en/Cube_root#/Complex_numbers
var arg_3 = x.arg() / 3;
var abs = x.abs();
// principal root:
var principal = new type.Complex(_cbrtNumber(abs), 0).mul(
new type.Complex(0, arg_3).exp());
if (allRoots) {
var all = [
principal,
new type.Complex(_cbrtNumber(abs), 0).mul(
new type.Complex(0, arg_3 + Math.PI * 2 / 3).exp()),
new type.Complex(_cbrtNumber(abs), 0).mul(
new type.Complex(0, arg_3 - Math.PI * 2 / 3).exp())
];
return (config.matrix === 'Array') ? all : matrix(all);
}
else {
return principal;
}
}
/**
* Calculate the cubic root for a Unit
* @param {Unit} x
* @return {Unit} Returns the cubic root of x
* @private
*/
function _cbrtUnit(x) {
if(x.value && x.value.isComplex) {
var result = x.clone();
result.value = 1.0;
result = result.pow(1.0/3); // Compute the units
result.value = _cbrtComplex(x.value); // Compute the value
return result;
}
else {
var negate = isNegative(x.value);
if (negate) {
x.value = unaryMinus(x.value);
}
// TODO: create a helper function for this
var third;
if (x.value && x.value.isBigNumber) {
third = new type.BigNumber(1).div(3);
}
else if (x.value && x.value.isFraction) {
third = new type.Fraction(1, 3);
} ...
n/a
function factory(type, config, load, typed) {
/**
* Round a value towards plus infinity
* If `x` is complex, both real and imaginary part are rounded towards plus infinity.
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.ceil(x)
*
* Examples:
*
* math.ceil(3.2); // returns number 4
* math.ceil(3.8); // returns number 4
* math.ceil(-4.2); // returns number -4
* math.ceil(-4.7); // returns number -4
*
* var c = math.complex(3.2, -2.7);
* math.ceil(c); // returns Complex 4 - 2i
*
* math.ceil([3.2, 3.8, -4.7]); // returns Array [4, 4, -4]
*
* See also:
*
* floor, fix, round
*
* @param {number | BigNumber | Fraction | Complex | Array | Matrix} x Number to be rounded
* @return {number | BigNumber | Fraction | Complex | Array | Matrix} Rounded value
*/
var ceil = typed('ceil', {
'number': Math.ceil,
'Complex': function (x) {
return x.ceil();
},
'BigNumber': function (x) {
return x.ceil();
},
'Fraction': function (x) {
return x.ceil();
},
'Array | Matrix': function (x) {
// deep map collection, skip zeros since ceil(0) = 0
return deepMap(x, ceil, true);
}
});
ceil.toTex = {1: '\\left\\lceil${args[0]}\\right\\rceil'};
return ceil;
}
n/a
function factory(type, config, load, typed) {
/**
* Clone an object.
*
* Syntax:
*
* math.clone(x)
*
* Examples:
*
* math.clone(3.5); // returns number 3.5
* math.clone(math.complex('2-4i'); // returns Complex 2 - 4i
* math.clone(math.unit(45, 'deg')); // returns Unit 45 deg
* math.clone([[1, 2], [3, 4]]); // returns Array [[1, 2], [3, 4]]
* math.clone("hello world"); // returns string "hello world"
*
* @param {*} x Object to be cloned
* @return {*} A clone of object x
*/
var clone = typed('clone', {
'any': object.clone
});
clone.toTex = undefined; // use default template
return clone;
}
n/a
function factory(type, config, load, typed) {
/**
* Compute the number of ways of picking `k` unordered outcomes from `n`
* possibilities.
*
* Combinations only takes integer arguments.
* The following condition must be enforced: k <= n.
*
* Syntax:
*
* math.combinations(n, k)
*
* Examples:
*
* math.combinations(7, 5); // returns 21
*
* See also:
*
* permutations, factorial
*
* @param {number | BigNumber} n Total number of objects in the set
* @param {number | BigNumber} k Number of objects in the subset
* @return {number | BigNumber} Number of possible combinations.
*/
var combinations = typed('combinations', {
'number, number': function (n, k) {
var max, result, i;
if (!isInteger(n) || n < 0) {
throw new TypeError('Positive integer value expected in function combinations');
}
if (!isInteger(k) || k < 0) {
throw new TypeError('Positive integer value expected in function combinations');
}
if (k > n) {
throw new TypeError('k must be less than or equal to n');
}
max = Math.max(k, n - k);
result = 1;
for (i = 1; i <= n - max; i++) {
result = result * (max + i) / i;
}
return result;
},
'BigNumber, BigNumber': function (n, k) {
var max, result, i, ii;
var one = new type.BigNumber(1);
if (!isPositiveInteger(n) || !isPositiveInteger(k)) {
throw new TypeError('Positive integer value expected in function combinations');
}
if (k.gt(n)) {
throw new TypeError('k must be less than n in function combinations');
}
max = n.minus(k);
if (k.lt(max)) max = k;
result = one;
for (i = one, ii = n.minus(max); i.lte(ii); i = i.plus(1)) {
result = result.times(max.plus(i)).dividedBy(i);
}
return result;
}
// TODO: implement support for collection in combinations
});
combinations.toTex = {2: '\\binom{${args[0]}}{${args[1]}}'};
return combinations;
}
n/a
function factory(type, config, load, typed) {
var matrix = load(require('../../type/matrix/function/matrix'));
var algorithm03 = load(require('../../type/matrix/utils/algorithm03'));
var algorithm05 = load(require('../../type/matrix/utils/algorithm05'));
var algorithm12 = load(require('../../type/matrix/utils/algorithm12'));
var algorithm13 = load(require('../../type/matrix/utils/algorithm13'));
var algorithm14 = load(require('../../type/matrix/utils/algorithm14'));
/**
* Compare two values. Returns 1 when x > y, -1 when x < y, and 0 when x == y.
*
* x and y are considered equal when the relative difference between x and y
* is smaller than the configured epsilon. The function cannot be used to
* compare values smaller than approximately 2.22e-16.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.compare(x, y)
*
* Examples:
*
* math.compare(6, 1); // returns 1
* math.compare(2, 3); // returns -1
* math.compare(7, 7); // returns 0
*
* var a = math.unit('5 cm');
* var b = math.unit('40 mm');
* math.compare(a, b); // returns 1
*
* math.compare(2, [1, 2, 3]); // returns [1, 0, -1]
*
* See also:
*
* equal, unequal, smaller, smallerEq, larger, largerEq
*
* @param {number | BigNumber | Fraction | Unit | string | Array | Matrix} x First value to compare
* @param {number | BigNumber | Fraction | Unit | string | Array | Matrix} y Second value to compare
* @return {number | BigNumber | Fraction | Array | Matrix} Returns the result of the comparison: 1, 0 or -1.
*/
var compare = typed('compare', {
'boolean, boolean': function (x, y) {
return x === y ? 0 : (x > y ? 1 : -1);
},
'number, number': function (x, y) {
return (x === y || nearlyEqual(x, y, config.epsilon))
? 0
: (x > y ? 1 : -1);
},
'BigNumber, BigNumber': function (x, y) {
return (x.eq(y) || bigNearlyEqual(x, y, config.epsilon))
? new type.BigNumber(0)
: new type.BigNumber(x.cmp(y));
},
'Fraction, Fraction': function (x, y) {
return new type.Fraction(x.compare(y));
},
'Complex, Complex': function () {
throw new TypeError('No ordering relation is defined for complex numbers');
},
'Unit, Unit': function (x, y) {
if (!x.equalBase(y)) {
throw new Error('Cannot compare units with different base');
}
return compare(x.value, y.value);
},
'string, string': function (x, y) {
return x === y ? 0 : (x > y ? 1 : -1);
},
'Matrix, Matrix': function (x, y) {
// result
var c;
// process matrix storage
switch (x.storage()) {
case 'sparse':
switch (y.storage()) {
case 'sparse':
// sparse + sparse
c = algorithm05(x, y, compare);
break;
default:
// sparse + dense
c = algorithm03(y, x, compare, true);
break;
}
break;
default:
switch (y.storage()) {
case 'sparse':
// dense + sparse
c = algorithm03(x, y, compare, false);
break;
default:
// dense + dense
c = algorithm13(x, y, compare);
break;
}
break;
}
return c;
},
'Array, Array': function (x, y) {
// use matrix implementation
return compare(matrix(x), matrix(y)).valueOf();
},
'Array, Matrix': function (x, y) {
// use matrix implementation
return compare(matrix(x), y);
},
'Matrix, Array': function (x, y) {
// use matrix implementation
return compare(x, matrix(y));
},
'Matrix, any': function (x, y) {
// result
var c;
// check storage format
switch (x.storage()) {
case 'sparse':
c = algorithm12(x, y, compare, false);
break; ...
n/a
function factory(type, config, load, typed) {
var parse = load(require('../parse'));
/**
* Parse and compile an expression.
* Returns a an object with a function `eval([scope])` to evaluate the
* compiled expression.
*
* Syntax:
*
* math.compile(expr) // returns one node
* math.compile([expr1, expr2, expr3, ...]) // returns an array with nodes
*
* Examples:
*
* var code = math.compile('sqrt(3^2 + 4^2)');
* code.eval(); // 5
*
* var scope = {a: 3, b: 4}
* var code = math.compile('a * b'); // 12
* code.eval(scope); // 12
* scope.a = 5;
* code.eval(scope); // 20
*
* var nodes = math.compile(['a = 3', 'b = 4', 'a * b']);
* nodes[2].eval(); // 12
*
* See also:
*
* parse, eval
*
* @param {string | string[] | Array | Matrix} expr
* The expression to be compiled
* @return {{eval: Function} | Array.<{eval: Function}>} code
* An object with the compiled expression
* @throws {Error}
*/
return typed('compile', {
'string': function (expr) {
return parse(expr).compile();
},
'Array | Matrix': function (expr) {
return deepMap(expr, function (entry) {
return parse(entry).compile();
});
}
});
}
n/a
function factory(type, config, load, typed) {
var combinations = load(require('../probability/combinations'));
var add = load(require('../arithmetic/addScalar'));
var isPositive = load(require('../utils/isPositive'));
var isInteger = load(require('../utils/isInteger'));
var larger = load(require('../relational/larger'));
/**
* The composition counts of n into k parts.
*
* composition only takes integer arguments.
* The following condition must be enforced: k <= n.
*
* Syntax:
*
* math.composition(n, k)
*
* Examples:
*
* math.composition(5, 3); // returns 6
*
* See also:
*
* combinations
*
* @param {Number | BigNumber} n Total number of objects in the set
* @param {Number | BigNumber} k Number of objects in the subset
* @return {Number | BigNumber} Returns the composition counts of n into k parts.
*/
var composition = typed('composition', {
'number | BigNumber, number | BigNumber': function (n, k) {
if (!isInteger(n) || !isPositive(n) || !isInteger(k) || !isPositive(k)) {
throw new TypeError('Positive integer value expected in function composition');
}
else if (larger(k, n)) {
throw new TypeError('k must be less than or equal to n in function composition');
}
return combinations(add(n, -1), add(k, -1));
}
});
composition.toTex = undefined; // use default template
return composition;
}
n/a
function factory(type, config, load, typed) {
var matrix = load(require('../../type/matrix/function/matrix'));
/**
* Concatenate two or more matrices.
*
* Syntax:
*
* math.concat(A, B, C, ...)
* math.concat(A, B, C, ..., dim)
*
* Where:
*
* - `dim: number` is a zero-based dimension over which to concatenate the matrices.
* By default the last dimension of the matrices.
*
* Examples:
*
* var A = [[1, 2], [5, 6]];
* var B = [[3, 4], [7, 8]];
*
* math.concat(A, B); // returns [[1, 2, 3, 4], [5, 6, 7, 8]]
* math.concat(A, B, 0); // returns [[1, 2], [5, 6], [3, 4], [7, 8]]
* math.concat('hello', ' ', 'world'); // returns 'hello world'
*
* See also:
*
* size, squeeze, subset, transpose
*
* @param {... Array | Matrix} args Two or more matrices
* @return {Array | Matrix} Concatenated matrix
*/
var concat = typed('concat', {
// TODO: change signature to '...Array | Matrix, dim?' when supported
'...Array | Matrix | number | BigNumber': function (args) {
var i;
var len = args.length;
var dim = -1; // zero-based dimension
var prevDim;
var asMatrix = false;
var matrices = []; // contains multi dimensional arrays
for (i = 0; i < len; i++) {
var arg = args[i];
// test whether we need to return a Matrix (if not we return an Array)
if (arg && arg.isMatrix === true) {
asMatrix = true;
}
if (typeof arg === 'number' || (arg && arg.isBigNumber === true)) {
if (i !== len - 1) {
throw new Error('Dimension must be specified as last argument');
}
// last argument contains the dimension on which to concatenate
prevDim = dim;
dim = arg.valueOf(); // change BigNumber to number
if (!isInteger(dim)) {
throw new TypeError('Integer number expected for dimension');
}
if (dim < 0 || (i > 0 && dim > prevDim)) {
// TODO: would be more clear when throwing a DimensionError here
throw new IndexError(dim, prevDim + 1);
}
}
else {
// this is a matrix or array
var m = clone(arg).valueOf();
var size = array.size(m);
matrices[i] = m;
prevDim = dim;
dim = size.length - 1;
// verify whether each of the matrices has the same number of dimensions
if (i > 0 && dim != prevDim) {
throw new DimensionError(prevDim + 1, dim + 1);
}
}
}
if (matrices.length == 0) {
throw new SyntaxError('At least one matrix expected');
}
var res = matrices.shift();
while (matrices.length) {
res = _concat(res, matrices.shift(), dim, 0);
}
return asMatrix ? matrix(res) : res;
},
'...string': function (args) {
return args.join('');
}
});
concat.toTex = undefined; // use default template
return concat;
}
n/a
function factory(type, config, load, typed) { var concat = load(require('../../function/matrix/concat')); // @see: comment of concat itself return typed('concat', { '...any': function (args) { // change last argument from one-based to zero-based var lastIndex = args.length - 1; var last = args[lastIndex]; if (typeof last === 'number') { args[lastIndex] = last - 1; } else if (last && last.isBigNumber === true) { args[lastIndex] = last.minus(1); } try { return concat.apply(null, args); } catch (err) { throw errorTransform(err); } } }); }
n/a
function factory(type, config, load, typed, math) {
var MATRIX = ['Matrix', 'Array']; // valid values for option matrix
var NUMBER = ['number', 'BigNumber', 'Fraction']; // valid values for option number
/**
* Set configuration options for math.js, and get current options.
* Will emit a 'config' event, with arguments (curr, prev, changes).
*
* Syntax:
*
* math.config(config: Object): Object
*
* Examples:
*
* math.config().number; // outputs 'number'
* math.eval('0.4'); // outputs number 0.4
* math.config({number: 'Fraction'});
* math.eval('0.4'); // outputs Fraction 2/5
*
* @param {Object} [options] Available options:
* {number} epsilon
* Minimum relative difference between two
* compared values, used by all comparison functions.
* {string} matrix
* A string 'Matrix' (default) or 'Array'.
* {string} number
* A string 'number' (default), 'BigNumber', or 'Fraction'
* {number} precision
* The number of significant digits for BigNumbers.
* Not applicable for Numbers.
* {string} parenthesis
* How to display parentheses in LaTeX and string
* output.
* {string} randomSeed
* Random seed for seeded pseudo random number generator.
* Set to null to randomly seed.
* @return {Object} Returns the current configuration
*/
function _config(options) {
if (options) {
var prev = object.clone(config);
// validate some of the options
validateOption(options, 'matrix', MATRIX);
validateOption(options, 'number', NUMBER);
// merge options
object.deepExtend(config, options);
var curr = object.clone(config);
var changes = object.clone(options);
// emit 'config' event
math.emit('config', curr, prev, changes);
return curr;
}
else {
return object.clone(config);
}
}
// attach the valid options to the function so they can be extended
_config.MATRIX = MATRIX;
_config.NUMBER = NUMBER;
return _config;
}
n/a
function factory(type, config, load, typed) {
/**
* Compute the complex conjugate of a complex value.
* If `x = a+bi`, the complex conjugate of `x` is `a - bi`.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.conj(x)
*
* Examples:
*
* math.conj(math.complex('2 + 3i')); // returns Complex 2 - 3i
* math.conj(math.complex('2 - 3i')); // returns Complex 2 + 3i
* math.conj(math.complex('-5.2i')); // returns Complex 5.2i
*
* See also:
*
* re, im, arg, abs
*
* @param {number | BigNumber | Complex | Array | Matrix} x
* A complex number or array with complex numbers
* @return {number | BigNumber | Complex | Array | Matrix}
* The complex conjugate of x
*/
var conj = typed('conj', {
'number': function (x) {
return x;
},
'BigNumber': function (x) {
return x;
},
'Complex': function (x) {
return x.conjugate();
},
'Array | Matrix': function (x) {
return deepMap(x, conj);
}
});
conj.toTex = {1: '\\left(${args[0]}\\right)^*'};
return conj;
}
n/a
function factory(type, config, load, typed, math) { // listen for changed in the configuration, automatically reload // constants when needed math.on('config', function (curr, prev) { if (curr.number !== prev.number) { factory(type, config, load, typed, math); } }); setConstant(math, 'true', true); setConstant(math, 'false', false); setConstant(math, 'null', null); setConstant(math, 'uninitialized', require('./utils/array').UNINITIALIZED); if (config.number === 'BigNumber') { setConstant(math, 'Infinity', new type.BigNumber(Infinity)); setConstant(math, 'NaN', new type.BigNumber(NaN)); setLazyConstant(math, 'pi', function () {return bigConstants.pi(type.BigNumber)}); setLazyConstant(math, 'tau', function () {return bigConstants.tau(type.BigNumber)}); setLazyConstant(math, 'e', function () {return bigConstants.e(type.BigNumber)}); setLazyConstant(math, 'phi', function () {return bigConstants.phi(type.BigNumber)}); // golden ratio, (1+sqrt(5))/2 // uppercase constants (for compatibility with built-in Math) setLazyConstant(math, 'E', function () {return math.e;}); setLazyConstant(math, 'LN2', function () {return new type.BigNumber(2).ln();}); setLazyConstant(math, 'LN10', function () {return new type.BigNumber(10).ln()}); setLazyConstant(math, 'LOG2E', function () {return new type.BigNumber(1).div(new type.BigNumber(2).ln());}); setLazyConstant(math, 'LOG10E', function () {return new type.BigNumber(1).div(new type.BigNumber(10).ln())}); setLazyConstant(math, 'PI', function () {return math.pi}); setLazyConstant(math, 'SQRT1_2', function () {return new type.BigNumber('0.5').sqrt()}); setLazyConstant(math, 'SQRT2', function () {return new type.BigNumber(2).sqrt()}); } else { setConstant(math, 'Infinity', Infinity); setConstant(math, 'NaN', NaN); setConstant(math, 'pi', Math.PI); setConstant(math, 'tau', Math.PI * 2); setConstant(math, 'e', Math.E); setConstant(math, 'phi', 1.61803398874989484820458683436563811772030917980576286213545); // golden ratio, (1+sqrt(5))/2 // uppercase constants (for compatibility with built-in Math) setConstant(math, 'E', math.e); setConstant(math, 'LN2', Math.LN2); setConstant(math, 'LN10', Math.LN10); setConstant(math, 'LOG2E', Math.LOG2E); setConstant(math, 'LOG10E', Math.LOG10E); setConstant(math, 'PI', math.pi); setConstant(math, 'SQRT1_2', Math.SQRT1_2); setConstant(math, 'SQRT2', Math.SQRT2); } // complex i setConstant(math, 'i', type.Complex.I); // meta information setConstant(math, 'version', require('./version')); }
n/a
function create(options) {
// simple test for ES5 support
if (typeof Object.create !== 'function') {
throw new Error('ES5 not supported by this JavaScript engine. ' +
'Please load the es5-shim and es5-sham library for compatibility.');
}
// cached factories and instances
var factories = [];
var instances = [];
// create a namespace for the mathjs instance, and attach emitter functions
var math = emitter.mixin({});
math.type = {};
math.expression = {
transform: {},
mathWithTransform: {}
};
// create a new typed instance
math.typed = typedFactory.create(math.type);
// create configuration options. These are private
var _config = {
// minimum relative difference between two compared values,
// used by all comparison functions
epsilon: 1e-12,
// type of default matrix output. Choose 'matrix' (default) or 'array'
matrix: 'Matrix',
// type of default number output. Choose 'number' (default) 'BigNumber', or 'Fraction
number: 'number',
// number of significant digits in BigNumbers
precision: 64,
// predictable output type of functions. When true, output type depends only
// on the input types. When false (default), output type can vary depending
// on input values. For example `math.sqrt(-4)` returns `complex('2i')` when
// predictable is false, and returns `NaN` when true.
predictable: false,
// random seed for seeded pseudo random number generation
// null = randomly seed
randomSeed: null
};
/**
* Load a function or data type from a factory.
* If the function or data type already exists, the existing instance is
* returned.
* @param {{type: string, name: string, factory: Function}} factory
* @returns {*}
*/
function load (factory) {
if (!isFactory(factory)) {
throw new Error('Factory object with properties `type`, `name`, and `factory` expected');
}
var index = factories.indexOf(factory);
var instance;
if (index === -1) {
// doesn't yet exist
if (factory.math === true) {
// pass with math namespace
instance = factory.factory(math.type, _config, load, math.typed, math);
}
else {
instance = factory.factory(math.type, _config, load, math.typed);
}
// append to the cache
factories.push(factory);
instances.push(instance);
}
else {
// already existing function, return the cached instance
instance = instances[index];
}
return instance;
}
// load the import and config functions
math['import'] = load(importFactory);
math['config'] = load(configFactory);
math.expression.mathWithTransform['config'] = math['config']
// apply options
if (options) {
math.config(options);
}
return math;
}
...
* false (default), output type can vary depending
* on input values. For example `math.sqrt(-4)`
* returns `complex('2i')` when predictable is false, and
* returns `NaN` when true.
*/
function create (config) {
// create a new math.js instance
var math = core.create(config);
math.create = create;
// import data types, functions, constants, expression parser, etc.
math['import'](require('./lib'));
return math;
}
...
function factory(type, config, load, typed) {
/**
* Calculate the cosine of a value.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.cos(x)
*
* Examples:
*
* math.cos(2); // returns number -0.4161468365471422
* math.cos(math.pi / 4); // returns number 0.7071067811865475
* math.cos(math.unit(180, 'deg')); // returns number -1
* math.cos(math.unit(60, 'deg')); // returns number 0.5
*
* var angle = 0.2;
* math.pow(math.sin(angle), 2) + math.pow(math.cos(angle), 2); // returns number ~1
*
* See also:
*
* cos, tan
*
* @param {number | BigNumber | Complex | Unit | Array | Matrix} x Function input
* @return {number | BigNumber | Complex | Array | Matrix} Cosine of x
*/
var cos = typed('cos', {
'number': Math.cos,
'Complex': function (x) {
return x.cos();
},
'BigNumber': function (x) {
return x.cos();
},
'Unit': function (x) {
if (!x.hasBase(type.Unit.BASE_UNITS.ANGLE)) {
throw new TypeError ('Unit in function cos is no angle');
}
return cos(x.value);
},
'Array | Matrix': function (x) {
return deepMap(x, cos);
}
});
cos.toTex = {1: '\\cos\\left(${args[0]}\\right)'};
return cos;
}
n/a
function factory(type, config, load, typed) { /** * Calculate the hyperbolic cosine of a value, * defined as `cosh(x) = 1/2 * (exp(x) + exp(-x))`. * * For matrices, the function is evaluated element wise. * * Syntax: * * math.cosh(x) * * Examples: * * math.cosh(0.5); // returns number 1.1276259652063807 * * See also: * * sinh, tanh * * @param {number | BigNumber | Complex | Unit | Array | Matrix} x Function input * @return {number | BigNumber | Complex | Array | Matrix} Hyperbolic cosine of x */ var cosh = typed('cosh', { 'number': _cosh, 'Complex': function (x) { return x.cosh(); }, 'BigNumber': function (x) { return x.cosh(); }, 'Unit': function (x) { if (!x.hasBase(type.Unit.BASE_UNITS.ANGLE)) { throw new TypeError ('Unit in function cosh is no angle'); } return cosh(x.value); }, 'Array | Matrix': function (x) { return deepMap(x, cosh); } }); cosh.toTex = {1: '\\cosh\\left(${args[0]}\\right)'}; return cosh; }
n/a
function factory(type, config, load, typed) {
/**
* Calculate the cotangent of a value. Defined as `cot(x) = 1 / tan(x)`.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.cot(x)
*
* Examples:
*
* math.cot(2); // returns number -0.45765755436028577
* 1 / math.tan(2); // returns number -0.45765755436028577
*
* See also:
*
* tan, sec, csc
*
* @param {number | Complex | Unit | Array | Matrix} x Function input
* @return {number | Complex | Array | Matrix} Cotangent of x
*/
var cot = typed('cot', {
'number': function (x) {
return 1 / Math.tan(x);
},
'Complex': function (x) {
return x.cot();
},
'BigNumber': function (x) {
return new type.BigNumber(1).div(x.tan());
},
'Unit': function (x) {
if (!x.hasBase(type.Unit.BASE_UNITS.ANGLE)) {
throw new TypeError ('Unit in function cot is no angle');
}
return cot(x.value);
},
'Array | Matrix': function (x) {
return deepMap(x, cot);
}
});
cot.toTex = {1: '\\cot\\left(${args[0]}\\right)'};
return cot;
}
n/a
function factory(type, config, load, typed) { /** * Calculate the hyperbolic cotangent of a value, * defined as `coth(x) = 1 / tanh(x)`. * * For matrices, the function is evaluated element wise. * * Syntax: * * math.coth(x) * * Examples: * * // coth(x) = 1 / tanh(x) * math.coth(2); // returns 1.0373147207275482 * 1 / math.tanh(2); // returns 1.0373147207275482 * * See also: * * sinh, tanh, cosh * * @param {number | Complex | Unit | Array | Matrix} x Function input * @return {number | Complex | Array | Matrix} Hyperbolic cotangent of x */ var coth = typed('coth', { 'number': _coth, 'Complex': function (x) { return x.coth(); }, 'BigNumber': function (x) { return new type.BigNumber(1).div(x.tanh()); }, 'Unit': function (x) { if (!x.hasBase(type.Unit.BASE_UNITS.ANGLE)) { throw new TypeError ('Unit in function coth is no angle'); } return coth(x.value); }, 'Array | Matrix': function (x) { return deepMap(x, coth); } }); coth.toTex = {1: '\\coth\\left(${args[0]}\\right)'}; return coth; }
n/a
function factory(type, config, load, typed) {
var matrix = load(require('../../type/matrix/function/matrix'));
var subtract = load(require('../arithmetic/subtract'));
var multiply = load(require('../arithmetic/multiply'));
/**
* Calculate the cross product for two vectors in three dimensional space.
* The cross product of `A = [a1, a2, a3]` and `B = [b1, b2, b3]` is defined
* as:
*
* cross(A, B) = [
* a2 * b3 - a3 * b2,
* a3 * b1 - a1 * b3,
* a1 * b2 - a2 * b1
* ]
*
* If one of the input vectors has a dimension greater than 1, the output
* vector will be a 1x3 (2-dimensional) matrix.
*
* Syntax:
*
* math.cross(x, y)
*
* Examples:
*
* math.cross([1, 1, 0], [0, 1, 1]); // Returns [1, -1, 1]
* math.cross([3, -3, 1], [4, 9, 2]); // Returns [-15, -2, 39]
* math.cross([2, 3, 4], [5, 6, 7]); // Returns [-3, 6, -3]
* math.cross([[1, 2, 3]], [[4], [5], [6]]); // Returns [[-3, 6, -3]]
*
* See also:
*
* dot, multiply
*
* @param {Array | Matrix} x First vector
* @param {Array | Matrix} y Second vector
* @return {Array | Matrix} Returns the cross product of `x` and `y`
*/
var cross = typed('cross', {
'Matrix, Matrix': function (x, y) {
return matrix(_cross(x.toArray(), y.toArray()));
},
'Matrix, Array': function (x, y) {
return matrix(_cross(x.toArray(), y));
},
'Array, Matrix': function (x, y) {
return matrix(_cross(x, y.toArray()));
},
'Array, Array': _cross
});
cross.toTex = {
2: '\\left(${args[0]}\\right)\\times\\left(${args[1]}\\right)'
};
return cross;
/**
* Calculate the cross product for two arrays
* @param {Array} x First vector
* @param {Array} y Second vector
* @returns {Array} Returns the cross product of x and y
* @private
*/
function _cross(x, y) {
var highestDimension = Math.max(array.size(x).length, array.size(y).length);
x = array.squeeze(x);
y = array.squeeze(y);
var xSize = array.size(x);
var ySize = array.size(y);
if (xSize.length != 1 || ySize.length != 1 || xSize[0] != 3 || ySize[0] != 3) {
throw new RangeError('Vectors with length 3 expected ' +
'(Size A = [' + xSize.join(', ') + '], B = [' + ySize.join(', ') + '])');
}
var product = [
subtract(multiply(x[1], y[2]), multiply(x[2], y[1])),
subtract(multiply(x[2], y[0]), multiply(x[0], y[2])),
subtract(multiply(x[0], y[1]), multiply(x[1], y[0]))
];
if (highestDimension > 1) {
return [product];
} else {
return product;
}
}
}
n/a
function factory(type, config, load, typed) {
/**
* Calculate the cosecant of a value, defined as `csc(x) = 1/sin(x)`.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.csc(x)
*
* Examples:
*
* math.csc(2); // returns number 1.099750170294617
* 1 / math.sin(2); // returns number 1.099750170294617
*
* See also:
*
* sin, sec, cot
*
* @param {number | Complex | Unit | Array | Matrix} x Function input
* @return {number | Complex | Array | Matrix} Cosecant of x
*/
var csc = typed('csc', {
'number': function (x) {
return 1 / Math.sin(x);
},
'Complex': function (x) {
return x.csc();
},
'BigNumber': function (x) {
return new type.BigNumber(1).div(x.sin());
},
'Unit': function (x) {
if (!x.hasBase(type.Unit.BASE_UNITS.ANGLE)) {
throw new TypeError ('Unit in function csc is no angle');
}
return csc(x.value);
},
'Array | Matrix': function (x) {
return deepMap(x, csc);
}
});
csc.toTex = {1: '\\csc\\left(${args[0]}\\right)'};
return csc;
}
n/a
function factory(type, config, load, typed) { /** * Calculate the hyperbolic cosecant of a value, * defined as `csch(x) = 1 / sinh(x)`. * * For matrices, the function is evaluated element wise. * * Syntax: * * math.csch(x) * * Examples: * * // csch(x) = 1/ sinh(x) * math.csch(0.5); // returns 1.9190347513349437 * 1 / math.sinh(0.5); // returns 1.9190347513349437 * * See also: * * sinh, sech, coth * * @param {number | Complex | Unit | Array | Matrix} x Function input * @return {number | Complex | Array | Matrix} Hyperbolic cosecant of x */ var csch = typed('csch', { 'number': _csch, 'Complex': function (x) { return x.csch(); }, 'BigNumber': function (x) { return new type.BigNumber(1).div(x.sinh()); }, 'Unit': function (x) { if (!x.hasBase(type.Unit.BASE_UNITS.ANGLE)) { throw new TypeError ('Unit in function csch is no angle'); } return csch(x.value); }, 'Array | Matrix': function (x) { return deepMap(x, csch); } }); csch.toTex = {1: '\\mathrm{csch}\\left(${args[0]}\\right)'}; return csch; }
n/a
function factory(type, config, load, typed) {
/**
* Compute the cube of a value, `x * x * x`.
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.cube(x)
*
* Examples:
*
* math.cube(2); // returns number 8
* math.pow(2, 3); // returns number 8
* math.cube(4); // returns number 64
* 4 * 4 * 4; // returns number 64
*
* math.cube([1, 2, 3, 4]); // returns Array [1, 8, 27, 64]
*
* See also:
*
* multiply, square, pow, cbrt
*
* @param {number | BigNumber | Fraction | Complex | Array | Matrix | Unit} x Number for which to calculate the cube
* @return {number | BigNumber | Fraction | Complex | Array | Matrix | Unit} Cube of x
*/
var cube = typed('cube', {
'number': function (x) {
return x * x * x;
},
'Complex': function (x) {
return x.mul(x).mul(x); // Is faster than pow(x, 3)
},
'BigNumber': function (x) {
return x.times(x).times(x);
},
'Fraction': function (x) {
return x.pow(3); // Is faster than mul()mul()mul()
},
'Array | Matrix': function (x) {
// deep map collection, skip zeros since cube(0) = 0
return deepMap(x, cube, true);
},
'Unit': function(x) {
return x.pow(3);
}
});
cube.toTex = {1: '\\left(${args[0]}\\right)^3'};
return cube;
}
n/a
function factory(type, config, load, typed) {
var equal = load(require('./equal'));
/**
* Test element wise whether two matrices are equal.
* The function accepts both matrices and scalar values.
*
* Syntax:
*
* math.deepEqual(x, y)
*
* Examples:
*
* math.deepEqual(2, 4); // returns false
*
* a = [2, 5, 1];
* b = [2, 7, 1];
*
* math.deepEqual(a, b); // returns false
* math.equal(a, b); // returns [true, false, true]
*
* See also:
*
* equal, unequal
*
* @param {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} x First matrix to compare
* @param {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} y Second matrix to compare
* @return {number | BigNumber | Fraction | Complex | Unit | Array | Matrix}
* Returns true when the input matrices have the same size and each of their elements is equal.
*/
var deepEqual = typed('deepEqual', {
'any, any': function (x, y) {
return _deepEqual(x.valueOf(), y.valueOf());
}
});
deepEqual.toTex = undefined; // use default template
return deepEqual;
/**
* Test whether two arrays have the same size and all elements are equal
* @param {Array | *} x
* @param {Array | *} y
* @return {boolean} Returns true if both arrays are deep equal
*/
function _deepEqual(x, y) {
if (Array.isArray(x)) {
if (Array.isArray(y)) {
var len = x.length;
if (len !== y.length) {
return false;
}
for (var i = 0; i < len; i++) {
if (!_deepEqual(x[i], y[i])) {
return false;
}
}
return true;
}
else {
return false;
}
}
else {
if (Array.isArray(y)) {
return false;
}
else {
return equal(x, y);
}
}
}
}
n/a
function derivative(arg0, arg1, arg2) { "use strict"; var name = 'derivative'; if (test0(arg0)) { // type: string if (test0(arg1)) { // type: string if (arguments.length === 2) { return signature0(arg0, arg1); // signature: string, string } if (test1(arg2)) { // type: Object if (arguments.length === 3) { return signature1(arg0, arg1, arg2); // signature: string, string, Object } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } throw createError(name, arguments.length, 2, arguments[2], 'Object'); } if (test2(arg1)) { // type: SymbolNode if (arguments.length === 2) { return signature2(arg0, arg1); // signature: string, SymbolNode } if (test1(arg2)) { // type: Object if (arguments.length === 3) { return signature3(arg0, arg1, arg2); // signature: string, SymbolNode, Object } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } throw createError(name, arguments.length, 2, arguments[2], 'Object'); } if (test3(arg1)) { // type: number (convert to string) if (arguments.length === 2) { return signature0(arg0, convert0(arg1)); // signature: string, number } if (test1(arg2)) { // type: Object if (arguments.length === 3) { return signature1(arg0, convert0(arg1), arg2); // signature: string, number, Object } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } throw createError(name, arguments.length, 2, arguments[2], 'Object'); } if (test4(arg1)) { // type: boolean (convert to string) if (arguments.length === 2) { return signature0(arg0, convert1(arg1)); // signature: string, boolean } if (test1(arg2)) { // type: Object if (arguments.length === 3) { return signature1(arg0, convert1(arg1), arg2); // signature: string, boolean, Object } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } throw createError(name, arguments.length, 2, arguments[2], 'Object'); } if (test5(arg1)) { // type: null (convert to string) if (arguments.length === 2) { return signature0(arg0, convert2(arg1)); // signature: string, null } if (test1(arg2)) { // type: Object if (arguments.length === 3) { return signature1(arg0, convert2(arg1), arg2); // signature: string, null, Object } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } throw createError(name, arguments.length, 2, arguments[2], 'Object'); } throw createError(name, arguments.length, 1, arguments[1], 'string,SymbolNode'); } if (test6(arg0)) { // type: Node if (test0(arg1)) { // type: string if (arguments.length === 2) { return signature4(arg0, arg1); // signature: Node, string } if (test1(arg2)) { // type: Object if (arguments.length === 3) { return signature5(arg0, arg1, arg2); // signature: Node, string, Object } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } throw createError(name, arguments.length, 2, arguments[2], 'Object'); } if (test2(arg1)) { // type: SymbolNode if (arguments.length === 2) { return signature6(arg0, arg1); // signature: Node, SymbolNode } if (test1(arg2)) { // type: Object if (arguments.length === 3) { return signature7(arg0, arg1, arg2); // signature: Node, SymbolNode, Object } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } throw createError(name, arguments.length, 2, arguments[2], 'Object'); } if (t ...
...
// functions and constants
math.round(math.e, 3); // 2.718
math.atan2(3, -3) / math.pi; // 0.75
math.log(1000, 10); // 3
math.sqrt(-4); // 2i
math.pow([[-1, 2], [3, 1]], 2); // [[7, 0], [0, 7]]
math.derivative('x^2 + x', 'x'); // 2 * x + 1
// expressions
math.eval('12 / (2.3 + 0.7)'); // 4
math.eval('5.08 cm to inch'); // 2 inch
math.eval('sin(45 deg) ^ 2'); // 0.5
math.eval('9 / 3 + 2i'); // 3 + 2i
math.eval('det([-1, 2; 3, 1])'); // -7
...
toTex = function (deriv) { return _derivTex.apply(null, deriv.args); }
...
catch (err) {
console.log(err.toString());
}
break;
case 'tex':
try {
var tex = math.parse(expr).toTex({parenthesis: parenthesis});
console.log(tex);
}
catch (err) {
console.log(err.toString());
}
break;
}
...
function factory(type, config, load, typed) {
var matrix = load(require('../../type/matrix/function/matrix'));
var add = load(require('../arithmetic/add'));
var subtract = load(require('../arithmetic/subtract'));
var multiply = load(require('../arithmetic/multiply'));
var unaryMinus = load(require('../arithmetic/unaryMinus'));
/**
* Calculate the determinant of a matrix.
*
* Syntax:
*
* math.det(x)
*
* Examples:
*
* math.det([[1, 2], [3, 4]]); // returns -2
*
* var A = [
* [-2, 2, 3],
* [-1, 1, 3],
* [2, 0, -1]
* ]
* math.det(A); // returns 6
*
* See also:
*
* inv
*
* @param {Array | Matrix} x A matrix
* @return {number} The determinant of `x`
*/
var det = typed('det', {
'any': function (x) {
return object.clone(x);
},
'Array | Matrix': function det (x) {
var size;
if (x && x.isMatrix === true) {
size = x.size();
}
else if (Array.isArray(x)) {
x = matrix(x);
size = x.size();
}
else {
// a scalar
size = [];
}
switch (size.length) {
case 0:
// scalar
return object.clone(x);
case 1:
// vector
if (size[0] == 1) {
return object.clone(x.valueOf()[0]);
}
else {
throw new RangeError('Matrix must be square ' +
'(size: ' + string.format(size) + ')');
}
case 2:
// two dimensional array
var rows = size[0];
var cols = size[1];
if (rows == cols) {
return _det(x.clone().valueOf(), rows, cols);
}
else {
throw new RangeError('Matrix must be square ' +
'(size: ' + string.format(size) + ')');
}
default:
// multi dimensional array
throw new RangeError('Matrix must be two dimensional ' +
'(size: ' + string.format(size) + ')');
}
}
});
det.toTex = {1: '\\det\\left(${args[0]}\\right)'};
return det;
/**
* Calculate the determinant of a matrix
* @param {Array[]} matrix A square, two dimensional matrix
* @param {number} rows Number of rows of the matrix (zero-based)
* @param {number} cols Number of columns of the matrix (zero-based)
* @returns {number} det
* @private
*/
function _det (matrix, rows, cols) {
if (rows == 1) {
// this is a 1 x 1 matrix
return object.clone(matrix[0][0]);
}
else if (rows == 2) {
// this is a 2 x 2 matrix
// the determinant of [a11,a12;a21,a22] is det = a11*a22-a21*a12
return subtract(
multiply(matrix[0][0], matrix[1][1]),
multiply(matrix[1][0], matrix[0][1])
);
}
else {
// this is an n x n matrix
var compute_mu = function (matrix) {
var i, j;
// Compute the matrix with zero lower triangle, same upper triangle,
// and diagonals given by the negated sum of the below diagonal
// elements.
var mu = new Array(matrix.length);
var sum = 0;
for (i = 1; i < matrix.length; i++) {
sum = add(sum, matrix[i][i]);
}
for (i = 0; i < matrix.length; i++) {
mu[i] = new Array(matrix.length);
mu[i][i] = unaryMinus(sum);
for (j = 0; j < i; j++) {
mu[i][j] = 0; // TODO: make bignumber 0 in case of bignumber computation
}
for (j = i + 1; j < matrix.length; j++) {
mu[i][j] = matrix[i][j];
}
if (i+1 < matrix.length) {
sum = subtract(sum, matrix[i + 1][i + 1]);
}
}
return mu;
};
var fa = matrix;
for (var i = 0; i < rows - 1; i++) {
fa = multiply(compute_mu(fa), matrix);
}
if (rows % 2 == 0) {
return unaryMinus(fa[0][0]);
} else {
return fa[0][0];
}
}
}
}
n/a
function factory(type, config, load, typed) {
var matrix = load(require('../../type/matrix/function/matrix'));
/**
* Create a diagonal matrix or retrieve the diagonal of a matrix
*
* When `x` is a vector, a matrix with vector `x` on the diagonal will be returned.
* When `x` is a two dimensional matrix, the matrixes `k`th diagonal will be returned as vector.
* When k is positive, the values are placed on the super diagonal.
* When k is negative, the values are placed on the sub diagonal.
*
* Syntax:
*
* math.diag(X)
* math.diag(X, format)
* math.diag(X, k)
* math.diag(X, k, format)
*
* Examples:
*
* // create a diagonal matrix
* math.diag([1, 2, 3]); // returns [[1, 0, 0], [0, 2, 0], [0, 0, 3]]
* math.diag([1, 2, 3], 1); // returns [[0, 1, 0, 0], [0, 0, 2, 0], [0, 0, 0, 3]]
* math.diag([1, 2, 3], -1); // returns [[0, 0, 0], [1, 0, 0], [0, 2, 0], [0, 0, 3]]
*
* // retrieve the diagonal from a matrix
* var a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
* math.diag(a); // returns [1, 5, 9]
*
* See also:
*
* ones, zeros, eye
*
* @param {Matrix | Array} x A two dimensional matrix or a vector
* @param {number | BigNumber} [k=0] The diagonal where the vector will be filled
* in or retrieved.
* @param {string} [format='dense'] The matrix storage format.
*
* @returns {Matrix | Array} Diagonal matrix from input vector, or diagonal from input matrix.
*/
var diag = typed('diag', {
// FIXME: simplify this huge amount of signatures as soon as typed-function supports optional arguments
'Array': function (x) {
return _diag(x, 0, array.size(x), null);
},
'Array, number': function (x, k) {
return _diag(x, k, array.size(x), null);
},
'Array, BigNumber': function (x, k) {
return _diag(x, k.toNumber(), array.size(x), null);
},
'Array, string': function (x, format) {
return _diag(x, 0, array.size(x), format);
},
'Array, number, string': function (x, k, format) {
return _diag(x, k, array.size(x), format);
},
'Array, BigNumber, string': function (x, k, format) {
return _diag(x, k.toNumber(), array.size(x), format);
},
'Matrix': function (x) {
return _diag(x, 0, x.size(), x.storage());
},
'Matrix, number': function (x, k) {
return _diag(x, k, x.size(), x.storage());
},
'Matrix, BigNumber': function (x, k) {
return _diag(x, k.toNumber(), x.size(), x.storage());
},
'Matrix, string': function (x, format) {
return _diag(x, 0, x.size(), format);
},
'Matrix, number, string': function (x, k, format) {
return _diag(x, k, x.size(), format);
},
'Matrix, BigNumber, string': function (x, k, format) {
return _diag(x, k.toNumber(), x.size(), format);
}
});
diag.toTex = undefined; // use default template
return diag;
/**
* Creeate diagonal matrix from a vector or vice versa
* @param {Array | Matrix} x
* @param {number} k
* @param {string} format Storage format for matrix. If null,
* an Array is returned
* @returns {Array | Matrix}
* @private
*/
function _diag (x, k, size, format) {
if (!isInteger(k)) {
throw new TypeError ('Second parameter in function diag must be an integer');
}
var kSuper = k > 0 ? k : 0;
var kSub = k < 0 ? -k : 0;
// check dimensions
switch (size.length) {
case 1:
return _createDiagonalMatrix(x, k, format, size[0], kSub, kSuper);
case 2:
return _getDiagonal(x, k, format, size, kSub, kSuper);
}
throw new RangeError('Matrix for function diag must be 2 dimensional');
}
function _createDiagonalMatrix(x, k, format, l, kSub, kSuper) {
// matrix size
var ms = [l + kSub, l + kSuper];
// get matrix constructor
var F = type.Matrix.storage(format || 'dense');
// create diagonal matrix
var m = F.di ...
n/a
function factory(type, config, load, typed) {
var matrix = load(require('../../type/matrix/function/matrix'));
/**
* Calculates:
* The eucledian distance between two points in 2 and 3 dimensional spaces.
* Distance between point and a line in 2 and 3 dimensional spaces.
* Pairwise distance between a set of 2D or 3D points
* NOTE:
* When substituting coefficients of a line(a, b and c), use ax + by + c = 0 instead of ax + by = c
* For parametric equation of a 3D line, x0, y0, z0, a, b, c are from: (x−x0, y−y0, z−z0) = t(a, b, c)
*
* Syntax:
* math.distance([x1, y1], [x2, y2])
*- math.distance({pointOneX: 4, pointOneY: 5}, {pointTwoX: 2, pointTwoY: 7})
* math.distance([x1, y1, z1], [x2, y2, z2])
* math.distance({pointOneX: 4, pointOneY: 5, pointOneZ: 8}, {pointTwoX: 2, pointTwoY: 7, pointTwoZ: 9})
* math.distance([[A], [B], [C]...])
* math.distance([x1, y1], [LinePtX1, LinePtY1], [LinePtX2, LinePtY2])
* math.distance({pointX: 1, pointY: 4}, {lineOnePtX: 6, lineOnePtY: 3}, {lineTwoPtX: 2, lineTwoPtY: 8})
* math.distance([x1, y1, z1], [LinePtX1, LinePtY1, LinePtZ1], [LinePtX2, LinePtY2, LinePtZ2])
* math.distance({pointX: 1, pointY: 4, pointZ: 7}, {lineOnePtX: 6, lineOnePtY: 3, lineOnePtZ: 4}, {lineTwoPtX: 2, lineTwoPtY
: 8, lineTwoPtZ: 5})
* math.distance([x1, y1], [xCoeffLine, yCoeffLine, constant])
* math.distance({pointX: 10, pointY: 10}, {xCoeffLine: 8, yCoeffLine: 1, constant: 3})
* math.distance([x1, y1, z1], [x0, y0, z0, a-tCoeff, b-tCoeff, c-tCoeff]) point and parametric equation of 3D line
* math.distance([x, y, z], [x0, y0, z0, a, b, c])
* math.distance({pointX: 2, pointY: 5, pointZ: 9}, {x0: 4, y0: 6, z0: 3, a: 4, b: 2, c: 0})
*
* Examples:
* math.distance([0,0], [4,4]) // Returns 5.6569
* math.distance(
* {pointOneX: 0, pointOneY: 0},
* {pointTwoX: 10, pointTwoY: 10}) // Returns 14.142135623730951
* math.distance([1, 0, 1], [4, -2, 2]) // Returns 3.74166
* math.distance(
* {pointOneX: 4, pointOneY: 5, pointOneZ: 8},
* {pointTwoX: 2, pointTwoY: 7, pointTwoZ: 9}) // Returns 3
* math.distance([[1, 2], [1, 2], [1, 3]]) // Returns [0, 1, 1]
* math.distance([[1,2,4], [1,2,6], [8,1,3]]) // Returns [2, 7.14142842854285, 7.681145747868608]
* math.distance([10, 10], [8, 1, 3]) // Returns 11.535230316796387
* math.distance([10, 10], [2, 3], [-8, 0]) // Returns 8.759953130362847
* math.distance(
* {pointX: 1, pointY: 4},
* {lineOnePtX: 6, lineOnePtY: 3},
* {lineTwoPtX: 2, lineTwoPtY: 8}) // Returns 2.720549372624744
* math.distance([2, 3, 1], [1, 1, 2, 5, 0, 1]) // Returns 2.3204774044612857
* math.distance(
* {pointX: 2, pointY: 3, pointZ: 1},
* {x0: 1, y0: 1, z0: 2, a: 5, b: 0, c: 1} // Returns 2.3204774044612857
*
* @param {Array | Matrix | Object} x Co-ordinates of first point
* @param {Array | Matrix | Object} y Co-ordinates of second point
* @return {Number | BigNumber} Returns the distance from two/three points
*/
var distance = typed('distance', {
'Array, Array, Array': function(x, y, z){
// Point to Line 2D; (x=Point, y=LinePoint1, z=LinePoint2)
if (x.length == 2 && y.length == 2 && z.length == 2){
if (!_2d(x)) { throw new TypeError('Array with 2 numbers expected for first argument'); }
if (!_2d(y)) { throw new TypeError('Array with 2 numbers expected for second argument'); }
if (!_2d(z)) { throw new TypeError('Array with 2 numbers expected for third argument'); }
var m = (z[1]-z[0])/(y[1]-y[0]);
var xCoeff = m*m*y[0];
var yCoeff = -1*(m*y[0]);
var constant = x[1];
return _distancePointLine2D(x[0], x[1], xCoeff, yCoeff, constant);
}
else{
throw new TypeError('Invalid Arguments: Try ...
n/a
function factory(type, config, load, typed, math) {
var matrix = load(require('../../type/matrix/function/matrix'));
var array = require('../../utils/array');
// seeded pseudo random number generator
var rng = load(require('./seededRNG'));
/**
* Create a distribution object with a set of random functions for given
* random distribution.
*
* Syntax:
*
* math.distribution(name)
*
* Examples:
*
* var normalDist = math.distribution('normal'); // create a normal distribution
* normalDist.random(0, 10); // get a random value between 0 and 10
*
* See also:
*
* random, randomInt, pickRandom
*
* @param {string} name Name of a distribution. Choose from 'uniform', 'normal'.
* @return {Object} Returns a distribution object containing functions:
* `random([size] [, min] [, max])`,
* `randomInt([min] [, max])`,
* `pickRandom(array)`
*/
function distribution(name) {
if (!distributions.hasOwnProperty(name))
throw new Error('Unknown distribution ' + name);
var args = Array.prototype.slice.call(arguments, 1),
distribution = distributions[name].apply(this, args);
return (function(distribution) {
// This is the public API for all distributions
var randFunctions = {
random: function(arg1, arg2, arg3) {
var size, min, max;
if (arguments.length > 3) {
throw new ArgumentsError('random', arguments.length, 0, 3);
} else if (arguments.length === 1) {
// `random(max)` or `random(size)`
if (isCollection(arg1)) {
size = arg1;
} else {
max = arg1;
}
} else if (arguments.length === 2) {
// `random(min, max)` or `random(size, max)`
if (isCollection(arg1)) {
size = arg1;
max = arg2;
} else {
min = arg1;
max = arg2;
}
} else {
// `random(size, min, max)`
size = arg1;
min = arg2;
max = arg3;
}
// TODO: validate type of size
if ((min !== undefined && !isNumber(min)) || (max !== undefined && !isNumber(max))) {
throw new TypeError('Invalid argument in function random');
}
if (max === undefined) max = 1;
if (min === undefined) min = 0;
if (size !== undefined) {
var res = _randomDataForMatrix(size.valueOf(), min, max, _random);
return (size && size.isMatrix === true) ? matrix(res) : res;
}
return _random(min, max);
},
randomInt: typed({
'number | Array': function(arg) {
var min = 0;
if (isCollection(arg)) {
var size = arg;
var max = 1;
var res = _randomDataForMatrix(size.valueOf(), min, max, _randomInt);
return (size && size.isMatrix === true) ? matrix(res) : res;
} else {
var max = arg;
return _randomInt(min, max);
}
},
'number | Array, number': function(arg1, arg2) {
if (isCollection(arg1)) {
var size = arg1;
var max = arg2;
var min = 0;
var res = _randomDataForMatrix(size.valueOf(), min, max, _randomInt);
return (size && size.isMatrix === true) ? matrix(res) : res;
}
else {
var min = arg1;
var max = arg2;
return _randomInt(min, max);
}
},
'Array, number, number': function(size, min, max) {
var res = _randomDataForMatrix(size.valueOf(), min, max, _randomInt);
return (size && size.isMatrix === true) ? matrix(res) : res;
}
}),
pickRandom: typed({
'Array': function(possibles) {
return _pi ...
n/a
function factory(type, config, load, typed) {
var divideScalar = load(require('./divideScalar'));
var multiply = load(require('./multiply'));
var inv = load(require('../matrix/inv'));
var matrix = load(require('../../type/matrix/function/matrix'));
var algorithm11 = load(require('../../type/matrix/utils/algorithm11'));
var algorithm14 = load(require('../../type/matrix/utils/algorithm14'));
/**
* Divide two values, `x / y`.
* To divide matrices, `x` is multiplied with the inverse of `y`: `x * inv(y)`.
*
* Syntax:
*
* math.divide(x, y)
*
* Examples:
*
* math.divide(2, 3); // returns number 0.6666666666666666
*
* var a = math.complex(5, 14);
* var b = math.complex(4, 1);
* math.divide(a, b); // returns Complex 2 + 3i
*
* var c = [[7, -6], [13, -4]];
* var d = [[1, 2], [4, 3]];
* math.divide(c, d); // returns Array [[-9, 4], [-11, 6]]
*
* var e = math.unit('18 km');
* math.divide(e, 4.5); // returns Unit 4 km
*
* See also:
*
* multiply
*
* @param {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} x Numerator
* @param {number | BigNumber | Fraction | Complex | Array | Matrix} y Denominator
* @return {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} Quotient, `x / y`
*/
var divide = typed('divide', extend({
// we extend the signatures of divideScalar with signatures dealing with matrices
'Array | Matrix, Array | Matrix': function (x, y) {
// TODO: implement matrix right division using pseudo inverse
// http://www.mathworks.nl/help/matlab/ref/mrdivide.html
// http://www.gnu.org/software/octave/doc/interpreter/Arithmetic-Ops.html
// http://stackoverflow.com/questions/12263932/how-does-gnu-octave-matrix-division-work-getting-unexpected-behaviour
return multiply(x, inv(y));
},
'Matrix, any': function (x, y) {
// result
var c;
// process storage format
switch (x.storage()) {
case 'sparse':
c = algorithm11(x, y, divideScalar, false);
break;
case 'dense':
c = algorithm14(x, y, divideScalar, false);
break;
}
return c;
},
'Array, any': function (x, y) {
// use matrix implementation
return algorithm14(matrix(x), y, divideScalar, false).valueOf();
},
'any, Array | Matrix': function (x, y) {
return multiply(x, inv(y));
}
}, divideScalar.signatures));
divide.toTex = {2: '\\frac{${args[0]}}{${args[1]}}'};
return divide;
}
n/a
function factory(type, config, load, typed) {
var multiplyScalar = load(require('./multiplyScalar'));
/**
* Divide two scalar values, `x / y`.
* This function is meant for internal use: it is used by the public functions
* `divide` and `inv`.
*
* This function does not support collections (Array or Matrix), and does
* not validate the number of of inputs.
*
* @param {number | BigNumber | Fraction | Complex | Unit} x Numerator
* @param {number | BigNumber | Fraction | Complex} y Denominator
* @return {number | BigNumber | Fraction | Complex | Unit} Quotient, `x / y`
* @private
*/
var divideScalar = typed('divide', {
'number, number': function (x, y) {
return x / y;
},
'Complex, Complex': function (x, y) {
return x.div(y);
},
'BigNumber, BigNumber': function (x, y) {
return x.div(y);
},
'Fraction, Fraction': function (x, y) {
return x.div(y);
},
'Unit, number | Fraction | BigNumber': function (x, y) {
var res = x.clone();
// TODO: move the divide function to Unit.js, it uses internals of Unit
res.value = divideScalar(((res.value === null) ? res._normalize(1) : res.value), y);
return res;
},
'number | Fraction | BigNumber, Unit': function (x, y) {
var res = y.pow(-1);
// TODO: move the divide function to Unit.js, it uses internals of Unit
res.value = multiplyScalar(((res.value === null) ? res._normalize(1) : res.value), x);
return res;
},
'Unit, Unit': function (x, y) {
return x.divide(y);
}
});
return divideScalar;
}
n/a
function factory(type, config, load, typed) {
var add = load(require('../arithmetic/add'));
var multiply = load(require('../arithmetic/multiply'));
/**
* Calculate the dot product of two vectors. The dot product of
* `A = [a1, a2, a3, ..., an]` and `B = [b1, b2, b3, ..., bn]` is defined as:
*
* dot(A, B) = a1 * b1 + a2 * b2 + a3 * b3 + ... + an * bn
*
* Syntax:
*
* math.dot(x, y)
*
* Examples:
*
* math.dot([2, 4, 1], [2, 2, 3]); // returns number 15
* math.multiply([2, 4, 1], [2, 2, 3]); // returns number 15
*
* See also:
*
* multiply, cross
*
* @param {Array | Matrix} x First vector
* @param {Array | Matrix} y Second vector
* @return {number} Returns the dot product of `x` and `y`
*/
var dot = typed('dot', {
'Matrix, Matrix': function (x, y) {
return _dot(x.toArray(), y.toArray());
},
'Matrix, Array': function (x, y) {
return _dot(x.toArray(), y);
},
'Array, Matrix': function (x, y) {
return _dot(x, y.toArray());
},
'Array, Array': _dot
});
dot.toTex = {2: '\\left(${args[0]}\\cdot${args[1]}\\right)'};
return dot;
/**
* Calculate the dot product for two arrays
* @param {Array} x First vector
* @param {Array} y Second vector
* @returns {number} Returns the dot product of x and y
* @private
*/
// TODO: double code with math.multiply
function _dot(x, y) {
var xSize= size(x);
var ySize = size(y);
var len = xSize[0];
if (xSize.length !== 1 || ySize.length !== 1) throw new RangeError('Vector expected'); // TODO: better error message
if (xSize[0] != ySize[0]) throw new RangeError('Vectors must have equal length (' + xSize[0] + ' != ' + ySize[0] + ')');
if (len == 0) throw new RangeError('Cannot calculate the dot product of empty vectors');
var prod = 0;
for (var i = 0; i < len; i++) {
prod = add(prod, multiply(x[i], y[i]));
}
return prod;
}
}
n/a
function factory(type, config, load, typed) {
var matrix = load(require('../../type/matrix/function/matrix'));
var divideScalar = load(require('./divideScalar'));
var latex = require('../../utils/latex');
var algorithm02 = load(require('../../type/matrix/utils/algorithm02'));
var algorithm03 = load(require('../../type/matrix/utils/algorithm03'));
var algorithm07 = load(require('../../type/matrix/utils/algorithm07'));
var algorithm11 = load(require('../../type/matrix/utils/algorithm11'));
var algorithm12 = load(require('../../type/matrix/utils/algorithm12'));
var algorithm13 = load(require('../../type/matrix/utils/algorithm13'));
var algorithm14 = load(require('../../type/matrix/utils/algorithm14'));
/**
* Divide two matrices element wise. The function accepts both matrices and
* scalar values.
*
* Syntax:
*
* math.dotDivide(x, y)
*
* Examples:
*
* math.dotDivide(2, 4); // returns 0.5
*
* a = [[9, 5], [6, 1]];
* b = [[3, 2], [5, 2]];
*
* math.dotDivide(a, b); // returns [[3, 2.5], [1.2, 0.5]]
* math.divide(a, b); // returns [[1.75, 0.75], [-1.75, 2.25]]
*
* See also:
*
* divide, multiply, dotMultiply
*
* @param {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} x Numerator
* @param {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} y Denominator
* @return {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} Quotient, `x ./ y`
*/
var dotDivide = typed('dotDivide', {
'any, any': divideScalar,
'Matrix, Matrix': function (x, y) {
// result
var c;
// process matrix storage
switch (x.storage()) {
case 'sparse':
switch (y.storage()) {
case 'sparse':
// sparse ./ sparse
c = algorithm07(x, y, divideScalar, false);
break;
default:
// sparse ./ dense
c = algorithm02(y, x, divideScalar, true);
break;
}
break;
default:
switch (y.storage()) {
case 'sparse':
// dense ./ sparse
c = algorithm03(x, y, divideScalar, false);
break;
default:
// dense ./ dense
c = algorithm13(x, y, divideScalar);
break;
}
break;
}
return c;
},
'Array, Array': function (x, y) {
// use matrix implementation
return dotDivide(matrix(x), matrix(y)).valueOf();
},
'Array, Matrix': function (x, y) {
// use matrix implementation
return dotDivide(matrix(x), y);
},
'Matrix, Array': function (x, y) {
// use matrix implementation
return dotDivide(x, matrix(y));
},
'Matrix, any': function (x, y) {
// result
var c;
// check storage format
switch (x.storage()) {
case 'sparse':
c = algorithm11(x, y, divideScalar, false);
break;
default:
c = algorithm14(x, y, divideScalar, false);
break;
}
return c;
},
'any, Matrix': function (x, y) {
// result
var c;
// check storage format
switch (y.storage()) {
case 'sparse':
c = algorithm12(y, x, divideScalar, true);
break;
default:
c = algorithm14(y, x, divideScalar, true);
break;
}
return c;
},
'Array, any': function (x, y) {
// use matrix implementation
return algorithm14(matrix(x), y, divideScalar, false).valueOf();
},
'any, Array': function (x, y) {
// use matrix implementation
return algorithm14(matrix(y), x, divideScalar, true).valueOf();
}
});
dotDivide.toTex = {
2: '\\left(${args[0]}' + latex.operators['dotDivide'] + '${args[1]}\\right)'
};
return dotDivide;
}
n/a
function factory(type, config, load, typed) {
var matrix = load(require('../../type/matrix/function/matrix'));
var multiplyScalar = load(require('./multiplyScalar'));
var latex = require('../../utils/latex');
var algorithm02 = load(require('../../type/matrix/utils/algorithm02'));
var algorithm09 = load(require('../../type/matrix/utils/algorithm09'));
var algorithm11 = load(require('../../type/matrix/utils/algorithm11'));
var algorithm13 = load(require('../../type/matrix/utils/algorithm13'));
var algorithm14 = load(require('../../type/matrix/utils/algorithm14'));
/**
* Multiply two matrices element wise. The function accepts both matrices and
* scalar values.
*
* Syntax:
*
* math.dotMultiply(x, y)
*
* Examples:
*
* math.dotMultiply(2, 4); // returns 8
*
* a = [[9, 5], [6, 1]];
* b = [[3, 2], [5, 2]];
*
* math.dotMultiply(a, b); // returns [[27, 10], [30, 2]]
* math.multiply(a, b); // returns [[52, 28], [23, 14]]
*
* See also:
*
* multiply, divide, dotDivide
*
* @param {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} x Left hand value
* @param {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} y Right hand value
* @return {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} Multiplication of `x` and `y`
*/
var dotMultiply = typed('dotMultiply', {
'any, any': multiplyScalar,
'Matrix, Matrix': function (x, y) {
// result
var c;
// process matrix storage
switch (x.storage()) {
case 'sparse':
switch (y.storage()) {
case 'sparse':
// sparse .* sparse
c = algorithm09(x, y, multiplyScalar, false);
break;
default:
// sparse .* dense
c = algorithm02(y, x, multiplyScalar, true);
break;
}
break;
default:
switch (y.storage()) {
case 'sparse':
// dense .* sparse
c = algorithm02(x, y, multiplyScalar, false);
break;
default:
// dense .* dense
c = algorithm13(x, y, multiplyScalar);
break;
}
break;
}
return c;
},
'Array, Array': function (x, y) {
// use matrix implementation
return dotMultiply(matrix(x), matrix(y)).valueOf();
},
'Array, Matrix': function (x, y) {
// use matrix implementation
return dotMultiply(matrix(x), y);
},
'Matrix, Array': function (x, y) {
// use matrix implementation
return dotMultiply(x, matrix(y));
},
'Matrix, any': function (x, y) {
// result
var c;
// check storage format
switch (x.storage()) {
case 'sparse':
c = algorithm11(x, y, multiplyScalar, false);
break;
default:
c = algorithm14(x, y, multiplyScalar, false);
break;
}
return c;
},
'any, Matrix': function (x, y) {
// result
var c;
// check storage format
switch (y.storage()) {
case 'sparse':
c = algorithm11(y, x, multiplyScalar, true);
break;
default:
c = algorithm14(y, x, multiplyScalar, true);
break;
}
return c;
},
'Array, any': function (x, y) {
// use matrix implementation
return algorithm14(matrix(x), y, multiplyScalar, false).valueOf();
},
'any, Array': function (x, y) {
// use matrix implementation
return algorithm14(matrix(y), x, multiplyScalar, true).valueOf();
}
});
dotMultiply.toTex = {
2: '\\left(${args[0]}' + latex.operators['dotMultiply'] + '${args[1]}\\right)'
};
return dotMultiply;
}
n/a
function factory(type, config, load, typed) {
var matrix = load(require('../../type/matrix/function/matrix'));
var pow = load(require('./pow'));
var latex = require('../../utils/latex');
var algorithm03 = load(require('../../type/matrix/utils/algorithm03'));
var algorithm07 = load(require('../../type/matrix/utils/algorithm07'));
var algorithm11 = load(require('../../type/matrix/utils/algorithm11'));
var algorithm12 = load(require('../../type/matrix/utils/algorithm12'));
var algorithm13 = load(require('../../type/matrix/utils/algorithm13'));
var algorithm14 = load(require('../../type/matrix/utils/algorithm14'));
/**
* Calculates the power of x to y element wise.
*
* Syntax:
*
* math.dotPow(x, y)
*
* Examples:
*
* math.dotPow(2, 3); // returns number 8
*
* var a = [[1, 2], [4, 3]];
* math.dotPow(a, 2); // returns Array [[1, 4], [16, 9]]
* math.pow(a, 2); // returns Array [[9, 8], [16, 17]]
*
* See also:
*
* pow, sqrt, multiply
*
* @param {number | BigNumber | Complex | Unit | Array | Matrix} x The base
* @param {number | BigNumber | Complex | Unit | Array | Matrix} y The exponent
* @return {number | BigNumber | Complex | Unit | Array | Matrix} The value of `x` to the power `y`
*/
var dotPow = typed('dotPow', {
'any, any': pow,
'Matrix, Matrix': function (x, y) {
// result
var c;
// process matrix storage
switch (x.storage()) {
case 'sparse':
switch (y.storage()) {
case 'sparse':
// sparse .^ sparse
c = algorithm07(x, y, pow, false);
break;
default:
// sparse .^ dense
c = algorithm03(y, x, pow, true);
break;
}
break;
default:
switch (y.storage()) {
case 'sparse':
// dense .^ sparse
c = algorithm03(x, y, pow, false);
break;
default:
// dense .^ dense
c = algorithm13(x, y, pow);
break;
}
break;
}
return c;
},
'Array, Array': function (x, y) {
// use matrix implementation
return dotPow(matrix(x), matrix(y)).valueOf();
},
'Array, Matrix': function (x, y) {
// use matrix implementation
return dotPow(matrix(x), y);
},
'Matrix, Array': function (x, y) {
// use matrix implementation
return dotPow(x, matrix(y));
},
'Matrix, any': function (x, y) {
// result
var c;
// check storage format
switch (x.storage()) {
case 'sparse':
c = algorithm11(x, y, dotPow, false);
break;
default:
c = algorithm14(x, y, dotPow, false);
break;
}
return c;
},
'any, Matrix': function (x, y) {
// result
var c;
// check storage format
switch (y.storage()) {
case 'sparse':
c = algorithm12(y, x, dotPow, true);
break;
default:
c = algorithm14(y, x, dotPow, true);
break;
}
return c;
},
'Array, any': function (x, y) {
// use matrix implementation
return algorithm14(matrix(x), y, dotPow, false).valueOf();
},
'any, Array': function (x, y) {
// use matrix implementation
return algorithm14(matrix(y), x, dotPow, true).valueOf();
}
});
dotPow.toTex = {
2: '\\left(${args[0]}' + latex.operators['dotPow'] + '${args[1]}\\right)'
};
return dotPow;
}
n/a
mixin = function (obj) { // create event emitter var emitter = new Emitter(); // bind methods to obj (we don't want to expose the emitter.e Array...) obj.on = emitter.on.bind(emitter); obj.off = emitter.off.bind(emitter); obj.once = emitter.once.bind(emitter); obj.emit = emitter.emit.bind(emitter); return obj; }
n/a
function factory(type, config, load, typed) {
var matrix = load(require('../../type/matrix/function/matrix'));
var equalScalar = load(require('./equalScalar'));
var algorithm03 = load(require('../../type/matrix/utils/algorithm03'));
var algorithm07 = load(require('../../type/matrix/utils/algorithm07'));
var algorithm12 = load(require('../../type/matrix/utils/algorithm12'));
var algorithm13 = load(require('../../type/matrix/utils/algorithm13'));
var algorithm14 = load(require('../../type/matrix/utils/algorithm14'));
var latex = require('../../utils/latex');
/**
* Test whether two values are equal.
*
* The function tests whether the relative difference between x and y is
* smaller than the configured epsilon. The function cannot be used to
* compare values smaller than approximately 2.22e-16.
*
* For matrices, the function is evaluated element wise.
* In case of complex numbers, x.re must equal y.re, and x.im must equal y.im.
*
* Values `null` and `undefined` are compared strictly, thus `null` is only
* equal to `null` and nothing else, and `undefined` is only equal to
* `undefined` and nothing else.
*
* Syntax:
*
* math.equal(x, y)
*
* Examples:
*
* math.equal(2 + 2, 3); // returns false
* math.equal(2 + 2, 4); // returns true
*
* var a = math.unit('50 cm');
* var b = math.unit('5 m');
* math.equal(a, b); // returns true
*
* var c = [2, 5, 1];
* var d = [2, 7, 1];
*
* math.equal(c, d); // returns [true, false, true]
* math.deepEqual(c, d); // returns false
*
* math.equal(0, null); // returns false
*
* See also:
*
* unequal, smaller, smallerEq, larger, largerEq, compare, deepEqual
*
* @param {number | BigNumber | boolean | Complex | Unit | string | Array | Matrix} x First value to compare
* @param {number | BigNumber | boolean | Complex | Unit | string | Array | Matrix} y Second value to compare
* @return {boolean | Array | Matrix} Returns true when the compared values are equal, else returns false
*/
var equal = typed('equal', {
'any, any': function (x, y) {
// strict equality for null and undefined?
if (x === null) { return y === null; }
if (y === null) { return x === null; }
if (x === undefined) { return y === undefined; }
if (y === undefined) { return x === undefined; }
return equalScalar(x, y);
},
'Matrix, Matrix': function (x, y) {
// result
var c;
// process matrix storage
switch (x.storage()) {
case 'sparse':
switch (y.storage()) {
case 'sparse':
// sparse + sparse
c = algorithm07(x, y, equalScalar);
break;
default:
// sparse + dense
c = algorithm03(y, x, equalScalar, true);
break;
}
break;
default:
switch (y.storage()) {
case 'sparse':
// dense + sparse
c = algorithm03(x, y, equalScalar, false);
break;
default:
// dense + dense
c = algorithm13(x, y, equalScalar);
break;
}
break;
}
return c;
},
'Array, Array': function (x, y) {
// use matrix implementation
return equal(matrix(x), matrix(y)).valueOf();
},
'Array, Matrix': function (x, y) {
// use matrix implementation
return equal(matrix(x), y);
},
'Matrix, Array': function (x, y) {
// use matrix implementation
return equal(x, matrix(y));
},
'Matrix, any': function (x, y) {
// result
var c;
// check storage format
switch (x.storage()) {
case 'sparse':
c = algorithm12(x, y, equalScalar, false);
break;
default:
c = algorithm14(x, y, equalScalar, false);
break;
}
return c;
}, ...
n/a
function factory(type, config, load, typed) {
/**
* Test whether two values are equal.
*
* @param {number | BigNumber | Fraction | boolean | Complex | Unit} x First value to compare
* @param {number | BigNumber | Fraction | boolean | Complex} y Second value to compare
* @return {boolean} Returns true when the compared values are equal, else returns
false
* @private
*/
var equalScalar = typed('equalScalar', {
'boolean, boolean': function (x, y) {
return x === y;
},
'number, number': function (x, y) {
return x === y || nearlyEqual(x, y, config.epsilon);
},
'BigNumber, BigNumber': function (x, y) {
return x.eq(y) || bigNearlyEqual(x, y, config.epsilon);
},
'Fraction, Fraction': function (x, y) {
return x.equals(y);
},
'Complex, Complex': function (x, y) {
return x.equals(y);
},
'Unit, Unit': function (x, y) {
if (!x.equalBase(y)) {
throw new Error('Cannot compare units with different base');
}
return equalScalar(x.value, y.value);
},
'string, string': function (x, y) {
return x === y;
}
});
return equalScalar;
}
n/a
function factory(type, config, load, typed) {
/**
* Compute the erf function of a value using a rational Chebyshev
* approximations for different intervals of x.
*
* This is a translation of W. J. Cody's Fortran implementation from 1987
* ( http://www.netlib.org/specfun/erf ). See the AMS publication
* "Rational Chebyshev Approximations for the Error Function" by W. J. Cody
* for an explanation of this process.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.erf(x)
*
* Examples:
*
* math.erf(0.2); // returns 0.22270258921047847
* math.erf(-0.5); // returns -0.5204998778130465
* math.erf(4); // returns 0.9999999845827421
*
* @param {number | Array | Matrix} x A real number
* @return {number | Array | Matrix} The erf of `x`
*/
var erf = typed('erf', {
'number': function (x) {
var y = Math.abs(x);
if (y >= MAX_NUM) {
return sign(x);
}
if (y <= THRESH) {
return sign(x) * erf1(y);
}
if (y <= 4.0) {
return sign(x) * (1 - erfc2(y));
}
return sign(x) * (1 - erfc3(y));
},
// TODO: Not sure if there's a way to guarantee some degree of accuracy here.
// Perhaps it would be best to set the precision of the number to that which
// is guaranteed by erf()
'BigNumber': function (n) {
return new type.BigNumber(erf(n.toNumber()));
},
'Array | Matrix': function (n) {
return deepMap(n, erf);
}
// TODO: For complex numbers, use the approximation for the Faddeeva function
// from "More Efficient Computation of the Complex Error Function" (AMS)
});
/**
* Approximates the error function erf() for x <= 0.46875 using this function:
* n
* erf(x) = x * sum (p_j * x^(2j)) / (q_j * x^(2j))
* j=0
*/
function erf1(y) {
var ysq = y * y;
var xnum = P[0][4]*ysq;
var xden = ysq;
var i;
for (i = 0; i < 3; i += 1) {
xnum = (xnum + P[0][i]) * ysq;
xden = (xden + Q[0][i]) * ysq;
}
return y * (xnum + P[0][3]) / (xden + Q[0][3]);
}
/**
* Approximates the complement of the error function erfc() for
* 0.46875 <= x <= 4.0 using this function:
* n
* erfc(x) = e^(-x^2) * sum (p_j * x^j) / (q_j * x^j)
* j=0
*/
function erfc2(y) {
var xnum = P[1][8] * y;
var xden = y;
var i;
for (i = 0; i < 7; i += 1) {
xnum = (xnum + P[1][i]) * y;
xden = (xden + Q[1][i]) * y;
}
var result = (xnum + P[1][7]) / (xden + Q[1][7]);
var ysq = parseInt(y * 16) / 16;
var del = (y - ysq) * (y + ysq);
return Math.exp(-ysq*ysq) * Math.exp(-del) * result;
}
/**
* Approximates the complement of the error function erfc() for x > 4.0 using
* this function:
*
* erfc(x) = (e^(-x^2) / x) * [ 1/sqrt(pi) +
* n
* 1/(x^2) * sum (p_j * x^(-2j)) / (q_j * x^(-2j)) ]
* j=0
*/
function erfc3(y) {
var ysq = 1 / (y * y);
var xnum = P[2][5] * ysq;
var xden = ysq;
var i;
for (i = 0; i < 4; i += 1) {
xnum = (xnum + P[2][i]) * ysq;
xden = (xden + Q[2][i]) * ysq;
}
var result = ysq * (xnum + P[2][4]) / (xden + Q[2][4]);
result = (SQRPI - result) / y;
ysq = parseInt(y * 16) / 16;
var del = (y - ysq) * (y + ysq);
return Math.exp(-ysq*ysq) * Math.exp(-del) * result;
}
erf.toTex = {1: 'erf\\left(${args[0]}\\right)'};
return erf;
}
n/a
function ArgumentsError(fn, count, min, max) { if (!(this instanceof ArgumentsError)) { throw new SyntaxError('Constructor must be called with the new operator'); } this.fn = fn; this.count = count; this.min = min; this.max = max; this.message = 'Wrong number of arguments in function ' + fn + ' (' + count + ' provided, ' + min + ((max != undefined) ? ('-' + max) : '') + ' expected)'; this.stack = (new Error()).stack; }
n/a
function DimensionError(actual, expected, relation) { if (!(this instanceof DimensionError)) { throw new SyntaxError('Constructor must be called with the new operator'); } this.actual = actual; this.expected = expected; this.relation = relation; this.message = 'Dimension mismatch (' + (Array.isArray(actual) ? ('[' + actual.join(', ') + ']') : actual) + ' ' + (this.relation || '!=') + ' ' + (Array.isArray(expected) ? ('[' + expected.join(', ') + ']') : expected) + ')'; this.stack = (new Error()).stack; }
n/a
function IndexError(index, min, max) { if (!(this instanceof IndexError)) { throw new SyntaxError('Constructor must be called with the new operator'); } this.index = index; if (arguments.length < 3) { this.min = 0; this.max = min; } else { this.min = min; this.max = max; } if (this.min !== undefined && this.index < this.min) { this.message = 'Index out of range (' + this.index + ' < ' + this.min + ')'; } else if (this.max !== undefined && this.index >= this.max) { this.message = 'Index out of range (' + this.index + ' > ' + (this.max - 1) + ')'; } else { this.message = 'Index out of range (' + this.index + ')'; } this.stack = (new Error()).stack; }
n/a
function ArgumentsError(fn, count, min, max) { if (!(this instanceof ArgumentsError)) { throw new SyntaxError('Constructor must be called with the new operator'); } this.fn = fn; this.count = count; this.min = min; this.max = max; this.message = 'Wrong number of arguments in function ' + fn + ' (' + count + ' provided, ' + min + ((max != undefined) ? ('-' + max) : '') + ' expected)'; this.stack = (new Error()).stack; }
n/a
function Error() { [native code] }
...
}
if (probOrN && probOrN.isBigNumber) {
if (probOrN.isNegative()) {
throw new Error('N/prob must be non-negative');
}
one = new probOrN.constructor(1);
if (probOrN.lte(one)) {
// quantileSeq([a, b, c, d, ...], prob[,sorted])
return _quantileSeq(dataArr, probOrN, sorted);
}
if (probOrN.gt(one)) {
...
function Function() { [native code] }
...
}
if (probOrN && probOrN.isBigNumber) {
if (probOrN.isNegative()) {
throw new Error('N/prob must be non-negative');
}
one = new probOrN.constructor(1);
if (probOrN.lte(one)) {
// quantileSeq([a, b, c, d, ...], prob[,sorted])
return _quantileSeq(dataArr, probOrN, sorted);
}
if (probOrN.gt(one)) {
...
function captureStackTrace() { [native code] }
n/a
function DimensionError(actual, expected, relation) { if (!(this instanceof DimensionError)) { throw new SyntaxError('Constructor must be called with the new operator'); } this.actual = actual; this.expected = expected; this.relation = relation; this.message = 'Dimension mismatch (' + (Array.isArray(actual) ? ('[' + actual.join(', ') + ']') : actual) + ' ' + (this.relation || '!=') + ' ' + (Array.isArray(expected) ? ('[' + expected.join(', ') + ']') : expected) + ')'; this.stack = (new Error()).stack; }
n/a
function RangeError() { [native code] }
...
}
if (probOrN && probOrN.isBigNumber) {
if (probOrN.isNegative()) {
throw new Error('N/prob must be non-negative');
}
one = new probOrN.constructor(1);
if (probOrN.lte(one)) {
// quantileSeq([a, b, c, d, ...], prob[,sorted])
return _quantileSeq(dataArr, probOrN, sorted);
}
if (probOrN.gt(one)) {
...
function IndexError(index, min, max) { if (!(this instanceof IndexError)) { throw new SyntaxError('Constructor must be called with the new operator'); } this.index = index; if (arguments.length < 3) { this.min = 0; this.max = min; } else { this.min = min; this.max = max; } if (this.min !== undefined && this.index < this.min) { this.message = 'Index out of range (' + this.index + ' < ' + this.min + ')'; } else if (this.max !== undefined && this.index >= this.max) { this.message = 'Index out of range (' + this.index + ' > ' + (this.max - 1) + ')'; } else { this.message = 'Index out of range (' + this.index + ')'; } this.stack = (new Error()).stack; }
n/a
function RangeError() { [native code] }
...
}
if (probOrN && probOrN.isBigNumber) {
if (probOrN.isNegative()) {
throw new Error('N/prob must be non-negative');
}
one = new probOrN.constructor(1);
if (probOrN.lte(one)) {
// quantileSeq([a, b, c, d, ...], prob[,sorted])
return _quantileSeq(dataArr, probOrN, sorted);
}
if (probOrN.gt(one)) {
...
transform = function (err) { if (err && err.isIndexError) { return new IndexError( err.index + 1, err.min + 1, err.max !== undefined ? err.max + 1 : undefined); } return err; }
...
/**
* Recursively transform a node tree via a transform function.
*
* For example, to replace all nodes of type SymbolNode having name 'x' with a
* ConstantNode with value 2:
*
* var res = Node.transform(function (node, path, parent) {
* if (node && node.isSymbolNode) && (node.name == 'x')) {
* return new ConstantNode(2);
* }
* else {
* return node;
* }
* });
...
function factory(type, config, load, typed) {
var parse = load(require('../parse'));
/**
* Evaluate an expression.
*
* Note the evaluating arbitrary expressions may involve security risks,
* see [http://mathjs.org/docs/expressions/security.html](http://mathjs.org/docs/expressions/security.html) for more information
.
*
* Syntax:
*
* math.eval(expr)
* math.eval(expr, scope)
* math.eval([expr1, expr2, expr3, ...])
* math.eval([expr1, expr2, expr3, ...], scope)
*
* Example:
*
* math.eval('(2+3)/4'); // 1.25
* math.eval('sqrt(3^2 + 4^2)'); // 5
* math.eval('sqrt(-4)'); // 2i
* math.eval(['a=3', 'b=4', 'a*b']);, // [3, 4, 12]
*
* var scope = {a:3, b:4};
* math.eval('a * b', scope); // 12
*
* See also:
*
* parse, compile
*
* @param {string | string[] | Matrix} expr The expression to be evaluated
* @param {Object} [scope] Scope to read/write variables
* @return {*} The result of the expression
* @throws {Error}
*/
return typed('compile', {
'string': function (expr) {
var scope = {};
return parse(expr).compile().eval(scope);
},
'string, Object': function (expr, scope) {
return parse(expr).compile().eval(scope);
},
'Array | Matrix': function (expr) {
var scope = {};
return deepMap(expr, function (entry) {
return parse(entry).compile().eval(scope);
});
},
'Array | Matrix, Object': function (expr, scope) {
return deepMap(expr, function (entry) {
return parse(entry).compile().eval(scope);
});
}
});
}
n/a
function factory(type, config, load, typed) {
/**
* Calculate the exponent of a value.
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.exp(x)
*
* Examples:
*
* math.exp(2); // returns number 7.3890560989306495
* math.pow(math.e, 2); // returns number 7.3890560989306495
* math.log(math.exp(2)); // returns number 2
*
* math.exp([1, 2, 3]);
* // returns Array [
* // 2.718281828459045,
* // 7.3890560989306495,
* // 20.085536923187668
* // ]
*
* See also:
*
* log, pow
*
* @param {number | BigNumber | Complex | Array | Matrix} x A number or matrix to exponentiate
* @return {number | BigNumber | Complex | Array | Matrix} Exponent of `x`
*/
var exp = typed('exp', {
'number': Math.exp,
'Complex': function (x) {
return x.exp();
},
'BigNumber': function (x) {
return x.exp();
},
'Array | Matrix': function (x) {
// TODO: exp(sparse) should return a dense matrix since exp(0)==1
return deepMap(x, exp);
}
});
exp.toTex = {1: '\\exp\\left(${args[0]}\\right)'};
return exp;
}
n/a
function Parser() { if (!(this instanceof Parser)) { throw new SyntaxError( 'Constructor must be called with the new operator'); } this.scope = {}; }
n/a
function parse(expr, options) { if (arguments.length != 1 && arguments.length != 2) { throw new ArgumentsError('parse', arguments.length, 1, 2); } // pass extra nodes extra_nodes = (options && options.nodes) ? options.nodes : {}; if (typeof expr === 'string') { // parse a single expression expression = expr; return parseStart(); } else if (Array.isArray(expr) || expr instanceof type.Matrix) { // parse an array or matrix with expressions return deepMap(expr, function (elem) { if (typeof elem !== 'string') throw new TypeError('String expected'); expression = elem; return parseStart(); }); } else { // oops throw new TypeError('String or matrix expected'); } }
...
if (!expr) {
break;
}
switch (mode) {
case 'eval':
// evaluate expression
try {
var node = math.parse(expr);
var res = node.eval(scope);
if (res && res.isResultSet) {
// we can have 0 or 1 results in the ResultSet, as the CLI
// does not allow multiple expressions separated by a return
res = res.entries[0];
node = node.blocks
...
function Parser() { if (!(this instanceof Parser)) { throw new SyntaxError( 'Constructor must be called with the new operator'); } this.scope = {}; }
n/a
clear = function () { for (var name in this.scope) { if (this.scope.hasOwnProperty(name)) { delete this.scope[name]; } } }
...
* Methods:
* var result = parser.eval(expr); // evaluate an expression
* var value = parser.get(name); // retrieve a variable from the parser
* var values = parser.getAll(); // retrieve all defined variables
* parser.set(name, value); // set a variable in the parser
* parser.remove(name); // clear a variable from the
* // parsers scope
* parser.clear(); // clear the parsers scope
*
* Example usage:
* var parser = new Parser();
* // Note: there is a convenience method which can be used instead:
* // var parser = new math.parser();
*
* // evaluate expressions
...
compile = function (expr) { throw new Error('Parser.compile is deprecated. Use math.compile instead.'); }
...
* parse(expr, options)
* parse([expr1, expr2, expr3, ...])
* parse([expr1, expr2, expr3, ...], options)
*
* Example:
*
* var node = parse('sqrt(3^2 + 4^2)');
* node.compile(math).eval(); // 5
*
* var scope = {a:3, b:4}
* var node = parse('a * b'); // 12
* var code = node.compile(math);
* code.eval(scope); // 12
* scope.a = 5;
* code.eval(scope); // 20
...
eval = function (expr) { // TODO: validate arguments return _parse(expr) .compile() .eval(this.scope); }
...
math.atan2(3, -3) / math.pi; // 0.75
math.log(1000, 10); // 3
math.sqrt(-4); // 2i
math.pow([[-1, 2], [3, 1]], 2); // [[7, 0], [0, 7]]
math.derivative('x^2 + x', 'x'); // 2 * x + 1
// expressions
math.eval('12 / (2.3 + 0.7)'); // 4
math.eval('5.08 cm to inch'); // 2 inch
math.eval('sin(45 deg) ^ 2'); // 0.5
math.eval('9 / 3 + 2i'); // 3 + 2i
math.eval('det([-1, 2; 3, 1])'); // -7
// chaining
math.chain(3)
...
get = function (name) { // TODO: validate arguments return name in this.scope ? customs.getSafeProperty(this.scope, name) : undefined; }
...
* Parser contains methods to evaluate or parse expressions, and has a number
* of convenience methods to get, set, and remove variables from memory. Parser
* keeps a scope containing variables in memory, which is used for all
* evaluations.
*
* Methods:
* var result = parser.eval(expr); // evaluate an expression
* var value = parser.get(name); // retrieve a variable from the parser
* var values = parser.getAll(); // retrieve all defined variables
* parser.set(name, value); // set a variable in the parser
* parser.remove(name); // clear a variable from the
* // parsers scope
* parser.clear(); // clear the parsers scope
*
* Example usage:
...
getAll = function () { return extend({}, this.scope); }
...
* of convenience methods to get, set, and remove variables from memory. Parser
* keeps a scope containing variables in memory, which is used for all
* evaluations.
*
* Methods:
* var result = parser.eval(expr); // evaluate an expression
* var value = parser.get(name); // retrieve a variable from the parser
* var values = parser.getAll(); // retrieve all defined variables
* parser.set(name, value); // set a variable in the parser
* parser.remove(name); // clear a variable from the
* // parsers scope
* parser.clear(); // clear the parsers scope
*
* Example usage:
* var parser = new Parser();
...
parse = function (expr) { throw new Error('Parser.parse is deprecated. Use math.parse instead.'); }
...
if (!expr) {
break;
}
switch (mode) {
case 'eval':
// evaluate expression
try {
var node = math.parse(expr);
var res = node.eval(scope);
if (res && res.isResultSet) {
// we can have 0 or 1 results in the ResultSet, as the CLI
// does not allow multiple expressions separated by a return
res = res.entries[0];
node = node.blocks
...
remove = function (name) { // TODO: validate arguments delete this.scope[name]; }
...
* evaluations.
*
* Methods:
* var result = parser.eval(expr); // evaluate an expression
* var value = parser.get(name); // retrieve a variable from the parser
* var values = parser.getAll(); // retrieve all defined variables
* parser.set(name, value); // set a variable in the parser
* parser.remove(name); // clear a variable from the
* // parsers scope
* parser.clear(); // clear the parsers scope
*
* Example usage:
* var parser = new Parser();
* // Note: there is a convenience method which can be used instead:
* // var parser = new math.parser();
...
set = function (name, value) { // TODO: validate arguments return customs.setSafeProperty(this.scope, name, value); }
...
* keeps a scope containing variables in memory, which is used for all
* evaluations.
*
* Methods:
* var result = parser.eval(expr); // evaluate an expression
* var value = parser.get(name); // retrieve a variable from the parser
* var values = parser.getAll(); // retrieve all defined variables
* parser.set(name, value); // set a variable in the parser
* parser.remove(name); // clear a variable from the
* // parsers scope
* parser.clear(); // clear the parsers scope
*
* Example usage:
* var parser = new Parser();
* // Note: there is a convenience method which can be used instead:
...
function AccessorNode(object, index) { if (!(this instanceof AccessorNode)) { throw new SyntaxError('Constructor must be called with the new operator'); } if (!(object && object.isNode)) { throw new TypeError('Node expected for parameter "object"'); } if (!(index && index.isIndexNode)) { throw new TypeError('IndexNode expected for parameter "index"'); } this.object = object || null; this.index = index; // readonly property name Object.defineProperty(this, 'name', { get: function () { if (this.index) { return (this.index.isObjectProperty()) ? this.index.getObjectProperty() : ''; } else { return this.object.name || ''; } }.bind(this), set: function () { throw new Error('Cannot assign a new name, name is read-only'); } }); }
n/a
function ArgumentsError(fn, count, min, max) { if (!(this instanceof ArgumentsError)) { throw new SyntaxError('Constructor must be called with the new operator'); } this.fn = fn; this.count = count; this.min = min; this.max = max; this.message = 'Wrong number of arguments in function ' + fn + ' (' + count + ' provided, ' + min + ((max != undefined) ? ('-' + max) : '') + ' expected)'; this.stack = (new Error()).stack; }
n/a
function ArrayNode(items) { if (!(this instanceof ArrayNode)) { throw new SyntaxError('Constructor must be called with the new operator'); } this.items = items || []; // validate input if (!Array.isArray(this.items) || !this.items.every(function (item) {return item && item.isNode;})) { throw new TypeError('Array containing Nodes expected'); } // TODO: deprecated since v3, remove some day var deprecated = function () { throw new Error('Property `ArrayNode.nodes` is deprecated, use `ArrayNode.items` instead'); }; Object.defineProperty(this, 'nodes', { get: deprecated, set: deprecated }); }
n/a
function AssignmentNode(object, index, value) { if (!(this instanceof AssignmentNode)) { throw new SyntaxError('Constructor must be called with the new operator'); } this.object = object; this.index = value ? index : null; this.value = value ? value : index; // validate input if (!object || !(object.isSymbolNode || object.isAccessorNode)) { throw new TypeError('SymbolNode or AccessorNode expected as "object"'); } if (object && object.isSymbolNode && object.name === 'end') { throw new Error('Cannot assign to symbol "end"'); } if (this.index && !this.index.isIndexNode) { throw new TypeError('IndexNode expected as "index"'); } if (!this.value || !this.value.isNode) { throw new TypeError('Node expected as "value"'); } // readonly property name Object.defineProperty(this, 'name', { get: function () { if (this.index) { return (this.index.isObjectProperty()) ? this.index.getObjectProperty() : ''; } else { return this.object.name || ''; } }.bind(this), set: function () { throw new Error('Cannot assign a new name, name is read-only'); } }); }
n/a
function Decimal(v) { var e, i, t, x = this; // Decimal called without new. if (!(x instanceof Decimal)) return new Decimal(v); // Retain a reference to this Decimal constructor, and shadow Decimal.prototype.constructor // which points to Object. x.constructor = Decimal; // Duplicate. if (v instanceof Decimal) { x.s = v.s; x.e = v.e; x.d = (v = v.d) ? v.slice() : v; return; } t = typeof v; if (t === 'number') { if (v === 0) { x.s = 1 / v < 0 ? -1 : 1; x.e = 0; x.d = [0]; return; } if (v < 0) { v = -v; x.s = -1; } else { x.s = 1; } // Fast path for small integers. if (v === ~~v && v < 1e7) { for (e = 0, i = v; i >= 10; i /= 10) e++; x.e = e; x.d = [v]; return; // Infinity, NaN. } else if (v * 0 !== 0) { if (!v) x.s = NaN; x.e = NaN; x.d = null; return; } return parseDecimal(x, v.toString()); } else if (t !== 'string') { throw Error(invalidArgument + v); } // Minus sign? if (v.charCodeAt(0) === 45) { v = v.slice(1); x.s = -1; } else { x.s = 1; } return isDecimal.test(v) ? parseDecimal(x, v) : parseOther(x, v); }
...
setConstant(math, 'true', true);
setConstant(math, 'false', false);
setConstant(math, 'null', null);
setConstant(math, 'uninitialized', require('./utils/array').UNINITIALIZED);
if (config.number === 'BigNumber') {
setConstant(math, 'Infinity', new type.BigNumber(Infinity));
setConstant(math, 'NaN', new type.BigNumber(NaN));
setLazyConstant(math, 'pi', function () {return bigConstants.pi(type.BigNumber)});
setLazyConstant(math, 'tau', function () {return bigConstants.tau(type.BigNumber)});
setLazyConstant(math, 'e', function () {return bigConstants.e(type.BigNumber)});
setLazyConstant(math, 'phi', function () {return bigConstants.phi(type.BigNumber)}); // golden ratio, (1+sqrt(5))/2
...
function BlockNode(blocks) { if (!(this instanceof BlockNode)) { throw new SyntaxError('Constructor must be called with the new operator'); } // validate input, copy blocks if (!Array.isArray(blocks)) throw new Error('Array expected'); this.blocks = blocks.map(function (block) { var node = block && block.node; var visible = block && block.visible !== undefined ? block.visible : true; if (!(node && node.isNode)) throw new TypeError('Property "node" must be a Node'); if (typeof visible !== 'boolean') throw new TypeError('Property "visible" must be a boolean'); return { node: node, visible: visible } }); }
n/a
function Chain(value) { if (!(this instanceof Chain)) { throw new SyntaxError('Constructor must be called with the new operator'); } if (value && value.isChain) { this.value = value.value; } else { this.value = value; } }
n/a
function Complex(a, b) { if (!(this instanceof Complex)) { return new Complex(a, b); } parse(a, b); // mutates P this["re"] = P["re"]; this["im"] = P["im"]; }
...
}
return new type.BigNumber(x);
}
}, {
from: 'number',
to: 'Complex',
convert: function (x) {
return new type.Complex(x, 0);
}
}, {
from: 'number',
to: 'string',
convert: function (x) {
return x + '';
}
...
function ConditionalNode(condition, trueExpr, falseExpr) { if (!(this instanceof ConditionalNode)) { throw new SyntaxError('Constructor must be called with the new operator'); } if (!(condition && condition.isNode)) throw new TypeError('Parameter condition must be a Node'); if (!(trueExpr && trueExpr.isNode)) throw new TypeError('Parameter trueExpr must be a Node'); if (!(falseExpr && falseExpr.isNode)) throw new TypeError('Parameter falseExpr must be a Node'); this.condition = condition; this.trueExpr = trueExpr; this.falseExpr = falseExpr; }
n/a
function ConstantNode(value, valueType) { if (!(this instanceof ConstantNode)) { throw new SyntaxError('Constructor must be called with the new operator'); } if (valueType) { if (typeof valueType !== 'string') { throw new TypeError('String expected for parameter "valueType"'); } if (typeof value !== 'string') { throw new TypeError('String expected for parameter "value"'); } this.value = value; this.valueType = valueType; } else { // stringify the value and determine the type this.value = value + ''; this.valueType = getType(value); } if (!SUPPORTED_TYPES[this.valueType]) { throw new TypeError('Unsupported type of value "' + this.valueType + '"'); } }
n/a
function DenseMatrix(data, datatype) { if (!(this instanceof DenseMatrix)) throw new SyntaxError('Constructor must be called with the new operator'); if (datatype && !isString(datatype)) throw new Error('Invalid datatype: ' + datatype); if (data && data.isMatrix === true) { // check data is a DenseMatrix if (data.type === 'DenseMatrix') { // clone data & size this._data = object.clone(data._data); this._size = object.clone(data._size); this._datatype = datatype || data._datatype; } else { // build data from existing matrix this._data = data.toArray(); this._size = data.size(); this._datatype = datatype || data._datatype; } } else if (data && isArray(data.data) && isArray(data.size)) { // initialize fields from JSON representation this._data = data.data; this._size = data.size; this._datatype = datatype || data.datatype; } else if (isArray(data)) { // replace nested Matrices with Arrays this._data = preprocess(data); // get the dimensions of the array this._size = array.size(this._data); // verify the dimensions of the array, TODO: compute size while processing array array.validate(this._data, this._size); // data type unknown this._datatype = datatype; } else if (data) { // unsupported type throw new TypeError('Unsupported type of data (' + util.types.type(data) + ')'); } else { // nothing provided this._data = []; this._size = [0]; this._datatype = datatype; } }
...
return new type.Fraction(0);
}
}, {
from: 'Array',
to: 'Matrix',
convert: function (array) {
// TODO: how to decide on the right type of matrix to create?
return new type.DenseMatrix(array);
}
}, {
from: 'Matrix',
to: 'Array',
convert: function (matrix) {
return matrix.valueOf();
}
...
function DimensionError(actual, expected, relation) { if (!(this instanceof DimensionError)) { throw new SyntaxError('Constructor must be called with the new operator'); } this.actual = actual; this.expected = expected; this.relation = relation; this.message = 'Dimension mismatch (' + (Array.isArray(actual) ? ('[' + actual.join(', ') + ']') : actual) + ' ' + (this.relation || '!=') + ' ' + (Array.isArray(expected) ? ('[' + expected.join(', ') + ']') : expected) + ')'; this.stack = (new Error()).stack; }
n/a
function FibonacciHeap() { if (!(this instanceof FibonacciHeap)) throw new SyntaxError('Constructor must be called with the new operator'); // initialize fields this._minimum = null; this._size = 0; }
...
*/
function Spa() {
if (!(this instanceof Spa))
throw new SyntaxError('Constructor must be called with the new operator');
// allocate vector, TODO use typed arrays
this._values = [];
this._heap = new type.FibonacciHeap();
}
/**
* Attach type information
*/
Spa.prototype.type = 'Spa';
Spa.prototype.isSpa = true;
...
function Fraction(a, b) { if (!(this instanceof Fraction)) { return new Fraction(a, b); } parse(a, b); if (Fraction['REDUCE']) { a = gcd(P["d"], P["n"]); // Abuse a } else { a = 1; } this["s"] = P["s"]; this["n"] = P["n"] / a; this["d"] = P["d"] / a; }
...
to: 'Fraction',
convert: function (x) {
if (digits(x) > 15) {
throw new TypeError('Cannot implicitly convert a number with >15 significant digits to Fraction ' +
'(value: ' + x + '). ' +
'Use function fraction(x) to convert to Fraction.');
}
return new type.Fraction(x);
}
}, {
// FIXME: add conversion from Fraction to number, for example for `sqrt(fraction(1,3))`
// from: 'Fraction',
// to: 'number',
// convert: function (x) {
// return x.valueOf();
...
function FunctionAssignmentNode(name, params, expr) { if (!(this instanceof FunctionAssignmentNode)) { throw new SyntaxError('Constructor must be called with the new operator'); } // validate input if (typeof name !== 'string') throw new TypeError('String expected for parameter "name"'); if (!Array.isArray(params)) throw new TypeError('Array containing strings or objects expected for parameter "params"'); if (!(expr && expr.isNode)) throw new TypeError('Node expected for parameter "expr"'); if (name in keywords) throw new Error('Illegal function name, "' + name + '" is a reserved keyword'); this.name = name; this.params = params.map(function (param) { return param && param.name || param; }); this.types = params.map(function (param) { return param && param.type || 'any' }); this.expr = expr; }
n/a
function FunctionNode(fn, args) { if (!(this instanceof FunctionNode)) { throw new SyntaxError('Constructor must be called with the new operator'); } if (typeof fn === 'string') { fn = new SymbolNode(fn); } // validate input if (!fn || !fn.isNode) throw new TypeError('Node expected as parameter "fn"'); if (!Array.isArray(args) || !args.every(function (arg) {return arg && arg.isNode;})) { throw new TypeError('Array containing Nodes expected for parameter "args"'); } this.fn = fn; this.args = args || []; // readonly property name Object.defineProperty(this, 'name', { get: function () { return this.fn.name || ''; }.bind(this), set: function () { throw new Error('Cannot assign a new name, name is read-only'); } }); // TODO: deprecated since v3, remove some day var deprecated = function () { throw new Error('Property `FunctionNode.object` is deprecated, use `FunctionNode.fn` instead'); }; Object.defineProperty(this, 'object', { get: deprecated, set: deprecated }); }
n/a
function Help(doc) { if (!(this instanceof Help)) { throw new SyntaxError('Constructor must be called with the new operator'); } if (!doc) throw new Error('Argument "doc" missing'); this.doc = doc; }
n/a
function ImmutableDenseMatrix(data, datatype) { if (!(this instanceof ImmutableDenseMatrix)) throw new SyntaxError('Constructor must be called with the new operator'); if (datatype && !isString(datatype)) throw new Error('Invalid datatype: ' + datatype); if ((data && data.isMatrix === true) || isArray(data)) { // use DenseMatrix implementation var matrix = new DenseMatrix(data, datatype); // internal structures this._data = matrix._data; this._size = matrix._size; this._datatype = matrix._datatype; this._min = null; this._max = null; } else if (data && isArray(data.data) && isArray(data.size)) { // initialize fields from JSON representation this._data = data.data; this._size = data.size; this._datatype = data.datatype; this._min = typeof data.min !== 'undefined' ? data.min : null; this._max = typeof data.max !== 'undefined' ? data.max : null; } else if (data) { // unsupported type throw new TypeError('Unsupported type of data (' + util.types.type(data) + ')'); } else { // nothing provided this._data = []; this._size = [0]; this._datatype = datatype; this._min = null; this._max = null; } }
...
// loop array elements
for (var i = 0, l = arg.length; i < l; i++) {
if (typeof arg[i] !== 'number' || !isInteger(arg[i])) {
throw new TypeError('Index parameters must be positive integer numbers');
}
}
// create matrix
return new type.ImmutableDenseMatrix(arg);
}
/**
* Create a clone of the index
* @memberof Index
* @return {Index} clone
*/
...
function Index(ranges) { if (!(this instanceof Index)) { throw new SyntaxError('Constructor must be called with the new operator'); } this._dimensions = []; this._isScalar = true; for (var i = 0, ii = arguments.length; i < ii; i++) { var arg = arguments[i]; if (arg && (arg.isRange === true)) { this._dimensions.push(arg); this._isScalar = false; } else if (arg && (Array.isArray(arg) || arg.isMatrix === true)) { // create matrix var m = _createImmutableMatrix(arg.valueOf()); this._dimensions.push(m); // size var size = m.size(); // scalar if (size.length !== 1 || size[0] !== 1) { this._isScalar = false; } } else if (typeof arg === 'number') { this._dimensions.push(_createImmutableMatrix([arg])); } else if (typeof arg === 'string') { // object property (arguments.count should be 1) this._dimensions.push(arg); } // TODO: implement support for wildcard '*' else { throw new TypeError('Dimension must be an Array, Matrix, number, string, or Range'); } } }
...
else {
throw new TypeError('Dimension must be an Array, Matrix, number, string, or Range');
}
args[i] = arg;
}
var res = new type.Index();
type.Index.apply(res, args);
return res;
};
}
exports.name = 'index';
exports.path = 'expression.transform';
...
function IndexError(index, min, max) { if (!(this instanceof IndexError)) { throw new SyntaxError('Constructor must be called with the new operator'); } this.index = index; if (arguments.length < 3) { this.min = 0; this.max = min; } else { this.min = min; this.max = max; } if (this.min !== undefined && this.index < this.min) { this.message = 'Index out of range (' + this.index + ' < ' + this.min + ')'; } else if (this.max !== undefined && this.index >= this.max) { this.message = 'Index out of range (' + this.index + ' > ' + (this.max - 1) + ')'; } else { this.message = 'Index out of range (' + this.index + ')'; } this.stack = (new Error()).stack; }
n/a
function IndexNode(dimensions, dotNotation) { if (!(this instanceof IndexNode)) { throw new SyntaxError('Constructor must be called with the new operator'); } this.dimensions = dimensions; this.dotNotation = dotNotation || false; // validate input if (!isArray(dimensions) || !dimensions.every(function (range) {return range && range.isNode;})) { throw new TypeError('Array containing Nodes expected for parameter "dimensions"'); } if (this.dotNotation && !this.isObjectProperty()) { throw new Error('dotNotation only applicable for object properties'); } // TODO: deprecated since v3, remove some day var deprecated = function () { throw new Error('Property `IndexNode.object` is deprecated, use `IndexNode.fn` instead'); }; Object.defineProperty(this, 'object', { get: deprecated, set: deprecated }); }
n/a
function Matrix() { if (!(this instanceof Matrix)) { throw new SyntaxError('Constructor must be called with the new operator'); } }
n/a
function Node() { if (!(this instanceof Node)) { throw new SyntaxError('Constructor must be called with the new operator'); } }
n/a
function ObjectNode(properties) { if (!(this instanceof ObjectNode)) { throw new SyntaxError('Constructor must be called with the new operator'); } this.properties = properties || {}; // validate input if (properties) { if (!(typeof properties === 'object') || Object.keys(properties).some(function (key) { return !properties[key] || !properties[key].isNode; })) { throw new TypeError('Object containing Nodes expected'); } } }
n/a
function OperatorNode(op, fn, args, implicit) { if (!(this instanceof OperatorNode)) { throw new SyntaxError('Constructor must be called with the new operator'); } //validate input if (typeof op !== 'string') { throw new TypeError('string expected for parameter "op"'); } if (typeof fn !== 'string') { throw new TypeError('string expected for parameter "fn"'); } if (!Array.isArray(args) || !args.every(function (node) {return node && node.isNode;})) { throw new TypeError('Array containing Nodes expected for parameter "args"'); } this.implicit = (implicit === true); this.op = op; this.fn = fn; this.args = args || []; }
n/a
function ParenthesisNode(content) { if (!(this instanceof ParenthesisNode)) { throw new SyntaxError('Constructor must be called with the new operator'); } // validate input if (!(content && content.isNode)) { throw new TypeError('Node expected for parameter "content"'); } this.content = content; }
n/a
function Parser() { if (!(this instanceof Parser)) { throw new SyntaxError( 'Constructor must be called with the new operator'); } this.scope = {}; }
n/a
function Range(start, end, step) { if (!(this instanceof Range)) { throw new SyntaxError('Constructor must be called with the new operator'); } if (start != null) { if (start.isBigNumber === true) start = start.toNumber(); else if (typeof start !== 'number') throw new TypeError('Parameter start must be a number'); } if (end != null) { if (end.isBigNumber === true) end = end.toNumber(); else if (typeof end !== 'number') throw new TypeError('Parameter end must be a number'); } if (step != null) { if (step.isBigNumber === true) step = step.toNumber(); else if (typeof step !== 'number') throw new TypeError('Parameter step must be a number'); } this.start = (start != null) ? parseFloat(start) : 0; this.end = (end != null) ? parseFloat(end) : 0; this.step = (step != null) ? parseFloat(step) : 1; }
n/a
function RangeNode(start, end, step) { if (!(this instanceof RangeNode)) { throw new SyntaxError('Constructor must be called with the new operator'); } // validate inputs if (!(start && start.isNode)) throw new TypeError('Node expected'); if (!(end && end.isNode)) throw new TypeError('Node expected'); if (step && !(step && step.isNode)) throw new TypeError('Node expected'); if (arguments.length > 3) throw new Error('Too many arguments'); this.start = start; // included lower-bound this.end = end; // included upper-bound this.step = step || null; // optional step }
n/a
function ResultSet(entries) { if (!(this instanceof ResultSet)) { throw new SyntaxError('Constructor must be called with the new operator'); } this.entries = entries || []; }
n/a
function Spa() { if (!(this instanceof Spa)) throw new SyntaxError('Constructor must be called with the new operator'); // allocate vector, TODO use typed arrays this._values = []; this._heap = new type.FibonacciHeap(); }
n/a
function SparseMatrix(data, datatype) { if (!(this instanceof SparseMatrix)) throw new SyntaxError('Constructor must be called with the new operator'); if (datatype && !isString(datatype)) throw new Error('Invalid datatype: ' + datatype); if (data && data.isMatrix === true) { // create from matrix _createFromMatrix(this, data, datatype); } else if (data && isArray(data.index) && isArray(data.ptr) && isArray(data.size)) { // initialize fields this._values = data.values; this._index = data.index; this._ptr = data.ptr; this._size = data.size; this._datatype = datatype || data.datatype; } else if (isArray(data)) { // create from array _createFromArray(this, data, datatype); } else if (data) { // unsupported type throw new TypeError('Unsupported type of data (' + util.types.type(data) + ')'); } else { // nothing provided this._values = []; this._index = []; this._ptr = [0]; this._size = [0, 0]; this._datatype = datatype; } }
n/a
function SymbolNode(name) { if (!(this instanceof SymbolNode)) { throw new SyntaxError('Constructor must be called with the new operator'); } // validate input if (typeof name !== 'string') throw new TypeError('String expected for parameter "name"'); this.name = name; }
n/a
function Unit(value, name) { if (!(this instanceof Unit)) { throw new Error('Constructor must be called with the new operator'); } if (!(value === undefined || isNumeric(value) || value.isComplex)) { throw new TypeError('First parameter in Unit constructor must be number, BigNumber, Fraction, Complex, or undefined'); } if (name != undefined && (typeof name !== 'string' || name == '')) { throw new TypeError('Second parameter in Unit constructor must be a string'); } if (name != undefined) { var u = Unit.parse(name); this.units = u.units; this.dimensions = u.dimensions; } else { this.units = [ { unit: UNIT_NONE, prefix: PREFIXES.NONE, // link to a list with supported prefixes power: 0 } ]; this.dimensions = []; for(var i=0; i<BASE_DIMENSIONS.length; i++) { this.dimensions[i] = 0; } } this.value = (value != undefined) ? this._normalize(value) : null; this.fixPrefix = false; // if true, function format will not search for the // best prefix but leave it as initially provided. // fixPrefix is set true by the method Unit.to // The justification behind this is that if the constructor is explicitly called, // the caller wishes the units to be returned exactly as he supplied. this.isUnitListSimplified = true; }
n/a
function UpdateNode() { // TODO: deprecated since v3. Cleanup some day throw new Error('UpdateNode is deprecated. Use AssignmentNode instead.'); }
n/a
function abs(arg0) { "use strict"; var name = 'abs'; if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature0(arg0); // signature: number } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: Complex if (arguments.length === 1) { return signature1(arg0); // signature: Complex } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test2(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature2(arg0); // signature: BigNumber } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test3(arg0)) { // type: Fraction if (arguments.length === 1) { return signature3(arg0); // signature: Fraction } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test4(arg0)) { // type: Unit if (arguments.length === 1) { return signature4(arg0); // signature: Unit } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test5(arg0)) { // type: Array if (arguments.length === 1) { return signature5(arg0); // signature: Array } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test6(arg0)) { // type: Matrix if (arguments.length === 1) { return signature5(arg0); // signature: Matrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test7(arg0)) { // type: string (convert to number) if (arguments.length === 1) { return signature0(convert0(arg0)); // signature: string } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test8(arg0)) { // type: boolean (convert to number) if (arguments.length === 1) { return signature0(convert1(arg0)); // signature: boolean } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test9(arg0)) { // type: null (convert to number) if (arguments.length === 1) { return signature0(convert2(arg0)); // signature: null } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'number,Complex,BigNumber,Fraction,Unit,Array,Matrix'); }
...
function factory (type, config, load, typed) {
/**
* Calculate the absolute value of a number. For matrices, the function is
* evaluated element wise.
*
* Syntax:
*
* math.abs(x)
*
* Examples:
*
* math.abs(3.5); // returns number 3.5
* math.abs(-4.2); // returns number 4.2
*
* math.abs([3, -5, -1, 0, 2]); // returns Array [3, 5, 1, 0, 2]
...
function acos(arg0) { "use strict"; var name = 'acos'; if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature0(arg0); // signature: number } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: Complex if (arguments.length === 1) { return signature1(arg0); // signature: Complex } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test2(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature2(arg0); // signature: BigNumber } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test3(arg0)) { // type: Array if (arguments.length === 1) { return signature3(arg0); // signature: Array } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test4(arg0)) { // type: Matrix if (arguments.length === 1) { return signature3(arg0); // signature: Matrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test5(arg0)) { // type: Fraction (convert to BigNumber) if (arguments.length === 1) { return signature2(convert0(arg0)); // signature: Fraction } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test6(arg0)) { // type: string (convert to number) if (arguments.length === 1) { return signature0(convert1(arg0)); // signature: string } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test7(arg0)) { // type: boolean (convert to number) if (arguments.length === 1) { return signature0(convert2(arg0)); // signature: boolean } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test8(arg0)) { // type: null (convert to number) if (arguments.length === 1) { return signature0(convert3(arg0)); // signature: null } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'number,Complex,BigNumber,Array,Matrix'); }
...
/**
* Calculate the inverse cosine of a value.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.acos(x)
*
* Examples:
*
* math.acos(0.5); // returns number 1.0471975511965979
* math.acos(math.cos(1.5)); // returns number 1.5
*
* math.acos(2); // returns Complex 0 + 1.3169578969248166 i
...
function acosh(arg0) { "use strict"; var name = 'acosh'; if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature0(arg0); // signature: number } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: Complex if (arguments.length === 1) { return signature1(arg0); // signature: Complex } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test2(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature2(arg0); // signature: BigNumber } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test3(arg0)) { // type: Array if (arguments.length === 1) { return signature3(arg0); // signature: Array } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test4(arg0)) { // type: Matrix if (arguments.length === 1) { return signature3(arg0); // signature: Matrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test5(arg0)) { // type: Fraction (convert to BigNumber) if (arguments.length === 1) { return signature2(convert0(arg0)); // signature: Fraction } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test6(arg0)) { // type: string (convert to number) if (arguments.length === 1) { return signature0(convert1(arg0)); // signature: string } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test7(arg0)) { // type: boolean (convert to number) if (arguments.length === 1) { return signature0(convert2(arg0)); // signature: boolean } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test8(arg0)) { // type: null (convert to number) if (arguments.length === 1) { return signature0(convert3(arg0)); // signature: null } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'number,Complex,BigNumber,Array,Matrix'); }
...
* Calculate the hyperbolic arccos of a value,
* defined as `acosh(x) = ln(sqrt(x^2 - 1) + x)`.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.acosh(x)
*
* Examples:
*
* math.acosh(1.5); // returns 0.9624236501192069
*
* See also:
*
...
function acot(arg0) { "use strict"; var name = 'acot'; if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature0(arg0); // signature: number } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: Complex if (arguments.length === 1) { return signature1(arg0); // signature: Complex } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test2(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature2(arg0); // signature: BigNumber } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test3(arg0)) { // type: Array if (arguments.length === 1) { return signature3(arg0); // signature: Array } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test4(arg0)) { // type: Matrix if (arguments.length === 1) { return signature3(arg0); // signature: Matrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test5(arg0)) { // type: Fraction (convert to BigNumber) if (arguments.length === 1) { return signature2(convert0(arg0)); // signature: Fraction } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test6(arg0)) { // type: string (convert to number) if (arguments.length === 1) { return signature0(convert1(arg0)); // signature: string } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test7(arg0)) { // type: boolean (convert to number) if (arguments.length === 1) { return signature0(convert2(arg0)); // signature: boolean } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test8(arg0)) { // type: null (convert to number) if (arguments.length === 1) { return signature0(convert3(arg0)); // signature: null } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'number,Complex,BigNumber,Array,Matrix'); }
...
/**
* Calculate the inverse cotangent of a value, defined as `acot(x) = atan(1/x)`.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.acot(x)
*
* Examples:
*
* math.acot(0.5); // returns number 0.4636476090008061
* math.acot(math.cot(1.5)); // returns number 1.5
*
* math.acot(2); // returns Complex 1.5707963267948966 -1.3169578969248166 i
...
function acoth(arg0) { "use strict"; var name = 'acoth'; if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature0(arg0); // signature: number } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: Complex if (arguments.length === 1) { return signature1(arg0); // signature: Complex } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test2(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature2(arg0); // signature: BigNumber } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test3(arg0)) { // type: Array if (arguments.length === 1) { return signature3(arg0); // signature: Array } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test4(arg0)) { // type: Matrix if (arguments.length === 1) { return signature3(arg0); // signature: Matrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test5(arg0)) { // type: Fraction (convert to BigNumber) if (arguments.length === 1) { return signature2(convert0(arg0)); // signature: Fraction } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test6(arg0)) { // type: string (convert to number) if (arguments.length === 1) { return signature0(convert1(arg0)); // signature: string } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test7(arg0)) { // type: boolean (convert to number) if (arguments.length === 1) { return signature0(convert2(arg0)); // signature: boolean } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test8(arg0)) { // type: null (convert to number) if (arguments.length === 1) { return signature0(convert3(arg0)); // signature: null } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'number,Complex,BigNumber,Array,Matrix'); }
...
* Calculate the hyperbolic arccotangent of a value,
* defined as `acoth(x) = atanh(1/x) = (ln((x+1)/x) + ln(x/(x-1))) / 2`.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.acoth(x)
*
* Examples:
*
* math.acoth(0.5); // returns 0.8047189562170503
*
* See also:
*
...
function acsc(arg0) { "use strict"; var name = 'acsc'; if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature0(arg0); // signature: number } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: Complex if (arguments.length === 1) { return signature1(arg0); // signature: Complex } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test2(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature2(arg0); // signature: BigNumber } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test3(arg0)) { // type: Array if (arguments.length === 1) { return signature3(arg0); // signature: Array } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test4(arg0)) { // type: Matrix if (arguments.length === 1) { return signature3(arg0); // signature: Matrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test5(arg0)) { // type: Fraction (convert to BigNumber) if (arguments.length === 1) { return signature2(convert0(arg0)); // signature: Fraction } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test6(arg0)) { // type: string (convert to number) if (arguments.length === 1) { return signature0(convert1(arg0)); // signature: string } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test7(arg0)) { // type: boolean (convert to number) if (arguments.length === 1) { return signature0(convert2(arg0)); // signature: boolean } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test8(arg0)) { // type: null (convert to number) if (arguments.length === 1) { return signature0(convert3(arg0)); // signature: null } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'number,Complex,BigNumber,Array,Matrix'); }
...
/**
* Calculate the inverse cosecant of a value, defined as `acsc(x) = asin(1/x)`.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.acsc(x)
*
* Examples:
*
* math.acsc(0.5); // returns number 0.5235987755982989
* math.acsc(math.csc(1.5)); // returns number ~1.5
*
* math.acsc(2); // returns Complex 1.5707963267948966 -1.3169578969248166 i
...
function acsch(arg0) { "use strict"; var name = 'acsch'; if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature0(arg0); // signature: number } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: Complex if (arguments.length === 1) { return signature1(arg0); // signature: Complex } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test2(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature2(arg0); // signature: BigNumber } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test3(arg0)) { // type: Array if (arguments.length === 1) { return signature3(arg0); // signature: Array } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test4(arg0)) { // type: Matrix if (arguments.length === 1) { return signature3(arg0); // signature: Matrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test5(arg0)) { // type: Fraction (convert to BigNumber) if (arguments.length === 1) { return signature2(convert0(arg0)); // signature: Fraction } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test6(arg0)) { // type: string (convert to number) if (arguments.length === 1) { return signature0(convert1(arg0)); // signature: string } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test7(arg0)) { // type: boolean (convert to number) if (arguments.length === 1) { return signature0(convert2(arg0)); // signature: boolean } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test8(arg0)) { // type: null (convert to number) if (arguments.length === 1) { return signature0(convert3(arg0)); // signature: null } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'number,Complex,BigNumber,Array,Matrix'); }
...
* Calculate the hyperbolic arccosecant of a value,
* defined as `acsch(x) = asinh(1/x) = ln(1/x + sqrt(1/x^2 + 1))`.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.acsch(x)
*
* Examples:
*
* math.acsch(0.5); // returns 1.4436354751788103
*
* See also:
*
...
function add(arg0, arg1, arg2) { "use strict"; var name = 'add'; if (test0(arg0)) { // type: number if (test0(arg1)) { // type: number if (arguments.length === 2) { return signature0(arg0, arg1); // signature: number, number } } if (test1(arg1)) { // type: Complex if (arguments.length === 2) { return signature1(convert0(arg0), arg1); // signature: number, Complex } } if (test2(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature2(convert1(arg0), arg1); // signature: number, BigNumber } } if (test3(arg1)) { // type: Fraction if (arguments.length === 2) { return signature3(convert2(arg0), arg1); // signature: number, Fraction } } if (test4(arg1)) { // type: string (convert to number) if (arguments.length === 2) { return signature0(arg0, convert3(arg1)); // signature: number, string } } if (test5(arg1)) { // type: boolean (convert to number) if (arguments.length === 2) { return signature0(arg0, convert4(arg1)); // signature: number, boolean } } if (test6(arg1)) { // type: null (convert to number) if (arguments.length === 2) { return signature0(arg0, convert5(arg1)); // signature: number, null } } } if (test1(arg0)) { // type: Complex if (test1(arg1)) { // type: Complex if (arguments.length === 2) { return signature1(arg0, arg1); // signature: Complex, Complex } } if (test0(arg1)) { // type: number (convert to Complex) if (arguments.length === 2) { return signature1(arg0, convert0(arg1)); // signature: Complex, number } } if (test2(arg1)) { // type: BigNumber (convert to Complex) if (arguments.length === 2) { return signature1(arg0, convert6(arg1)); // signature: Complex, BigNumber } } if (test3(arg1)) { // type: Fraction (convert to Complex) if (arguments.length === 2) { return signature1(arg0, convert7(arg1)); // signature: Complex, Fraction } } if (test4(arg1)) { // type: string (convert to Complex) if (arguments.length === 2) { return signature1(arg0, convert8(arg1)); // signature: Complex, string } } } if (test2(arg0)) { // type: BigNumber if (test1(arg1)) { // type: Complex if (arguments.length === 2) { return signature1(convert6(arg0), arg1); // signature: BigNumber, Complex } } if (test2(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature2(arg0, arg1); // signature: BigNumber, BigNumber } } if (test0(arg1)) { // type: number (convert to BigNumber) if (arguments.length === 2) { return signature2(arg0, convert1(arg1)); // signature: BigNumber, number } } if (test3(arg1)) { // type: Fraction (convert to BigNumber) if (arguments.length === 2) { return signature2(arg0, convert9(arg1)); // signature: BigNumber, Fraction } } if (test4(arg1)) { // type: string (convert to BigNumber) if (arguments.length === 2) { return signature2(arg0, convert10(arg1)); // signature: BigNumber, string } } if (test5(arg1)) { // type: boolean (convert to BigNumber) if (arguments.length === 2) { return signature2(arg0, convert11(arg1)); // signature: BigNumber, boolean } } if (test6(arg1)) { // type: null (convert to BigNumber) if (arguments.length === 2) { return signature2(arg0, convert12(arg1)); // signature: BigNumber, null } } } if (test3(arg0)) { // type: Fraction if (test1(arg1)) { // type: Complex if (arguments.length === 2) { return signature1(convert7(arg0), arg1); // signature: Fraction, Complex } } if (test2(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature2(convert9(arg0), arg1); // signature: Fraction, BigNumber } } if (test3(arg1)) { // type: Fraction if (a ...
...
math.eval('5.08 cm to inch'); // 2 inch
math.eval('sin(45 deg) ^ 2'); // 0.5
math.eval('9 / 3 + 2i'); // 3 + 2i
math.eval('det([-1, 2; 3, 1])'); // -7
// chaining
math.chain(3)
.add(4)
.multiply(2)
.done(); // 14
```
## Browser support
Math.js works on any ES5 compatible JavaScript engine: node.js 0.10, and Internet Explorer 9 and newer, and all other browsers (
Chrome, Firefox, Safari). If support for old browsers like Internet Explorer 8 is required, the [es5-shim](https://github.com/kriskowal
/es5-shim) library has to be loaded.
...
function and(arg0, arg1) { "use strict"; var name = 'and'; if (test0(arg0)) { // type: number if (test0(arg1)) { // type: number if (arguments.length === 2) { return signature0(arg0, arg1); // signature: number, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test1(arg1)) { // type: Complex if (arguments.length === 2) { return signature1(convert0(arg0), arg1); // signature: number, Complex } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature2(convert1(arg0), arg1); // signature: number, BigNumber } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: Fraction (convert to BigNumber) if (arguments.length === 2) { return signature2(convert1(arg0), convert2(arg1)); // signature: number, Fraction } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test4(arg1)) { // type: string (convert to number) if (arguments.length === 2) { return signature0(arg0, convert3(arg1)); // signature: number, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test5(arg1)) { // type: boolean (convert to number) if (arguments.length === 2) { return signature0(arg0, convert4(arg1)); // signature: number, boolean } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test6(arg1)) { // type: null (convert to number) if (arguments.length === 2) { return signature0(arg0, convert5(arg1)); // signature: number, null } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } } if (test1(arg0)) { // type: Complex if (test1(arg1)) { // type: Complex if (arguments.length === 2) { return signature1(arg0, arg1); // signature: Complex, Complex } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test0(arg1)) { // type: number (convert to Complex) if (arguments.length === 2) { return signature1(arg0, convert0(arg1)); // signature: Complex, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: BigNumber (convert to Complex) if (arguments.length === 2) { return signature1(arg0, convert6(arg1)); // signature: Complex, BigNumber } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: Fraction (convert to Complex) if (arguments.length === 2) { return signature1(arg0, convert7(arg1)); // signature: Complex, Fraction } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test4(arg1)) { // type: string (convert to Complex) if (arguments.length === 2) { return signature1(arg0, convert8(arg1)); // signature: Complex, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } } if (test2(arg0)) { // type: BigNumber if (test1(arg1)) { // type: Complex if (arguments.length === 2) { return signature1(convert6(arg0), arg1); // signature: BigNumber, Complex } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature2(arg0, arg1); // ...
...
/**
* Logical `and`. Test whether two values are both defined with a nonzero/nonempty value.
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.and(x, y)
*
* Examples:
*
* math.and(2, 4); // returns true
*
* a = [2, 0, 0];
* b = [3, 7, 0];
...
function arg(arg0) { "use strict"; var name = 'arg'; if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature0(arg0); // signature: number } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: Complex if (arguments.length === 1) { return signature1(arg0); // signature: Complex } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test2(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature2(arg0); // signature: BigNumber } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test3(arg0)) { // type: Array if (arguments.length === 1) { return signature3(arg0); // signature: Array } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test4(arg0)) { // type: Matrix if (arguments.length === 1) { return signature3(arg0); // signature: Matrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test5(arg0)) { // type: Fraction (convert to BigNumber) if (arguments.length === 1) { return signature2(convert0(arg0)); // signature: Fraction } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test6(arg0)) { // type: string (convert to number) if (arguments.length === 1) { return signature0(convert1(arg0)); // signature: string } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test7(arg0)) { // type: boolean (convert to number) if (arguments.length === 1) { return signature0(convert2(arg0)); // signature: boolean } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test8(arg0)) { // type: null (convert to number) if (arguments.length === 1) { return signature0(convert3(arg0)); // signature: null } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'number,Complex,BigNumber,Array,Matrix'); }
...
* the principal root is returned.
* @returns {Complex | Array.<Complex> | Matrix.<Complex>} Returns the cubic root(s) of x
* @private
*/
function _cbrtComplex(x, allRoots) {
// https://www.wikiwand.com/en/Cube_root#/Complex_numbers
var arg_3 = x.arg() / 3;
var abs = x.abs();
// principal root:
var principal = new type.Complex(_cbrtNumber(abs), 0).mul(
new type.Complex(0, arg_3).exp());
if (allRoots) {
...
function asec(arg0) { "use strict"; var name = 'asec'; if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature0(arg0); // signature: number } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: Complex if (arguments.length === 1) { return signature1(arg0); // signature: Complex } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test2(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature2(arg0); // signature: BigNumber } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test3(arg0)) { // type: Array if (arguments.length === 1) { return signature3(arg0); // signature: Array } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test4(arg0)) { // type: Matrix if (arguments.length === 1) { return signature3(arg0); // signature: Matrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test5(arg0)) { // type: Fraction (convert to BigNumber) if (arguments.length === 1) { return signature2(convert0(arg0)); // signature: Fraction } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test6(arg0)) { // type: string (convert to number) if (arguments.length === 1) { return signature0(convert1(arg0)); // signature: string } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test7(arg0)) { // type: boolean (convert to number) if (arguments.length === 1) { return signature0(convert2(arg0)); // signature: boolean } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test8(arg0)) { // type: null (convert to number) if (arguments.length === 1) { return signature0(convert3(arg0)); // signature: null } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'number,Complex,BigNumber,Array,Matrix'); }
...
/**
* Calculate the inverse secant of a value. Defined as `asec(x) = acos(1/x)`.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.asec(x)
*
* Examples:
*
* math.asec(0.5); // returns 1.0471975511965979
* math.asec(math.sec(1.5)); // returns 1.5
*
* math.asec(2); // returns 0 + 1.3169578969248166 i
...
function asech(arg0) { "use strict"; var name = 'asech'; if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature0(arg0); // signature: number } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: Complex if (arguments.length === 1) { return signature1(arg0); // signature: Complex } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test2(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature2(arg0); // signature: BigNumber } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test3(arg0)) { // type: Array if (arguments.length === 1) { return signature3(arg0); // signature: Array } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test4(arg0)) { // type: Matrix if (arguments.length === 1) { return signature3(arg0); // signature: Matrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test5(arg0)) { // type: Fraction (convert to BigNumber) if (arguments.length === 1) { return signature2(convert0(arg0)); // signature: Fraction } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test6(arg0)) { // type: string (convert to number) if (arguments.length === 1) { return signature0(convert1(arg0)); // signature: string } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test7(arg0)) { // type: boolean (convert to number) if (arguments.length === 1) { return signature0(convert2(arg0)); // signature: boolean } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test8(arg0)) { // type: null (convert to number) if (arguments.length === 1) { return signature0(convert3(arg0)); // signature: null } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'number,Complex,BigNumber,Array,Matrix'); }
...
* Calculate the hyperbolic arcsecant of a value,
* defined as `asech(x) = acosh(1/x) = ln(sqrt(1/x^2 - 1) + 1/x)`.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.asech(x)
*
* Examples:
*
* math.asech(0.5); // returns 1.3169578969248166
*
* See also:
*
...
function asin(arg0) { "use strict"; var name = 'asin'; if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature0(arg0); // signature: number } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: Complex if (arguments.length === 1) { return signature1(arg0); // signature: Complex } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test2(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature2(arg0); // signature: BigNumber } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test3(arg0)) { // type: Array if (arguments.length === 1) { return signature3(arg0); // signature: Array } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test4(arg0)) { // type: Matrix if (arguments.length === 1) { return signature3(arg0); // signature: Matrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test5(arg0)) { // type: Fraction (convert to BigNumber) if (arguments.length === 1) { return signature2(convert0(arg0)); // signature: Fraction } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test6(arg0)) { // type: string (convert to number) if (arguments.length === 1) { return signature0(convert1(arg0)); // signature: string } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test7(arg0)) { // type: boolean (convert to number) if (arguments.length === 1) { return signature0(convert2(arg0)); // signature: boolean } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test8(arg0)) { // type: null (convert to number) if (arguments.length === 1) { return signature0(convert3(arg0)); // signature: null } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'number,Complex,BigNumber,Array,Matrix'); }
...
*
* @param {number | Complex | Array | Matrix} x Function input
* @return {number | Complex | Array | Matrix} The arc cosecant of x
*/
var acsc = typed('acsc', {
'number': function (x) {
if (x <= -1 || x >= 1 || config.predictable) {
return Math.asin(1 / x);
}
return new type.Complex(x, 0).acsc();
},
'Complex': function (x) {
return x.acsc();
},
...
function asinh(arg0) { "use strict"; var name = 'asinh'; if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature0(arg0); // signature: number } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: Complex if (arguments.length === 1) { return signature1(arg0); // signature: Complex } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test2(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature2(arg0); // signature: BigNumber } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test3(arg0)) { // type: Array if (arguments.length === 1) { return signature3(arg0); // signature: Array } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test4(arg0)) { // type: Matrix if (arguments.length === 1) { return signature3(arg0); // signature: Matrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test5(arg0)) { // type: Fraction (convert to BigNumber) if (arguments.length === 1) { return signature2(convert0(arg0)); // signature: Fraction } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test6(arg0)) { // type: string (convert to number) if (arguments.length === 1) { return signature0(convert1(arg0)); // signature: string } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test7(arg0)) { // type: boolean (convert to number) if (arguments.length === 1) { return signature0(convert2(arg0)); // signature: boolean } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test8(arg0)) { // type: null (convert to number) if (arguments.length === 1) { return signature0(convert3(arg0)); // signature: null } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'number,Complex,BigNumber,Array,Matrix'); }
...
},
'Complex': function (x) {
return x.acsch();
},
'BigNumber': function (x) {
return new type.BigNumber(1).div(x).asinh();
},
'Array | Matrix': function (x) {
return deepMap(x, acsch);
}
});
...
function atan(arg0) { "use strict"; var name = 'atan'; if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature0(arg0); // signature: number } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: Complex if (arguments.length === 1) { return signature1(arg0); // signature: Complex } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test2(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature2(arg0); // signature: BigNumber } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test3(arg0)) { // type: Array if (arguments.length === 1) { return signature3(arg0); // signature: Array } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test4(arg0)) { // type: Matrix if (arguments.length === 1) { return signature3(arg0); // signature: Matrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test5(arg0)) { // type: Fraction (convert to BigNumber) if (arguments.length === 1) { return signature2(convert0(arg0)); // signature: Fraction } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test6(arg0)) { // type: string (convert to number) if (arguments.length === 1) { return signature0(convert1(arg0)); // signature: string } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test7(arg0)) { // type: boolean (convert to number) if (arguments.length === 1) { return signature0(convert2(arg0)); // signature: boolean } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test8(arg0)) { // type: null (convert to number) if (arguments.length === 1) { return signature0(convert3(arg0)); // signature: null } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'number,Complex,BigNumber,Array,Matrix'); }
...
* cot, atan
*
* @param {number | Complex | Array | Matrix} x Function input
* @return {number | Complex | Array | Matrix} The arc cotangent of x
*/
var acot = typed('acot', {
'number': function (x) {
return Math.atan(1 / x);
},
'Complex': function (x) {
return x.acot();
},
'BigNumber': function (x) {
...
function atan2(arg0, arg1) { "use strict"; var name = 'atan2'; if (test0(arg0)) { // type: number if (test0(arg1)) { // type: number if (arguments.length === 2) { return signature0(arg0, arg1); // signature: number, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test1(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature1(convert0(arg0), arg1); // signature: number, BigNumber } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: Array if (arguments.length === 2) { return signature2(arg0, arg1); // signature: number, Array } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: Matrix if (arguments.length === 2) { return signature3(arg0, arg1); // signature: number, Matrix } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test4(arg1)) { // type: Fraction (convert to BigNumber) if (arguments.length === 2) { return signature1(convert0(arg0), convert1(arg1)); // signature: number, Fraction } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test5(arg1)) { // type: string (convert to number) if (arguments.length === 2) { return signature0(arg0, convert2(arg1)); // signature: number, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test6(arg1)) { // type: boolean (convert to number) if (arguments.length === 2) { return signature0(arg0, convert3(arg1)); // signature: number, boolean } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test7(arg1)) { // type: null (convert to number) if (arguments.length === 2) { return signature0(arg0, convert4(arg1)); // signature: number, null } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'number,BigNumber,Array,Matrix'); } if (test1(arg0)) { // type: BigNumber if (test1(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature1(arg0, arg1); // signature: BigNumber, BigNumber } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: Array if (arguments.length === 2) { return signature2(arg0, arg1); // signature: BigNumber, Array } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: Matrix if (arguments.length === 2) { return signature3(arg0, arg1); // signature: BigNumber, Matrix } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test0(arg1)) { // type: number (convert to BigNumber) if (arguments.length === 2) { return signature1(arg0, convert0(arg1)); // signature: BigNumber, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test4(arg1)) { // type: Fraction (convert to BigNumber) if (arguments.length === 2) { return signature1(arg0, convert1(arg1)); // signature: BigNumber, Fraction } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test5(arg1)) { // type: string (convert to BigNumber) if (arguments.length === 2) { return signature1(arg0, convert5(arg ...
...
```js
// load math.js
var math = require('mathjs');
// functions and constants
math.round(math.e, 3); // 2.718
math.atan2(3, -3) / math.pi; // 0.75
math.log(1000, 10); // 3
math.sqrt(-4); // 2i
math.pow([[-1, 2], [3, 1]], 2); // [[7, 0], [0, 7]]
math.derivative('x^2 + x', 'x'); // 2 * x + 1
// expressions
math.eval('12 / (2.3 + 0.7)'); // 4
...
function atanh(arg0) { "use strict"; var name = 'atanh'; if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature0(arg0); // signature: number } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: Complex if (arguments.length === 1) { return signature1(arg0); // signature: Complex } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test2(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature2(arg0); // signature: BigNumber } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test3(arg0)) { // type: Array if (arguments.length === 1) { return signature3(arg0); // signature: Array } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test4(arg0)) { // type: Matrix if (arguments.length === 1) { return signature3(arg0); // signature: Matrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test5(arg0)) { // type: Fraction (convert to BigNumber) if (arguments.length === 1) { return signature2(convert0(arg0)); // signature: Fraction } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test6(arg0)) { // type: string (convert to number) if (arguments.length === 1) { return signature0(convert1(arg0)); // signature: string } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test7(arg0)) { // type: boolean (convert to number) if (arguments.length === 1) { return signature0(convert2(arg0)); // signature: boolean } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test8(arg0)) { // type: null (convert to number) if (arguments.length === 1) { return signature0(convert3(arg0)); // signature: null } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'number,Complex,BigNumber,Array,Matrix'); }
...
},
'Complex': function (x) {
return x.acoth();
},
'BigNumber': function (x) {
return new type.BigNumber(1).div(x).atanh();
},
'Array | Matrix': function (x) {
return deepMap(x, acoth);
}
});
...
function bellNumbers(arg0) { "use strict"; var name = 'bellNumbers'; if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature0(arg0); // signature: number } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature0(arg0); // signature: BigNumber } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test2(arg0)) { // type: Fraction (convert to BigNumber) if (arguments.length === 1) { return signature0(convert0(arg0)); // signature: Fraction } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test3(arg0)) { // type: string (convert to number) if (arguments.length === 1) { return signature0(convert1(arg0)); // signature: string } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test4(arg0)) { // type: boolean (convert to number) if (arguments.length === 1) { return signature0(convert2(arg0)); // signature: boolean } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test5(arg0)) { // type: null (convert to number) if (arguments.length === 1) { return signature0(convert3(arg0)); // signature: null } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'number,BigNumber'); }
...
/**
* The Bell Numbers count the number of partitions of a set. A partition is a pairwise disjoint subset of S whose union is S.
* bellNumbers only takes integer arguments.
* The following condition must be enforced: n >= 0
*
* Syntax:
*
* math.bellNumbers(n)
*
* Examples:
*
* math.bellNumbers(3); // returns 5;
* math.bellNumbers(8); // returns 4140;
*
* See also:
...
function bignumber(arg0) { "use strict"; var name = 'bignumber'; if (arguments.length === 0) { return signature0(); // signature: } if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature1(arg0); // signature: number } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature2(arg0); // signature: BigNumber } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test2(arg0)) { // type: Fraction if (arguments.length === 1) { return signature3(arg0); // signature: Fraction } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test3(arg0)) { // type: string if (arguments.length === 1) { return signature4(arg0); // signature: string } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test4(arg0)) { // type: Array if (arguments.length === 1) { return signature5(arg0); // signature: Array } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test5(arg0)) { // type: Matrix if (arguments.length === 1) { return signature5(arg0); // signature: Matrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test6(arg0)) { // type: boolean (convert to number) if (arguments.length === 1) { return signature1(convert0(arg0)); // signature: boolean } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test7(arg0)) { // type: null (convert to number) if (arguments.length === 1) { return signature1(convert1(arg0)); // signature: null } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'number,BigNumber,Fraction,string,Array,Matrix'); }
...
*/
ConstantNode.prototype._compile = function (defs, args) {
switch (this.valueType) {
case 'number':
// TODO: replace this with using config.number
var numConfig = defs.math.config().number;
if (numConfig === 'BigNumber') {
return 'math.bignumber("' + this.value + '")';
}
else if (numConfig === 'Fraction') {
return 'math.fraction("' + this.value + '")';
}
else {
// remove leading zeros like '003.2' which are not allowed by JavaScript
return this.value.replace(/^(0*)[0-9]/, function (match, zeros) {
...
function bitAnd(arg0, arg1) { "use strict"; var name = 'bitAnd'; if (test0(arg0)) { // type: number if (test0(arg1)) { // type: number if (arguments.length === 2) { return signature0(arg0, arg1); // signature: number, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test1(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature1(convert0(arg0), arg1); // signature: number, BigNumber } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: Fraction (convert to BigNumber) if (arguments.length === 2) { return signature1(convert0(arg0), convert1(arg1)); // signature: number, Fraction } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: string (convert to number) if (arguments.length === 2) { return signature0(arg0, convert2(arg1)); // signature: number, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test4(arg1)) { // type: boolean (convert to number) if (arguments.length === 2) { return signature0(arg0, convert3(arg1)); // signature: number, boolean } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test5(arg1)) { // type: null (convert to number) if (arguments.length === 2) { return signature0(arg0, convert4(arg1)); // signature: number, null } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } } if (test1(arg0)) { // type: BigNumber if (test1(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature1(arg0, arg1); // signature: BigNumber, BigNumber } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test0(arg1)) { // type: number (convert to BigNumber) if (arguments.length === 2) { return signature1(arg0, convert0(arg1)); // signature: BigNumber, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: Fraction (convert to BigNumber) if (arguments.length === 2) { return signature1(arg0, convert1(arg1)); // signature: BigNumber, Fraction } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: string (convert to BigNumber) if (arguments.length === 2) { return signature1(arg0, convert5(arg1)); // signature: BigNumber, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test4(arg1)) { // type: boolean (convert to BigNumber) if (arguments.length === 2) { return signature1(arg0, convert6(arg1)); // signature: BigNumber, boolean } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test5(arg1)) { // type: null (convert to BigNumber) if (arguments.length === 2) { return signature1(arg0, convert7(arg1)); // signature: BigNumber, null } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } } if (test6(arg0)) { // type: Array if (test6(arg1)) { // type: Array if (arguments.length === 2) { return signature2(arg0, arg1); // signature: Array, Array } } if (test7(arg1)) { // type: Matrix if (arguments.length === 2) { return signature3(arg0, arg1); // signature: Array, Matrix } } // type: any if (arguments.length === 2) { ...
...
/**
* Bitwise AND two values, `x & y`.
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.bitAnd(x, y)
*
* Examples:
*
* math.bitAnd(53, 131); // returns number 1
*
* math.bitAnd([1, 12, 31], 42); // returns Array [0, 8, 10]
*
...
function bitNot(arg0) { "use strict"; var name = 'bitNot'; if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature0(arg0); // signature: number } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature1(arg0); // signature: BigNumber } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test2(arg0)) { // type: Array if (arguments.length === 1) { return signature2(arg0); // signature: Array } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test3(arg0)) { // type: Matrix if (arguments.length === 1) { return signature2(arg0); // signature: Matrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test4(arg0)) { // type: Fraction (convert to BigNumber) if (arguments.length === 1) { return signature1(convert0(arg0)); // signature: Fraction } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test5(arg0)) { // type: string (convert to number) if (arguments.length === 1) { return signature0(convert1(arg0)); // signature: string } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test6(arg0)) { // type: boolean (convert to number) if (arguments.length === 1) { return signature0(convert2(arg0)); // signature: boolean } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test7(arg0)) { // type: null (convert to number) if (arguments.length === 1) { return signature0(convert3(arg0)); // signature: null } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'number,BigNumber,Array,Matrix'); }
...
/**
* Bitwise NOT value, `~x`.
* For matrices, the function is evaluated element wise.
* For units, the function is evaluated on the best prefix base.
*
* Syntax:
*
* math.bitNot(x)
*
* Examples:
*
* math.bitNot(1); // returns number -2
*
* math.bitNot([2, -3, 4]); // returns Array [-3, 2, 5]
*
...
function bitOr(arg0, arg1) { "use strict"; var name = 'bitOr'; if (test0(arg0)) { // type: number if (test0(arg1)) { // type: number if (arguments.length === 2) { return signature0(arg0, arg1); // signature: number, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test1(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature1(convert0(arg0), arg1); // signature: number, BigNumber } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: Fraction (convert to BigNumber) if (arguments.length === 2) { return signature1(convert0(arg0), convert1(arg1)); // signature: number, Fraction } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: string (convert to number) if (arguments.length === 2) { return signature0(arg0, convert2(arg1)); // signature: number, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test4(arg1)) { // type: boolean (convert to number) if (arguments.length === 2) { return signature0(arg0, convert3(arg1)); // signature: number, boolean } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test5(arg1)) { // type: null (convert to number) if (arguments.length === 2) { return signature0(arg0, convert4(arg1)); // signature: number, null } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } } if (test1(arg0)) { // type: BigNumber if (test1(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature1(arg0, arg1); // signature: BigNumber, BigNumber } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test0(arg1)) { // type: number (convert to BigNumber) if (arguments.length === 2) { return signature1(arg0, convert0(arg1)); // signature: BigNumber, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: Fraction (convert to BigNumber) if (arguments.length === 2) { return signature1(arg0, convert1(arg1)); // signature: BigNumber, Fraction } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: string (convert to BigNumber) if (arguments.length === 2) { return signature1(arg0, convert5(arg1)); // signature: BigNumber, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test4(arg1)) { // type: boolean (convert to BigNumber) if (arguments.length === 2) { return signature1(arg0, convert6(arg1)); // signature: BigNumber, boolean } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test5(arg1)) { // type: null (convert to BigNumber) if (arguments.length === 2) { return signature1(arg0, convert7(arg1)); // signature: BigNumber, null } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } } if (test6(arg0)) { // type: Array if (test6(arg1)) { // type: Array if (arguments.length === 2) { return signature2(arg0, arg1); // signature: Array, Array } } if (test7(arg1)) { // type: Matrix if (arguments.length === 2) { return signature3(arg0, arg1); // signature: Array, Matrix } } // type: any if (arguments.length === 2) { ...
...
/**
* Bitwise OR two values, `x | y`.
* For matrices, the function is evaluated element wise.
* For units, the function is evaluated on the lowest print base.
*
* Syntax:
*
* math.bitOr(x, y)
*
* Examples:
*
* math.bitOr(1, 2); // returns number 3
*
* math.bitOr([1, 2, 3], 4); // returns Array [5, 6, 7]
*
...
function bitXor(arg0, arg1) { "use strict"; var name = 'bitXor'; if (test0(arg0)) { // type: number if (test0(arg1)) { // type: number if (arguments.length === 2) { return signature0(arg0, arg1); // signature: number, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test1(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature1(convert0(arg0), arg1); // signature: number, BigNumber } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: Fraction (convert to BigNumber) if (arguments.length === 2) { return signature1(convert0(arg0), convert1(arg1)); // signature: number, Fraction } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: string (convert to number) if (arguments.length === 2) { return signature0(arg0, convert2(arg1)); // signature: number, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test4(arg1)) { // type: boolean (convert to number) if (arguments.length === 2) { return signature0(arg0, convert3(arg1)); // signature: number, boolean } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test5(arg1)) { // type: null (convert to number) if (arguments.length === 2) { return signature0(arg0, convert4(arg1)); // signature: number, null } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } } if (test1(arg0)) { // type: BigNumber if (test1(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature1(arg0, arg1); // signature: BigNumber, BigNumber } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test0(arg1)) { // type: number (convert to BigNumber) if (arguments.length === 2) { return signature1(arg0, convert0(arg1)); // signature: BigNumber, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: Fraction (convert to BigNumber) if (arguments.length === 2) { return signature1(arg0, convert1(arg1)); // signature: BigNumber, Fraction } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: string (convert to BigNumber) if (arguments.length === 2) { return signature1(arg0, convert5(arg1)); // signature: BigNumber, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test4(arg1)) { // type: boolean (convert to BigNumber) if (arguments.length === 2) { return signature1(arg0, convert6(arg1)); // signature: BigNumber, boolean } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test5(arg1)) { // type: null (convert to BigNumber) if (arguments.length === 2) { return signature1(arg0, convert7(arg1)); // signature: BigNumber, null } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } } if (test6(arg0)) { // type: Array if (test6(arg1)) { // type: Array if (arguments.length === 2) { return signature2(arg0, arg1); // signature: Array, Array } } if (test7(arg1)) { // type: Matrix if (arguments.length === 2) { return signature3(arg0, arg1); // signature: Array, Matrix } } // type: any if (arguments.length === 2) { ...
...
/**
* Bitwise XOR two values, `x ^ y`.
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.bitXor(x, y)
*
* Examples:
*
* math.bitXor(1, 2); // returns number 3
*
* math.bitXor([2, 3, 4], 4); // returns Array [6, 7, 0]
*
...
function bool(arg0) { "use strict"; var name = 'bool'; if (arguments.length === 0) { return signature0(); // signature: } if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature1(arg0); // signature: number } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature2(arg0); // signature: BigNumber } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test2(arg0)) { // type: string if (arguments.length === 1) { return signature3(arg0); // signature: string } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test3(arg0)) { // type: Array if (arguments.length === 1) { return signature4(arg0); // signature: Array } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test4(arg0)) { // type: Matrix if (arguments.length === 1) { return signature4(arg0); // signature: Matrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test5(arg0)) { // type: boolean if (arguments.length === 1) { return signature5(arg0); // signature: boolean } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test6(arg0)) { // type: Fraction (convert to BigNumber) if (arguments.length === 1) { return signature2(convert0(arg0)); // signature: Fraction } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test7(arg0)) { // type: null (convert to number) if (arguments.length === 1) { return signature1(convert1(arg0)); // signature: null } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'number,BigNumber,string,Array,Matrix,boolean'); }
...
* In case of a number, `true` is returned for non-zero numbers, and `false` in
* case of zero.
* Strings can be `'true'` or `'false'`, or can contain a number.
* When value is a matrix, all elements will be converted to boolean.
*
* Syntax:
*
* math.boolean(x)
*
* Examples:
*
* math.boolean(0); // returns false
* math.boolean(1); // returns true
* math.boolean(-3); // returns true
* math.boolean('true'); // returns true
...
function catalan(arg0) { "use strict"; var name = 'catalan'; if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature0(arg0); // signature: number } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature0(arg0); // signature: BigNumber } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test2(arg0)) { // type: Fraction (convert to BigNumber) if (arguments.length === 1) { return signature0(convert0(arg0)); // signature: Fraction } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test3(arg0)) { // type: string (convert to number) if (arguments.length === 1) { return signature0(convert1(arg0)); // signature: string } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test4(arg0)) { // type: boolean (convert to number) if (arguments.length === 1) { return signature0(convert2(arg0)); // signature: boolean } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test5(arg0)) { // type: null (convert to number) if (arguments.length === 1) { return signature0(convert3(arg0)); // signature: null } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'number,BigNumber'); }
...
/**
* The Catalan Numbers enumerate combinatorial structures of many different types.
* catalan only takes integer arguments.
* The following condition must be enforced: n >= 0
*
* Syntax:
*
* math.catalan(n)
*
* Examples:
*
* math.catalan(3); // returns 5;
* math.catalan(8); // returns 1430;
*
* See also:
...
function cbrt(arg0, arg1) { "use strict"; var name = 'cbrt'; if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature0(arg0); // signature: number } if (test1(arg1)) { // type: boolean if (arguments.length === 2) { return signature1(convert0(arg0), arg1); // signature: number, boolean } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'boolean'); } if (test2(arg0)) { // type: Complex if (arguments.length === 1) { return signature1(arg0); // signature: Complex } if (test1(arg1)) { // type: boolean if (arguments.length === 2) { return signature1(arg0, arg1); // signature: Complex, boolean } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'boolean'); } if (test3(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature2(arg0); // signature: BigNumber } if (test1(arg1)) { // type: boolean if (arguments.length === 2) { return signature1(convert1(arg0), arg1); // signature: BigNumber, boolean } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'boolean'); } if (test4(arg0)) { // type: Unit if (arguments.length === 1) { return signature3(arg0); // signature: Unit } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test5(arg0)) { // type: Array if (arguments.length === 1) { return signature4(arg0); // signature: Array } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test6(arg0)) { // type: Matrix if (arguments.length === 1) { return signature4(arg0); // signature: Matrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test7(arg0)) { // type: Fraction (convert to BigNumber) if (arguments.length === 1) { return signature2(convert2(arg0)); // signature: Fraction } if (test1(arg1)) { // type: boolean if (arguments.length === 2) { return signature1(convert3(arg0), arg1); // signature: Fraction, boolean } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'boolean'); } if (test8(arg0)) { // type: string (convert to number) if (arguments.length === 1) { return signature0(convert4(arg0)); // signature: string } if (test1(arg1)) { // type: boolean if (arguments.length === 2) { return signature1(convert5(arg0), arg1); // signature: string, boolean } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'boolean'); } if (test1(arg0)) { // type: boolean (convert to number) if (arguments.length === 1) { return signature0(convert6(arg0)); // signature: boolean } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test9(arg0)) { // type: null (convert to number) if (arguments.length === 1) { return signature0(convert7(arg0)); // signature: null } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'number,Complex,BigNumber,Unit,Array,Matrix'); }
...
/**
* Calculate the cubic root of a value.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.cbrt(x)
* math.cbrt(x, allRoots)
*
* Examples:
*
* math.cbrt(27); // returns 3
* math.cube(3); // returns 27
* math.cbrt(-64); // returns -4
...
function ceil(arg0) { "use strict"; var name = 'ceil'; if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature0(arg0); // signature: number } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: Complex if (arguments.length === 1) { return signature1(arg0); // signature: Complex } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test2(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature2(arg0); // signature: BigNumber } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test3(arg0)) { // type: Fraction if (arguments.length === 1) { return signature3(arg0); // signature: Fraction } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test4(arg0)) { // type: Array if (arguments.length === 1) { return signature4(arg0); // signature: Array } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test5(arg0)) { // type: Matrix if (arguments.length === 1) { return signature4(arg0); // signature: Matrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test6(arg0)) { // type: string (convert to number) if (arguments.length === 1) { return signature0(convert0(arg0)); // signature: string } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test7(arg0)) { // type: boolean (convert to number) if (arguments.length === 1) { return signature0(convert1(arg0)); // signature: boolean } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test8(arg0)) { // type: null (convert to number) if (arguments.length === 1) { return signature0(convert2(arg0)); // signature: null } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'number,Complex,BigNumber,Fraction,Array,Matrix'); }
...
/**
* Round a value towards plus infinity
* If `x` is complex, both real and imaginary part are rounded towards plus infinity.
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.ceil(x)
*
* Examples:
*
* math.ceil(3.2); // returns number 4
* math.ceil(3.8); // returns number 4
* math.ceil(-4.2); // returns number -4
* math.ceil(-4.7); // returns number -4
...
function chain(arg0) { "use strict"; var name = 'chain'; if (arguments.length === 0) { return signature0(); // signature: } // type: any if (arguments.length === 1) { return signature1(arg0); // signature: any } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } throw createError(name, arguments.length, 0, arguments[0], 'any'); }
...
math.eval('12 / (2.3 + 0.7)'); // 4
math.eval('5.08 cm to inch'); // 2 inch
math.eval('sin(45 deg) ^ 2'); // 0.5
math.eval('9 / 3 + 2i'); // 3 + 2i
math.eval('det([-1, 2; 3, 1])'); // -7
// chaining
math.chain(3)
.add(4)
.multiply(2)
.done(); // 14
```
## Browser support
...
function clone(arg0) { "use strict"; var name = 'clone'; // type: any if (arguments.length === 1) { return signature0(arg0); // signature: any } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } throw createError(name, arguments.length, 0, arguments[0], 'any'); }
...
return desc;
};
/**
* Export the help object to JSON
*/
Help.prototype.toJSON = function () {
var obj = object.clone(this.doc);
obj.mathjs = 'Help';
return obj;
};
/**
* Instantiate a Help object from a JSON object
* @param {Object} json
...
function combinations(arg0, arg1) { "use strict"; var name = 'combinations'; if (test0(arg0)) { // type: number if (test0(arg1)) { // type: number if (arguments.length === 2) { return signature0(arg0, arg1); // signature: number, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test1(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature1(convert0(arg0), arg1); // signature: number, BigNumber } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: Fraction (convert to BigNumber) if (arguments.length === 2) { return signature1(convert0(arg0), convert1(arg1)); // signature: number, Fraction } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: string (convert to number) if (arguments.length === 2) { return signature0(arg0, convert2(arg1)); // signature: number, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test4(arg1)) { // type: boolean (convert to number) if (arguments.length === 2) { return signature0(arg0, convert3(arg1)); // signature: number, boolean } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test5(arg1)) { // type: null (convert to number) if (arguments.length === 2) { return signature0(arg0, convert4(arg1)); // signature: number, null } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'number,BigNumber'); } if (test1(arg0)) { // type: BigNumber if (test1(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature1(arg0, arg1); // signature: BigNumber, BigNumber } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test0(arg1)) { // type: number (convert to BigNumber) if (arguments.length === 2) { return signature1(arg0, convert0(arg1)); // signature: BigNumber, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: Fraction (convert to BigNumber) if (arguments.length === 2) { return signature1(arg0, convert1(arg1)); // signature: BigNumber, Fraction } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: string (convert to BigNumber) if (arguments.length === 2) { return signature1(arg0, convert5(arg1)); // signature: BigNumber, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test4(arg1)) { // type: boolean (convert to BigNumber) if (arguments.length === 2) { return signature1(arg0, convert6(arg1)); // signature: BigNumber, boolean } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test5(arg1)) { // type: null (convert to BigNumber) if (arguments.length === 2) { return signature1(arg0, convert7(arg1)); // signature: BigNumber, null } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'BigNumber'); } if (test2(arg0)) { // type: Fraction (convert to BigNumber) if (test1(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature1(convert1(arg0), arg1); // signature: Fraction, BigNumber ...
...
* possibilities.
*
* Combinations only takes integer arguments.
* The following condition must be enforced: k <= n.
*
* Syntax:
*
* math.combinations(n, k)
*
* Examples:
*
* math.combinations(7, 5); // returns 21
*
* See also:
*
...
function compare(arg0, arg1) { "use strict"; var name = 'compare'; if (test0(arg0)) { // type: number if (test0(arg1)) { // type: number if (arguments.length === 2) { return signature0(arg0, arg1); // signature: number, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test1(arg1)) { // type: Complex if (arguments.length === 2) { return signature1(convert0(arg0), arg1); // signature: number, Complex } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature2(convert1(arg0), arg1); // signature: number, BigNumber } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: Fraction if (arguments.length === 2) { return signature3(convert2(arg0), arg1); // signature: number, Fraction } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test4(arg1)) { // type: string (convert to number) if (arguments.length === 2) { return signature0(arg0, convert3(arg1)); // signature: number, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test5(arg1)) { // type: boolean (convert to number) if (arguments.length === 2) { return signature0(arg0, convert4(arg1)); // signature: number, boolean } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test6(arg1)) { // type: null (convert to number) if (arguments.length === 2) { return signature0(arg0, convert5(arg1)); // signature: number, null } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } } if (test1(arg0)) { // type: Complex if (test1(arg1)) { // type: Complex if (arguments.length === 2) { return signature1(arg0, arg1); // signature: Complex, Complex } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test0(arg1)) { // type: number (convert to Complex) if (arguments.length === 2) { return signature1(arg0, convert0(arg1)); // signature: Complex, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: BigNumber (convert to Complex) if (arguments.length === 2) { return signature1(arg0, convert6(arg1)); // signature: Complex, BigNumber } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: Fraction (convert to Complex) if (arguments.length === 2) { return signature1(arg0, convert7(arg1)); // signature: Complex, Fraction } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test4(arg1)) { // type: string (convert to Complex) if (arguments.length === 2) { return signature1(arg0, convert8(arg1)); // signature: Complex, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } } if (test2(arg0)) { // type: BigNumber if (test1(arg1)) { // type: Complex if (arguments.length === 2) { return signature1(convert6(arg0), arg1); // signature: BigNumber, Complex } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature2(arg0, arg1); // signature: BigNumber, Big ...
...
* is smaller than the configured epsilon. The function cannot be used to
* compare values smaller than approximately 2.22e-16.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.compare(x, y)
*
* Examples:
*
* math.compare(6, 1); // returns 1
* math.compare(2, 3); // returns -1
* math.compare(7, 7); // returns 0
*
...
function compile(arg0) { "use strict"; var name = 'compile'; if (test0(arg0)) { // type: string if (arguments.length === 1) { return signature0(arg0); // signature: string } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: Array if (arguments.length === 1) { return signature1(arg0); // signature: Array } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test2(arg0)) { // type: Matrix if (arguments.length === 1) { return signature1(arg0); // signature: Matrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test3(arg0)) { // type: number (convert to string) if (arguments.length === 1) { return signature0(convert0(arg0)); // signature: number } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test4(arg0)) { // type: boolean (convert to string) if (arguments.length === 1) { return signature0(convert1(arg0)); // signature: boolean } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test5(arg0)) { // type: null (convert to string) if (arguments.length === 1) { return signature0(convert2(arg0)); // signature: null } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'string,Array,Matrix'); }
...
* parse(expr, options)
* parse([expr1, expr2, expr3, ...])
* parse([expr1, expr2, expr3, ...], options)
*
* Example:
*
* var node = parse('sqrt(3^2 + 4^2)');
* node.compile(math).eval(); // 5
*
* var scope = {a:3, b:4}
* var node = parse('a * b'); // 12
* var code = node.compile(math);
* code.eval(scope); // 12
* scope.a = 5;
* code.eval(scope); // 20
...
function complex(arg0, arg1) { "use strict"; var name = 'complex'; if (arguments.length === 0) { return signature0(); // signature: } if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature1(arg0); // signature: number } if (test0(arg1)) { // type: number if (arguments.length === 2) { return signature2(arg0, arg1); // signature: number, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test1(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature3(convert0(arg0), arg1); // signature: number, BigNumber } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: Fraction (convert to BigNumber) if (arguments.length === 2) { return signature3(convert0(arg0), convert1(arg1)); // signature: number, Fraction } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: string (convert to number) if (arguments.length === 2) { return signature2(arg0, convert2(arg1)); // signature: number, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test4(arg1)) { // type: boolean (convert to number) if (arguments.length === 2) { return signature2(arg0, convert3(arg1)); // signature: number, boolean } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test5(arg1)) { // type: null (convert to number) if (arguments.length === 2) { return signature2(arg0, convert4(arg1)); // signature: number, null } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'number,BigNumber'); } if (test6(arg0)) { // type: Complex if (arguments.length === 1) { return signature4(arg0); // signature: Complex } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature4(convert5(arg0)); // signature: BigNumber } if (test1(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature3(arg0, arg1); // signature: BigNumber, BigNumber } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test0(arg1)) { // type: number (convert to BigNumber) if (arguments.length === 2) { return signature3(arg0, convert0(arg1)); // signature: BigNumber, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: Fraction (convert to BigNumber) if (arguments.length === 2) { return signature3(arg0, convert1(arg1)); // signature: BigNumber, Fraction } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: string (convert to BigNumber) if (arguments.length === 2) { return signature3(arg0, convert6(arg1)); // signature: BigNumber, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test4(arg1)) { // type: boolean (convert to BigNumber) if (arguments.length === 2) { return signature3(arg0, convert7(arg1)); // signature: BigNumber, boolean } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test5(arg1)) { // type: null (convert to BigNumber) if (arguments.length === 2) { ...
...
* Syntax:
*
* math.string(value)
*
* Examples:
*
* math.string(4.2); // returns string '4.2'
* math.string(math.complex(3, 2); // returns string '3 + 2i'
*
* var u = math.unit(5, 'km');
* math.string(u.to('m')); // returns string '5000 m'
*
* math.string([true, false]); // returns ['true', 'false']
*
* See also:
...
function composition(arg0, arg1) { "use strict"; var name = 'composition'; if (test0(arg0)) { // type: number if (test0(arg1)) { // type: number if (arguments.length === 2) { return signature0(arg0, arg1); // signature: number, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test1(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature0(arg0, arg1); // signature: number, BigNumber } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: Fraction (convert to BigNumber) if (arguments.length === 2) { return signature0(arg0, convert0(arg1)); // signature: number, Fraction } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: string (convert to number) if (arguments.length === 2) { return signature0(arg0, convert1(arg1)); // signature: number, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test4(arg1)) { // type: boolean (convert to number) if (arguments.length === 2) { return signature0(arg0, convert2(arg1)); // signature: number, boolean } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test5(arg1)) { // type: null (convert to number) if (arguments.length === 2) { return signature0(arg0, convert3(arg1)); // signature: number, null } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'number,BigNumber'); } if (test1(arg0)) { // type: BigNumber if (test0(arg1)) { // type: number if (arguments.length === 2) { return signature0(arg0, arg1); // signature: BigNumber, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test1(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature0(arg0, arg1); // signature: BigNumber, BigNumber } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: Fraction (convert to BigNumber) if (arguments.length === 2) { return signature0(arg0, convert0(arg1)); // signature: BigNumber, Fraction } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: string (convert to number) if (arguments.length === 2) { return signature0(arg0, convert1(arg1)); // signature: BigNumber, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test4(arg1)) { // type: boolean (convert to number) if (arguments.length === 2) { return signature0(arg0, convert2(arg1)); // signature: BigNumber, boolean } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test5(arg1)) { // type: null (convert to number) if (arguments.length === 2) { return signature0(arg0, convert3(arg1)); // signature: BigNumber, null } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'number,BigNumber'); } if (test2(arg0)) { // type: Fraction (convert to BigNumber) if (test0(arg1)) { // type: number if (arguments.length === 2) { return signature0(convert0(arg0), arg1); // signature: Fraction, number } if (arguments.length > 2) { throw createE ...
...
* The composition counts of n into k parts.
*
* composition only takes integer arguments.
* The following condition must be enforced: k <= n.
*
* Syntax:
*
* math.composition(n, k)
*
* Examples:
*
* math.composition(5, 3); // returns 6
*
* See also:
*
...
function concat(arg0) { "use strict"; var name = 'concat'; if (arguments.length > 0) { var varArgs = []; for (var i = 0; i < arguments.length; i++) { varArgs.push(arguments[i]); } return signature0(varArgs); // signature: ...any } throw createError(name, arguments.length, 0, arguments[0], 'any'); }
...
// figure out what number of arguments the callback function expects
var args = maxArgumentCount(callback);
var recurse = function (value, index) {
if (Array.isArray(value)) {
value.forEach(function (child, i) {
// we create a copy of the index array and append the new index value
recurse(child, index.concat(i + 1)); // one based index, hence i+1
});
}
else {
// invoke the callback function with the right number of arguments
if (args === 1) {
callback(value);
}
...
function _config(options) { if (options) { var prev = object.clone(config); // validate some of the options validateOption(options, 'matrix', MATRIX); validateOption(options, 'number', NUMBER); // merge options object.deepExtend(config, options); var curr = object.clone(config); var changes = object.clone(options); // emit 'config' event math.emit('config', curr, prev, changes); return curr; } else { return object.clone(config); } }
...
/**
* Set configuration options for math.js, and get current options.
* Will emit a 'config' event, with arguments (curr, prev, changes).
*
* Syntax:
*
* math.config(config: Object): Object
*
* Examples:
*
* math.config().number; // outputs 'number'
* math.eval('0.4'); // outputs number 0.4
* math.config({number: 'Fraction'});
* math.eval('0.4'); // outputs Fraction 2/5
...
function conj(arg0) { "use strict"; var name = 'conj'; if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature0(arg0); // signature: number } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: Complex if (arguments.length === 1) { return signature1(arg0); // signature: Complex } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test2(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature2(arg0); // signature: BigNumber } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test3(arg0)) { // type: Array if (arguments.length === 1) { return signature3(arg0); // signature: Array } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test4(arg0)) { // type: Matrix if (arguments.length === 1) { return signature3(arg0); // signature: Matrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test5(arg0)) { // type: Fraction (convert to BigNumber) if (arguments.length === 1) { return signature2(convert0(arg0)); // signature: Fraction } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test6(arg0)) { // type: string (convert to number) if (arguments.length === 1) { return signature0(convert1(arg0)); // signature: string } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test7(arg0)) { // type: boolean (convert to number) if (arguments.length === 1) { return signature0(convert2(arg0)); // signature: boolean } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test8(arg0)) { // type: null (convert to number) if (arguments.length === 1) { return signature0(convert3(arg0)); // signature: null } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'number,Complex,BigNumber,Array,Matrix'); }
...
* Compute the complex conjugate of a complex value.
* If `x = a+bi`, the complex conjugate of `x` is `a - bi`.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.conj(x)
*
* Examples:
*
* math.conj(math.complex('2 + 3i')); // returns Complex 2 - 3i
* math.conj(math.complex('2 - 3i')); // returns Complex 2 + 3i
* math.conj(math.complex('-5.2i')); // returns Complex 5.2i
*
...
function cos(arg0) { "use strict"; var name = 'cos'; if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature0(arg0); // signature: number } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: Complex if (arguments.length === 1) { return signature1(arg0); // signature: Complex } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test2(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature2(arg0); // signature: BigNumber } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test3(arg0)) { // type: Unit if (arguments.length === 1) { return signature3(arg0); // signature: Unit } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test4(arg0)) { // type: Array if (arguments.length === 1) { return signature4(arg0); // signature: Array } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test5(arg0)) { // type: Matrix if (arguments.length === 1) { return signature4(arg0); // signature: Matrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test6(arg0)) { // type: Fraction (convert to BigNumber) if (arguments.length === 1) { return signature2(convert0(arg0)); // signature: Fraction } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test7(arg0)) { // type: string (convert to number) if (arguments.length === 1) { return signature0(convert1(arg0)); // signature: string } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test8(arg0)) { // type: boolean (convert to number) if (arguments.length === 1) { return signature0(convert2(arg0)); // signature: boolean } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test9(arg0)) { // type: null (convert to number) if (arguments.length === 1) { return signature0(convert3(arg0)); // signature: null } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'number,Complex,BigNumber,Unit,Array,Matrix'); }
...
var u1, u2,
picked = -1;
// We reject values outside of the interval [0, 1]
// TODO: check if it is ok to do that?
while (picked < 0 || picked > 1) {
u1 = rng();
u2 = rng();
picked = 1/6 * Math.pow(-2 * Math.log(u1), 0.5) * Math.cos(2 * Math.PI * u2) +
0.5;
}
return picked;
}
}
};
distribution.toTex = undefined; // use default template
...
function cosh(arg0) { "use strict"; var name = 'cosh'; if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature0(arg0); // signature: number } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: Complex if (arguments.length === 1) { return signature1(arg0); // signature: Complex } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test2(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature2(arg0); // signature: BigNumber } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test3(arg0)) { // type: Unit if (arguments.length === 1) { return signature3(arg0); // signature: Unit } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test4(arg0)) { // type: Array if (arguments.length === 1) { return signature4(arg0); // signature: Array } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test5(arg0)) { // type: Matrix if (arguments.length === 1) { return signature4(arg0); // signature: Matrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test6(arg0)) { // type: Fraction (convert to BigNumber) if (arguments.length === 1) { return signature2(convert0(arg0)); // signature: Fraction } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test7(arg0)) { // type: string (convert to number) if (arguments.length === 1) { return signature0(convert1(arg0)); // signature: string } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test8(arg0)) { // type: boolean (convert to number) if (arguments.length === 1) { return signature0(convert2(arg0)); // signature: boolean } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test9(arg0)) { // type: null (convert to number) if (arguments.length === 1) { return signature0(convert3(arg0)); // signature: null } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'number,Complex,BigNumber,Unit,Array,Matrix'); }
...
* Calculate the hyperbolic cosine of a value,
* defined as `cosh(x) = 1/2 * (exp(x) + exp(-x))`.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.cosh(x)
*
* Examples:
*
* math.cosh(0.5); // returns number 1.1276259652063807
*
* See also:
*
...
function cot(arg0) { "use strict"; var name = 'cot'; if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature0(arg0); // signature: number } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: Complex if (arguments.length === 1) { return signature1(arg0); // signature: Complex } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test2(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature2(arg0); // signature: BigNumber } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test3(arg0)) { // type: Unit if (arguments.length === 1) { return signature3(arg0); // signature: Unit } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test4(arg0)) { // type: Array if (arguments.length === 1) { return signature4(arg0); // signature: Array } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test5(arg0)) { // type: Matrix if (arguments.length === 1) { return signature4(arg0); // signature: Matrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test6(arg0)) { // type: Fraction (convert to BigNumber) if (arguments.length === 1) { return signature2(convert0(arg0)); // signature: Fraction } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test7(arg0)) { // type: string (convert to number) if (arguments.length === 1) { return signature0(convert1(arg0)); // signature: string } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test8(arg0)) { // type: boolean (convert to number) if (arguments.length === 1) { return signature0(convert2(arg0)); // signature: boolean } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test9(arg0)) { // type: null (convert to number) if (arguments.length === 1) { return signature0(convert3(arg0)); // signature: null } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'number,Complex,BigNumber,Unit,Array,Matrix'); }
...
* Syntax:
*
* math.acot(x)
*
* Examples:
*
* math.acot(0.5); // returns number 0.4636476090008061
* math.acot(math.cot(1.5)); // returns number 1.5
*
* math.acot(2); // returns Complex 1.5707963267948966 -1.3169578969248166 i
*
* See also:
*
* cot, atan
*
...
function coth(arg0) { "use strict"; var name = 'coth'; if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature0(arg0); // signature: number } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: Complex if (arguments.length === 1) { return signature1(arg0); // signature: Complex } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test2(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature2(arg0); // signature: BigNumber } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test3(arg0)) { // type: Unit if (arguments.length === 1) { return signature3(arg0); // signature: Unit } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test4(arg0)) { // type: Array if (arguments.length === 1) { return signature4(arg0); // signature: Array } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test5(arg0)) { // type: Matrix if (arguments.length === 1) { return signature4(arg0); // signature: Matrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test6(arg0)) { // type: Fraction (convert to BigNumber) if (arguments.length === 1) { return signature2(convert0(arg0)); // signature: Fraction } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test7(arg0)) { // type: string (convert to number) if (arguments.length === 1) { return signature0(convert1(arg0)); // signature: string } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test8(arg0)) { // type: boolean (convert to number) if (arguments.length === 1) { return signature0(convert2(arg0)); // signature: boolean } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test9(arg0)) { // type: null (convert to number) if (arguments.length === 1) { return signature0(convert3(arg0)); // signature: null } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'number,Complex,BigNumber,Unit,Array,Matrix'); }
...
* Calculate the hyperbolic cotangent of a value,
* defined as `coth(x) = 1 / tanh(x)`.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.coth(x)
*
* Examples:
*
* // coth(x) = 1 / tanh(x)
* math.coth(2); // returns 1.0373147207275482
* 1 / math.tanh(2); // returns 1.0373147207275482
*
...
function createUnit(arg0, arg1, arg2) { "use strict"; var name = 'createUnit'; if (test0(arg0)) { // type: string if (arguments.length === 1) { return signature0(arg0); // signature: string } if (test1(arg1)) { // type: Unit if (arguments.length === 2) { return signature1(arg0, arg1); // signature: string, Unit } if (test2(arg2)) { // type: Object if (arguments.length === 3) { return signature2(arg0, arg1, arg2); // signature: string, Unit, Object } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } throw createError(name, arguments.length, 2, arguments[2], 'Object'); } if (test0(arg1)) { // type: string if (arguments.length === 2) { return signature1(arg0, arg1); // signature: string, string } if (test2(arg2)) { // type: Object if (arguments.length === 3) { return signature2(arg0, arg1, arg2); // signature: string, string, Object } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } throw createError(name, arguments.length, 2, arguments[2], 'Object'); } if (test3(arg1)) { // type: number (convert to string) if (arguments.length === 2) { return signature1(arg0, convert0(arg1)); // signature: string, number } if (test2(arg2)) { // type: Object if (arguments.length === 3) { return signature2(arg0, convert0(arg1), arg2); // signature: string, number, Object } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } throw createError(name, arguments.length, 2, arguments[2], 'Object'); } if (test4(arg1)) { // type: boolean (convert to string) if (arguments.length === 2) { return signature1(arg0, convert1(arg1)); // signature: string, boolean } if (test2(arg2)) { // type: Object if (arguments.length === 3) { return signature2(arg0, convert1(arg1), arg2); // signature: string, boolean, Object } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } throw createError(name, arguments.length, 2, arguments[2], 'Object'); } if (test5(arg1)) { // type: null (convert to string) if (arguments.length === 2) { return signature1(arg0, convert2(arg1)); // signature: string, null } if (test2(arg2)) { // type: Object if (arguments.length === 3) { return signature2(arg0, convert2(arg1), arg2); // signature: string, null, Object } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } throw createError(name, arguments.length, 2, arguments[2], 'Object'); } if (test2(arg1)) { // type: Object if (arguments.length === 2) { return signature1(arg0, arg1); // signature: string, Object } if (test2(arg2)) { // type: Object if (arguments.length === 3) { return signature2(arg0, arg1, arg2); // signature: string, Object, Object } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } throw createError(name, arguments.length, 2, arguments[2], 'Object'); } throw createError(name, arguments.length, 1, arguments[1], 'Unit,string,Object'); } if (test3(arg0)) { // type: number (convert to string) if (arguments.length === 1) { return signature0(convert0(arg0)); // signature: number } if (test1(arg1)) { // type: Unit if (arguments.length === 2) { return signature1(convert0(arg0), arg1); // signature: number, Unit } if (test2(arg2)) { // type: Object if (arguments.length === 3) { return signature2(convert0(arg0), arg1, arg2); // signature: number, Unit, Object } ...
n/a
function cross(arg0, arg1) { "use strict"; var name = 'cross'; if (test0(arg0)) { // type: Array if (test0(arg1)) { // type: Array if (arguments.length === 2) { return signature0(arg0, arg1); // signature: Array, Array } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test1(arg1)) { // type: Matrix if (arguments.length === 2) { return signature1(arg0, arg1); // signature: Array, Matrix } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'Array,Matrix'); } if (test1(arg0)) { // type: Matrix if (test0(arg1)) { // type: Array if (arguments.length === 2) { return signature2(arg0, arg1); // signature: Matrix, Array } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test1(arg1)) { // type: Matrix if (arguments.length === 2) { return signature3(arg0, arg1); // signature: Matrix, Matrix } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'Array,Matrix'); } throw createError(name, arguments.length, 0, arguments[0], 'Array,Matrix'); }
...
* ]
*
* If one of the input vectors has a dimension greater than 1, the output
* vector will be a 1x3 (2-dimensional) matrix.
*
* Syntax:
*
* math.cross(x, y)
*
* Examples:
*
* math.cross([1, 1, 0], [0, 1, 1]); // Returns [1, -1, 1]
* math.cross([3, -3, 1], [4, 9, 2]); // Returns [-15, -2, 39]
* math.cross([2, 3, 4], [5, 6, 7]); // Returns [-3, 6, -3]
* math.cross([[1, 2, 3]], [[4], [5], [6]]); // Returns [[-3, 6, -3]]
...
function csc(arg0) { "use strict"; var name = 'csc'; if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature0(arg0); // signature: number } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: Complex if (arguments.length === 1) { return signature1(arg0); // signature: Complex } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test2(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature2(arg0); // signature: BigNumber } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test3(arg0)) { // type: Unit if (arguments.length === 1) { return signature3(arg0); // signature: Unit } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test4(arg0)) { // type: Array if (arguments.length === 1) { return signature4(arg0); // signature: Array } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test5(arg0)) { // type: Matrix if (arguments.length === 1) { return signature4(arg0); // signature: Matrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test6(arg0)) { // type: Fraction (convert to BigNumber) if (arguments.length === 1) { return signature2(convert0(arg0)); // signature: Fraction } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test7(arg0)) { // type: string (convert to number) if (arguments.length === 1) { return signature0(convert1(arg0)); // signature: string } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test8(arg0)) { // type: boolean (convert to number) if (arguments.length === 1) { return signature0(convert2(arg0)); // signature: boolean } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test9(arg0)) { // type: null (convert to number) if (arguments.length === 1) { return signature0(convert3(arg0)); // signature: null } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'number,Complex,BigNumber,Unit,Array,Matrix'); }
...
* Syntax:
*
* math.acsc(x)
*
* Examples:
*
* math.acsc(0.5); // returns number 0.5235987755982989
* math.acsc(math.csc(1.5)); // returns number ~1.5
*
* math.acsc(2); // returns Complex 1.5707963267948966 -1.3169578969248166 i
*
* See also:
*
* csc, asin, asec
*
...
function csch(arg0) { "use strict"; var name = 'csch'; if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature0(arg0); // signature: number } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: Complex if (arguments.length === 1) { return signature1(arg0); // signature: Complex } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test2(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature2(arg0); // signature: BigNumber } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test3(arg0)) { // type: Unit if (arguments.length === 1) { return signature3(arg0); // signature: Unit } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test4(arg0)) { // type: Array if (arguments.length === 1) { return signature4(arg0); // signature: Array } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test5(arg0)) { // type: Matrix if (arguments.length === 1) { return signature4(arg0); // signature: Matrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test6(arg0)) { // type: Fraction (convert to BigNumber) if (arguments.length === 1) { return signature2(convert0(arg0)); // signature: Fraction } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test7(arg0)) { // type: string (convert to number) if (arguments.length === 1) { return signature0(convert1(arg0)); // signature: string } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test8(arg0)) { // type: boolean (convert to number) if (arguments.length === 1) { return signature0(convert2(arg0)); // signature: boolean } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test9(arg0)) { // type: null (convert to number) if (arguments.length === 1) { return signature0(convert3(arg0)); // signature: null } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'number,Complex,BigNumber,Unit,Array,Matrix'); }
...
* Calculate the hyperbolic cosecant of a value,
* defined as `csch(x) = 1 / sinh(x)`.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.csch(x)
*
* Examples:
*
* // csch(x) = 1/ sinh(x)
* math.csch(0.5); // returns 1.9190347513349437
* 1 / math.sinh(0.5); // returns 1.9190347513349437
*
...
function cube(arg0) { "use strict"; var name = 'cube'; if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature0(arg0); // signature: number } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: Complex if (arguments.length === 1) { return signature1(arg0); // signature: Complex } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test2(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature2(arg0); // signature: BigNumber } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test3(arg0)) { // type: Fraction if (arguments.length === 1) { return signature3(arg0); // signature: Fraction } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test4(arg0)) { // type: Unit if (arguments.length === 1) { return signature4(arg0); // signature: Unit } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test5(arg0)) { // type: Array if (arguments.length === 1) { return signature5(arg0); // signature: Array } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test6(arg0)) { // type: Matrix if (arguments.length === 1) { return signature5(arg0); // signature: Matrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test7(arg0)) { // type: string (convert to number) if (arguments.length === 1) { return signature0(convert0(arg0)); // signature: string } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test8(arg0)) { // type: boolean (convert to number) if (arguments.length === 1) { return signature0(convert1(arg0)); // signature: boolean } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test9(arg0)) { // type: null (convert to number) if (arguments.length === 1) { return signature0(convert2(arg0)); // signature: null } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'number,Complex,BigNumber,Fraction,Unit,Array,Matrix'); }
...
*
* math.cbrt(x)
* math.cbrt(x, allRoots)
*
* Examples:
*
* math.cbrt(27); // returns 3
* math.cube(3); // returns 27
* math.cbrt(-64); // returns -4
* math.cbrt(math.unit('27 m^3')); // returns Unit 3 m
* math.cbrt([27, 64, 125]); // returns [3, 4, 5]
*
* var x = math.complex('8i');
* math.cbrt(x); // returns Complex 1.7320508075689 + i
* math.cbrt(x, true); // returns Matrix [
...
function deepEqual(arg0, arg1) { "use strict"; var name = 'deepEqual'; // type: any // type: any if (arguments.length === 2) { return signature0(arg0, arg1); // signature: any, any } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } throw createError(name, arguments.length, 1, arguments[1], 'any'); throw createError(name, arguments.length, 0, arguments[0], 'any'); }
...
}
if (a.length != b.length) {
return false;
}
for (i = 0, len = a.length; i < len; i++) {
if (!exports.deepEqual(a[i], b[i])) {
return false;
}
}
return true;
}
else if (a instanceof Object) {
if (Array.isArray(b) || !(b instanceof Object)) {
...
function derivative(arg0, arg1, arg2) { "use strict"; var name = 'derivative'; if (test0(arg0)) { // type: string if (test0(arg1)) { // type: string if (arguments.length === 2) { return signature0(arg0, arg1); // signature: string, string } if (test1(arg2)) { // type: Object if (arguments.length === 3) { return signature1(arg0, arg1, arg2); // signature: string, string, Object } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } throw createError(name, arguments.length, 2, arguments[2], 'Object'); } if (test2(arg1)) { // type: SymbolNode if (arguments.length === 2) { return signature2(arg0, arg1); // signature: string, SymbolNode } if (test1(arg2)) { // type: Object if (arguments.length === 3) { return signature3(arg0, arg1, arg2); // signature: string, SymbolNode, Object } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } throw createError(name, arguments.length, 2, arguments[2], 'Object'); } if (test3(arg1)) { // type: number (convert to string) if (arguments.length === 2) { return signature0(arg0, convert0(arg1)); // signature: string, number } if (test1(arg2)) { // type: Object if (arguments.length === 3) { return signature1(arg0, convert0(arg1), arg2); // signature: string, number, Object } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } throw createError(name, arguments.length, 2, arguments[2], 'Object'); } if (test4(arg1)) { // type: boolean (convert to string) if (arguments.length === 2) { return signature0(arg0, convert1(arg1)); // signature: string, boolean } if (test1(arg2)) { // type: Object if (arguments.length === 3) { return signature1(arg0, convert1(arg1), arg2); // signature: string, boolean, Object } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } throw createError(name, arguments.length, 2, arguments[2], 'Object'); } if (test5(arg1)) { // type: null (convert to string) if (arguments.length === 2) { return signature0(arg0, convert2(arg1)); // signature: string, null } if (test1(arg2)) { // type: Object if (arguments.length === 3) { return signature1(arg0, convert2(arg1), arg2); // signature: string, null, Object } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } throw createError(name, arguments.length, 2, arguments[2], 'Object'); } throw createError(name, arguments.length, 1, arguments[1], 'string,SymbolNode'); } if (test6(arg0)) { // type: Node if (test0(arg1)) { // type: string if (arguments.length === 2) { return signature4(arg0, arg1); // signature: Node, string } if (test1(arg2)) { // type: Object if (arguments.length === 3) { return signature5(arg0, arg1, arg2); // signature: Node, string, Object } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } throw createError(name, arguments.length, 2, arguments[2], 'Object'); } if (test2(arg1)) { // type: SymbolNode if (arguments.length === 2) { return signature6(arg0, arg1); // signature: Node, SymbolNode } if (test1(arg2)) { // type: Object if (arguments.length === 3) { return signature7(arg0, arg1, arg2); // signature: Node, SymbolNode, Object } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } throw createError(name, arguments.length, 2, arguments[2], 'Object'); } if (t ...
...
// functions and constants
math.round(math.e, 3); // 2.718
math.atan2(3, -3) / math.pi; // 0.75
math.log(1000, 10); // 3
math.sqrt(-4); // 2i
math.pow([[-1, 2], [3, 1]], 2); // [[7, 0], [0, 7]]
math.derivative('x^2 + x', 'x'); // 2 * x + 1
// expressions
math.eval('12 / (2.3 + 0.7)'); // 4
math.eval('5.08 cm to inch'); // 2 inch
math.eval('sin(45 deg) ^ 2'); // 0.5
math.eval('9 / 3 + 2i'); // 3 + 2i
math.eval('det([-1, 2; 3, 1])'); // -7
...
function det(arg0) { "use strict"; var name = 'det'; if (test0(arg0)) { // type: Array if (arguments.length === 1) { return signature0(arg0); // signature: Array } } if (test1(arg0)) { // type: Matrix if (arguments.length === 1) { return signature0(arg0); // signature: Matrix } } // type: any if (arguments.length === 1) { return signature1(arg0); // signature: any } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } throw createError(name, arguments.length, 0, arguments[0], 'Array,Matrix,any'); }
...
var unaryMinus = load(require('../arithmetic/unaryMinus'));
/**
* Calculate the determinant of a matrix.
*
* Syntax:
*
* math.det(x)
*
* Examples:
*
* math.det([[1, 2], [3, 4]]); // returns -2
*
* var A = [
* [-2, 2, 3],
...
function diag(arg0, arg1, arg2) { "use strict"; var name = 'diag'; if (test0(arg0)) { // type: Array if (arguments.length === 1) { return signature0(arg0); // signature: Array } if (test1(arg1)) { // type: number if (arguments.length === 2) { return signature1(arg0, arg1); // signature: Array, number } if (test2(arg2)) { // type: string if (arguments.length === 3) { return signature2(arg0, arg1, arg2); // signature: Array, number, string } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } if (test1(arg2)) { // type: number (convert to string) if (arguments.length === 3) { return signature2(arg0, arg1, convert0(arg2)); // signature: Array, number, number } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } if (test3(arg2)) { // type: boolean (convert to string) if (arguments.length === 3) { return signature2(arg0, arg1, convert1(arg2)); // signature: Array, number, boolean } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } if (test4(arg2)) { // type: null (convert to string) if (arguments.length === 3) { return signature2(arg0, arg1, convert2(arg2)); // signature: Array, number, null } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } throw createError(name, arguments.length, 2, arguments[2], 'string'); } if (test5(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature3(arg0, arg1); // signature: Array, BigNumber } if (test2(arg2)) { // type: string if (arguments.length === 3) { return signature4(arg0, arg1, arg2); // signature: Array, BigNumber, string } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } if (test1(arg2)) { // type: number (convert to string) if (arguments.length === 3) { return signature4(arg0, arg1, convert0(arg2)); // signature: Array, BigNumber, number } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } if (test3(arg2)) { // type: boolean (convert to string) if (arguments.length === 3) { return signature4(arg0, arg1, convert1(arg2)); // signature: Array, BigNumber, boolean } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } if (test4(arg2)) { // type: null (convert to string) if (arguments.length === 3) { return signature4(arg0, arg1, convert2(arg2)); // signature: Array, BigNumber, null } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } throw createError(name, arguments.length, 2, arguments[2], 'string'); } if (test2(arg1)) { // type: string if (arguments.length === 2) { return signature5(arg0, arg1); // signature: Array, string } if (test2(arg2)) { // type: string if (arguments.length === 3) { return signature2(arg0, convert3(arg1), arg2); // signature: Array, string, string } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } if (test1(arg2)) { // type: number (convert to string) if (arguments.length === 3) { return signature2(arg0, convert3(arg1), convert0(arg2)); // signature: Array, string, number } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } if (test3(arg2)) { // type: boolean (convert to string) if (argume ...
...
* When `x` is a vector, a matrix with vector `x` on the diagonal will be returned.
* When `x` is a two dimensional matrix, the matrixes `k`th diagonal will be returned as vector.
* When k is positive, the values are placed on the super diagonal.
* When k is negative, the values are placed on the sub diagonal.
*
* Syntax:
*
* math.diag(X)
* math.diag(X, format)
* math.diag(X, k)
* math.diag(X, k, format)
*
* Examples:
*
* // create a diagonal matrix
...
function distance(arg0, arg1, arg2) { "use strict"; var name = 'distance'; if (test0(arg0)) { // type: Array if (arguments.length === 1) { return signature0(arg0); // signature: Array } if (test0(arg1)) { // type: Array if (arguments.length === 2) { return signature1(arg0, arg1); // signature: Array, Array } if (test0(arg2)) { // type: Array if (arguments.length === 3) { return signature2(arg0, arg1, arg2); // signature: Array, Array, Array } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } if (test1(arg2)) { // type: Matrix (convert to Array) if (arguments.length === 3) { return signature2(arg0, arg1, convert0(arg2)); // signature: Array, Array, Matrix } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } throw createError(name, arguments.length, 2, arguments[2], 'Array'); } if (test1(arg1)) { // type: Matrix (convert to Array) if (arguments.length === 2) { return signature1(arg0, convert0(arg1)); // signature: Array, Matrix } if (test0(arg2)) { // type: Array if (arguments.length === 3) { return signature2(arg0, convert0(arg1), arg2); // signature: Array, Matrix, Array } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } if (test1(arg2)) { // type: Matrix (convert to Array) if (arguments.length === 3) { return signature2(arg0, convert0(arg1), convert0(arg2)); // signature: Array, Matrix, Matrix } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } throw createError(name, arguments.length, 2, arguments[2], 'Array'); } throw createError(name, arguments.length, 1, arguments[1], 'Array'); } if (test1(arg0)) { // type: Matrix (convert to Array) if (arguments.length === 1) { return signature0(convert0(arg0)); // signature: Matrix } if (test0(arg1)) { // type: Array if (arguments.length === 2) { return signature1(convert0(arg0), arg1); // signature: Matrix, Array } if (test0(arg2)) { // type: Array if (arguments.length === 3) { return signature2(convert0(arg0), arg1, arg2); // signature: Matrix, Array, Array } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } if (test1(arg2)) { // type: Matrix (convert to Array) if (arguments.length === 3) { return signature2(convert0(arg0), arg1, convert0(arg2)); // signature: Matrix, Array, Matrix } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } throw createError(name, arguments.length, 2, arguments[2], 'Array'); } if (test1(arg1)) { // type: Matrix (convert to Array) if (arguments.length === 2) { return signature1(convert0(arg0), convert0(arg1)); // signature: Matrix, Matrix } if (test0(arg2)) { // type: Array if (arguments.length === 3) { return signature2(convert0(arg0), convert0(arg1), arg2); // signature: Matrix, Matrix, Array } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } if (test1(arg2)) { // type: Matrix (convert to Array) if (arguments.length === 3) { return signature2(convert0(arg0), convert0(arg1), convert0(arg2)); // signature: Matrix, Matrix, Matrix } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } throw createError(name, arguments.length, 2, arguments[2], 'Array'); } throw createError(name, arguments.length, 1, arguments[1], 'Array'); } if (test2(arg0)) { / ...
...
* Distance between point and a line in 2 and 3 dimensional spaces.
* Pairwise distance between a set of 2D or 3D points
* NOTE:
* When substituting coefficients of a line(a, b and c), use ax + by + c = 0 instead of ax + by = c
* For parametric equation of a 3D line, x0, y0, z0, a, b, c are from: (x−x0, y−y0, z−z0) = t(a, b, c)
*
* Syntax:
* math.distance([x1, y1], [x2, y2])
*- math.distance({pointOneX: 4, pointOneY: 5}, {pointTwoX: 2, pointTwoY: 7})
* math.distance([x1, y1, z1], [x2, y2, z2])
* math.distance({pointOneX: 4, pointOneY: 5, pointOneZ: 8}, {pointTwoX: 2, pointTwoY: 7, pointTwoZ: 9})
* math.distance([[A], [B], [C]...])
* math.distance([x1, y1], [LinePtX1, LinePtY1], [LinePtX2, LinePtY2])
* math.distance({pointX: 1, pointY: 4}, {lineOnePtX: 6, lineOnePtY: 3}, {lineTwoPtX: 2, lineTwoPtY: 8})
* math.distance([x1, y1, z1], [LinePtX1, LinePtY1, LinePtZ1], [LinePtX2, LinePtY2, LinePtZ2])
...
function divide(arg0, arg1) { "use strict"; var name = 'divide'; if (test0(arg0)) { // type: number if (test0(arg1)) { // type: number if (arguments.length === 2) { return signature0(arg0, arg1); // signature: number, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test1(arg1)) { // type: Complex if (arguments.length === 2) { return signature1(convert0(arg0), arg1); // signature: number, Complex } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature2(convert1(arg0), arg1); // signature: number, BigNumber } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: Fraction if (arguments.length === 2) { return signature3(convert2(arg0), arg1); // signature: number, Fraction } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test4(arg1)) { // type: Unit if (arguments.length === 2) { return signature4(arg0, arg1); // signature: number, Unit } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test5(arg1)) { // type: string (convert to number) if (arguments.length === 2) { return signature0(arg0, convert3(arg1)); // signature: number, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test6(arg1)) { // type: boolean (convert to number) if (arguments.length === 2) { return signature0(arg0, convert4(arg1)); // signature: number, boolean } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test7(arg1)) { // type: null (convert to number) if (arguments.length === 2) { return signature0(arg0, convert5(arg1)); // signature: number, null } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } } if (test1(arg0)) { // type: Complex if (test1(arg1)) { // type: Complex if (arguments.length === 2) { return signature1(arg0, arg1); // signature: Complex, Complex } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test0(arg1)) { // type: number (convert to Complex) if (arguments.length === 2) { return signature1(arg0, convert0(arg1)); // signature: Complex, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: BigNumber (convert to Complex) if (arguments.length === 2) { return signature1(arg0, convert6(arg1)); // signature: Complex, BigNumber } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: Fraction (convert to Complex) if (arguments.length === 2) { return signature1(arg0, convert7(arg1)); // signature: Complex, Fraction } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test5(arg1)) { // type: string (convert to Complex) if (arguments.length === 2) { return signature1(arg0, convert8(arg1)); // signature: Complex, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } } if (test2(arg0)) { // type: BigNumber if (test1(arg1)) { // type: Complex if (arguments.length === 2) { return signature1(convert6(arg0), arg1); // signature: BigNumber, Complex } ...
...
/**
* Divide two values, `x / y`.
* To divide matrices, `x` is multiplied with the inverse of `y`: `x * inv(y)`.
*
* Syntax:
*
* math.divide(x, y)
*
* Examples:
*
* math.divide(2, 3); // returns number 0.6666666666666666
*
* var a = math.complex(5, 14);
* var b = math.complex(4, 1);
...
function dot(arg0, arg1) { "use strict"; var name = 'dot'; if (test0(arg0)) { // type: Array if (test0(arg1)) { // type: Array if (arguments.length === 2) { return signature0(arg0, arg1); // signature: Array, Array } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test1(arg1)) { // type: Matrix if (arguments.length === 2) { return signature1(arg0, arg1); // signature: Array, Matrix } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'Array,Matrix'); } if (test1(arg0)) { // type: Matrix if (test0(arg1)) { // type: Array if (arguments.length === 2) { return signature2(arg0, arg1); // signature: Matrix, Array } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test1(arg1)) { // type: Matrix if (arguments.length === 2) { return signature3(arg0, arg1); // signature: Matrix, Matrix } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'Array,Matrix'); } throw createError(name, arguments.length, 0, arguments[0], 'Array,Matrix'); }
...
* Calculate the dot product of two vectors. The dot product of
* `A = [a1, a2, a3, ..., an]` and `B = [b1, b2, b3, ..., bn]` is defined as:
*
* dot(A, B) = a1 * b1 + a2 * b2 + a3 * b3 + ... + an * bn
*
* Syntax:
*
* math.dot(x, y)
*
* Examples:
*
* math.dot([2, 4, 1], [2, 2, 3]); // returns number 15
* math.multiply([2, 4, 1], [2, 2, 3]); // returns number 15
*
* See also:
...
function dotDivide(arg0, arg1) { "use strict"; var name = 'dotDivide'; if (test0(arg0)) { // type: Array if (test0(arg1)) { // type: Array if (arguments.length === 2) { return signature0(arg0, arg1); // signature: Array, Array } } if (test1(arg1)) { // type: Matrix if (arguments.length === 2) { return signature1(arg0, arg1); // signature: Array, Matrix } } // type: any if (arguments.length === 2) { return signature2(arg0, arg1); // signature: Array, any } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test1(arg0)) { // type: Matrix if (test0(arg1)) { // type: Array if (arguments.length === 2) { return signature3(arg0, arg1); // signature: Matrix, Array } } if (test1(arg1)) { // type: Matrix if (arguments.length === 2) { return signature4(arg0, arg1); // signature: Matrix, Matrix } } // type: any if (arguments.length === 2) { return signature5(arg0, arg1); // signature: Matrix, any } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } // type: any if (test0(arg1)) { // type: Array if (arguments.length === 2) { return signature6(arg0, arg1); // signature: any, Array } } if (test1(arg1)) { // type: Matrix if (arguments.length === 2) { return signature7(arg0, arg1); // signature: any, Matrix } } // type: any if (arguments.length === 2) { return signature8(arg0, arg1); // signature: any, any } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } throw createError(name, arguments.length, 1, arguments[1], 'Array,Matrix,any'); throw createError(name, arguments.length, 0, arguments[0], 'Array,Matrix,any'); }
...
/**
* Divide two matrices element wise. The function accepts both matrices and
* scalar values.
*
* Syntax:
*
* math.dotDivide(x, y)
*
* Examples:
*
* math.dotDivide(2, 4); // returns 0.5
*
* a = [[9, 5], [6, 1]];
* b = [[3, 2], [5, 2]];
...
function dotMultiply(arg0, arg1) { "use strict"; var name = 'dotMultiply'; if (test0(arg0)) { // type: Array if (test0(arg1)) { // type: Array if (arguments.length === 2) { return signature0(arg0, arg1); // signature: Array, Array } } if (test1(arg1)) { // type: Matrix if (arguments.length === 2) { return signature1(arg0, arg1); // signature: Array, Matrix } } // type: any if (arguments.length === 2) { return signature2(arg0, arg1); // signature: Array, any } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test1(arg0)) { // type: Matrix if (test0(arg1)) { // type: Array if (arguments.length === 2) { return signature3(arg0, arg1); // signature: Matrix, Array } } if (test1(arg1)) { // type: Matrix if (arguments.length === 2) { return signature4(arg0, arg1); // signature: Matrix, Matrix } } // type: any if (arguments.length === 2) { return signature5(arg0, arg1); // signature: Matrix, any } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } // type: any if (test0(arg1)) { // type: Array if (arguments.length === 2) { return signature6(arg0, arg1); // signature: any, Array } } if (test1(arg1)) { // type: Matrix if (arguments.length === 2) { return signature7(arg0, arg1); // signature: any, Matrix } } // type: any if (arguments.length === 2) { return signature8(arg0, arg1); // signature: any, any } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } throw createError(name, arguments.length, 1, arguments[1], 'Array,Matrix,any'); throw createError(name, arguments.length, 0, arguments[0], 'Array,Matrix,any'); }
...
/**
* Multiply two matrices element wise. The function accepts both matrices and
* scalar values.
*
* Syntax:
*
* math.dotMultiply(x, y)
*
* Examples:
*
* math.dotMultiply(2, 4); // returns 8
*
* a = [[9, 5], [6, 1]];
* b = [[3, 2], [5, 2]];
...
function dotPow(arg0, arg1) { "use strict"; var name = 'dotPow'; if (test0(arg0)) { // type: Array if (test0(arg1)) { // type: Array if (arguments.length === 2) { return signature0(arg0, arg1); // signature: Array, Array } } if (test1(arg1)) { // type: Matrix if (arguments.length === 2) { return signature1(arg0, arg1); // signature: Array, Matrix } } // type: any if (arguments.length === 2) { return signature2(arg0, arg1); // signature: Array, any } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test1(arg0)) { // type: Matrix if (test0(arg1)) { // type: Array if (arguments.length === 2) { return signature3(arg0, arg1); // signature: Matrix, Array } } if (test1(arg1)) { // type: Matrix if (arguments.length === 2) { return signature4(arg0, arg1); // signature: Matrix, Matrix } } // type: any if (arguments.length === 2) { return signature5(arg0, arg1); // signature: Matrix, any } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } // type: any if (test0(arg1)) { // type: Array if (arguments.length === 2) { return signature6(arg0, arg1); // signature: any, Array } } if (test1(arg1)) { // type: Matrix if (arguments.length === 2) { return signature7(arg0, arg1); // signature: any, Matrix } } // type: any if (arguments.length === 2) { return signature8(arg0, arg1); // signature: any, any } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } throw createError(name, arguments.length, 1, arguments[1], 'Array,Matrix,any'); throw createError(name, arguments.length, 0, arguments[0], 'Array,Matrix,any'); }
...
var algorithm14 = load(require('../../type/matrix/utils/algorithm14'));
/**
* Calculates the power of x to y element wise.
*
* Syntax:
*
* math.dotPow(x, y)
*
* Examples:
*
* math.dotPow(2, 3); // returns number 8
*
* var a = [[1, 2], [4, 3]];
* math.dotPow(a, 2); // returns Array [[1, 4], [16, 9]]
...
function equal(arg0, arg1) { "use strict"; var name = 'equal'; if (test0(arg0)) { // type: Array if (test0(arg1)) { // type: Array if (arguments.length === 2) { return signature0(arg0, arg1); // signature: Array, Array } } if (test1(arg1)) { // type: Matrix if (arguments.length === 2) { return signature1(arg0, arg1); // signature: Array, Matrix } } // type: any if (arguments.length === 2) { return signature2(arg0, arg1); // signature: Array, any } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test1(arg0)) { // type: Matrix if (test0(arg1)) { // type: Array if (arguments.length === 2) { return signature3(arg0, arg1); // signature: Matrix, Array } } if (test1(arg1)) { // type: Matrix if (arguments.length === 2) { return signature4(arg0, arg1); // signature: Matrix, Matrix } } // type: any if (arguments.length === 2) { return signature5(arg0, arg1); // signature: Matrix, any } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } // type: any if (test0(arg1)) { // type: Array if (arguments.length === 2) { return signature6(arg0, arg1); // signature: any, Array } } if (test1(arg1)) { // type: Matrix if (arguments.length === 2) { return signature7(arg0, arg1); // signature: any, Matrix } } // type: any if (arguments.length === 2) { return signature8(arg0, arg1); // signature: any, any } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } throw createError(name, arguments.length, 1, arguments[1], 'Array,Matrix,any'); throw createError(name, arguments.length, 0, arguments[0], 'Array,Matrix,any'); }
...
*
* math.deepEqual(2, 4); // returns false
*
* a = [2, 5, 1];
* b = [2, 7, 1];
*
* math.deepEqual(a, b); // returns false
* math.equal(a, b); // returns [true, false, true]
*
* See also:
*
* equal, unequal
*
* @param {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} x First matrix to compare
* @param {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} y Second matrix to compare
...
function erf(arg0) { "use strict"; var name = 'erf'; if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature0(arg0); // signature: number } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature1(arg0); // signature: BigNumber } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test2(arg0)) { // type: Array if (arguments.length === 1) { return signature2(arg0); // signature: Array } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test3(arg0)) { // type: Matrix if (arguments.length === 1) { return signature2(arg0); // signature: Matrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test4(arg0)) { // type: Fraction (convert to BigNumber) if (arguments.length === 1) { return signature1(convert0(arg0)); // signature: Fraction } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test5(arg0)) { // type: string (convert to number) if (arguments.length === 1) { return signature0(convert1(arg0)); // signature: string } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test6(arg0)) { // type: boolean (convert to number) if (arguments.length === 1) { return signature0(convert2(arg0)); // signature: boolean } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test7(arg0)) { // type: null (convert to number) if (arguments.length === 1) { return signature0(convert3(arg0)); // signature: null } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'number,BigNumber,Array,Matrix'); }
...
* "Rational Chebyshev Approximations for the Error Function" by W. J. Cody
* for an explanation of this process.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.erf(x)
*
* Examples:
*
* math.erf(0.2); // returns 0.22270258921047847
* math.erf(-0.5); // returns -0.5204998778130465
* math.erf(4); // returns 0.9999999845827421
*
...
function compile(arg0, arg1) { "use strict"; var name = 'compile'; if (test0(arg0)) { // type: string if (arguments.length === 1) { return signature0(arg0); // signature: string } if (test1(arg1)) { // type: Object if (arguments.length === 2) { return signature1(arg0, arg1); // signature: string, Object } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'Object'); } if (test2(arg0)) { // type: Array if (arguments.length === 1) { return signature2(arg0); // signature: Array } if (test1(arg1)) { // type: Object if (arguments.length === 2) { return signature3(arg0, arg1); // signature: Array, Object } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'Object'); } if (test3(arg0)) { // type: Matrix if (arguments.length === 1) { return signature2(arg0); // signature: Matrix } if (test1(arg1)) { // type: Object if (arguments.length === 2) { return signature3(arg0, arg1); // signature: Matrix, Object } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'Object'); } if (test4(arg0)) { // type: number (convert to string) if (arguments.length === 1) { return signature0(convert0(arg0)); // signature: number } if (test1(arg1)) { // type: Object if (arguments.length === 2) { return signature1(convert0(arg0), arg1); // signature: number, Object } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'Object'); } if (test5(arg0)) { // type: boolean (convert to string) if (arguments.length === 1) { return signature0(convert1(arg0)); // signature: boolean } if (test1(arg1)) { // type: Object if (arguments.length === 2) { return signature1(convert1(arg0), arg1); // signature: boolean, Object } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'Object'); } if (test6(arg0)) { // type: null (convert to string) if (arguments.length === 1) { return signature0(convert2(arg0)); // signature: null } if (test1(arg1)) { // type: Object if (arguments.length === 2) { return signature1(convert2(arg0), arg1); // signature: null, Object } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'Object'); } throw createError(name, arguments.length, 0, arguments[0], 'string,Array,Matrix'); }
...
math.atan2(3, -3) / math.pi; // 0.75
math.log(1000, 10); // 3
math.sqrt(-4); // 2i
math.pow([[-1, 2], [3, 1]], 2); // [[7, 0], [0, 7]]
math.derivative('x^2 + x', 'x'); // 2 * x + 1
// expressions
math.eval('12 / (2.3 + 0.7)'); // 4
math.eval('5.08 cm to inch'); // 2 inch
math.eval('sin(45 deg) ^ 2'); // 0.5
math.eval('9 / 3 + 2i'); // 3 + 2i
math.eval('det([-1, 2; 3, 1])'); // -7
// chaining
math.chain(3)
...
function exp(arg0) { "use strict"; var name = 'exp'; if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature0(arg0); // signature: number } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: Complex if (arguments.length === 1) { return signature1(arg0); // signature: Complex } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test2(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature2(arg0); // signature: BigNumber } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test3(arg0)) { // type: Array if (arguments.length === 1) { return signature3(arg0); // signature: Array } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test4(arg0)) { // type: Matrix if (arguments.length === 1) { return signature3(arg0); // signature: Matrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test5(arg0)) { // type: Fraction (convert to BigNumber) if (arguments.length === 1) { return signature2(convert0(arg0)); // signature: Fraction } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test6(arg0)) { // type: string (convert to number) if (arguments.length === 1) { return signature0(convert1(arg0)); // signature: string } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test7(arg0)) { // type: boolean (convert to number) if (arguments.length === 1) { return signature0(convert2(arg0)); // signature: boolean } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test8(arg0)) { // type: null (convert to number) if (arguments.length === 1) { return signature0(convert3(arg0)); // signature: null } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'number,Complex,BigNumber,Array,Matrix'); }
...
// https://www.wikiwand.com/en/Cube_root#/Complex_numbers
var arg_3 = x.arg() / 3;
var abs = x.abs();
// principal root:
var principal = new type.Complex(_cbrtNumber(abs), 0).mul(
new type.Complex(0, arg_3).exp());
if (allRoots) {
var all = [
principal,
new type.Complex(_cbrtNumber(abs), 0).mul(
new type.Complex(0, arg_3 + Math.PI * 2 / 3).exp()),
new type.Complex(_cbrtNumber(abs), 0).mul(
...
function eye(arg0, arg1, arg2) { "use strict"; var name = 'eye'; if (arguments.length === 0) { return signature0(); // signature: } if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature1(arg0); // signature: number } if (test0(arg1)) { // type: number if (arguments.length === 2) { return signature2(arg0, arg1); // signature: number, number } if (test1(arg2)) { // type: string if (arguments.length === 3) { return signature3(arg0, arg1, arg2); // signature: number, number, string } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } if (test0(arg2)) { // type: number (convert to string) if (arguments.length === 3) { return signature3(arg0, arg1, convert0(arg2)); // signature: number, number, number } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } if (test2(arg2)) { // type: boolean (convert to string) if (arguments.length === 3) { return signature3(arg0, arg1, convert1(arg2)); // signature: number, number, boolean } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } if (test3(arg2)) { // type: null (convert to string) if (arguments.length === 3) { return signature3(arg0, arg1, convert2(arg2)); // signature: number, number, null } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } throw createError(name, arguments.length, 2, arguments[2], 'string'); } if (test4(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature2(arg0, arg1); // signature: number, BigNumber } if (test1(arg2)) { // type: string if (arguments.length === 3) { return signature3(arg0, arg1, arg2); // signature: number, BigNumber, string } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } if (test0(arg2)) { // type: number (convert to string) if (arguments.length === 3) { return signature3(arg0, arg1, convert0(arg2)); // signature: number, BigNumber, number } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } if (test2(arg2)) { // type: boolean (convert to string) if (arguments.length === 3) { return signature3(arg0, arg1, convert1(arg2)); // signature: number, BigNumber, boolean } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } if (test3(arg2)) { // type: null (convert to string) if (arguments.length === 3) { return signature3(arg0, arg1, convert2(arg2)); // signature: number, BigNumber, null } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } throw createError(name, arguments.length, 2, arguments[2], 'string'); } if (test1(arg1)) { // type: string if (arguments.length === 2) { return signature4(arg0, arg1); // signature: number, string } if (test1(arg2)) { // type: string if (arguments.length === 3) { return signature3(arg0, convert3(arg1), arg2); // signature: number, string, string } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } if (test0(arg2)) { // type: number (convert to string) if (arguments.length === 3) { return signature3(arg0, convert3(arg1), convert0(arg2)); // signature: number, string, number } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } ...
...
/**
* Create a 2-dimensional identity matrix with size m x n or n x n.
* The matrix has ones on the diagonal and zeros elsewhere.
*
* Syntax:
*
* math.eye(n)
* math.eye(n, format)
* math.eye(m, n)
* math.eye(m, n, format)
* math.eye([m, n])
* math.eye([m, n], format)
*
* Examples:
...
function factorial(arg0) { "use strict"; var name = 'factorial'; if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature0(arg0); // signature: number } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature1(arg0); // signature: BigNumber } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test2(arg0)) { // type: Array if (arguments.length === 1) { return signature2(arg0); // signature: Array } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test3(arg0)) { // type: Matrix if (arguments.length === 1) { return signature2(arg0); // signature: Matrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test4(arg0)) { // type: Fraction (convert to BigNumber) if (arguments.length === 1) { return signature1(convert0(arg0)); // signature: Fraction } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test5(arg0)) { // type: string (convert to number) if (arguments.length === 1) { return signature0(convert1(arg0)); // signature: string } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test6(arg0)) { // type: boolean (convert to number) if (arguments.length === 1) { return signature0(convert2(arg0)); // signature: boolean } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test7(arg0)) { // type: null (convert to number) if (arguments.length === 1) { return signature0(convert3(arg0)); // signature: null } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'number,BigNumber,Array,Matrix'); }
...
* Compute the factorial of a value
*
* Factorial only supports an integer value as argument.
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.factorial(n)
*
* Examples:
*
* math.factorial(5); // returns 120
* math.factorial(3); // returns 6
*
* See also:
...
function filterTransform(args, math, scope) { var x, test; if (args[0]) { x = args[0].compile().eval(scope); } if (args[1]) { if (args[1] && args[1].isSymbolNode) { // a function pointer, like filter([3, -2, 5], myTestFunction); test = args[1].compile().eval(scope); } else { // an equation like filter([3, -2, 5], x > 0) // find an undefined symbol var _scope = scope || {}; var symbol = args[1] .filter(function (node) { return (node && node.isSymbolNode) && !(node.name in math) && !(node.name in _scope); })[0]; // create a test function for this equation var sub = Object.create(_scope); var eq = args[1].compile(); if (symbol) { var name = symbol.name; test = function (x) { sub[name] = x; return eq.eval(sub); } } else { throw new Error('No undefined variable found in filter equation'); } } } return filter(x, test); }
...
}
}
}
}
}
// remove duplicates
matches = matches.filter(function(elem, pos, arr) {
return arr.indexOf(elem) == pos;
});
}
return [matches, keyword];
}
...
function fix(arg0) { "use strict"; var name = 'fix'; if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature0(arg0); // signature: number } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: Complex if (arguments.length === 1) { return signature1(arg0); // signature: Complex } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test2(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature2(arg0); // signature: BigNumber } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test3(arg0)) { // type: Fraction if (arguments.length === 1) { return signature3(arg0); // signature: Fraction } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test4(arg0)) { // type: Array if (arguments.length === 1) { return signature4(arg0); // signature: Array } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test5(arg0)) { // type: Matrix if (arguments.length === 1) { return signature4(arg0); // signature: Matrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test6(arg0)) { // type: string (convert to number) if (arguments.length === 1) { return signature0(convert0(arg0)); // signature: string } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test7(arg0)) { // type: boolean (convert to number) if (arguments.length === 1) { return signature0(convert1(arg0)); // signature: boolean } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test8(arg0)) { // type: null (convert to number) if (arguments.length === 1) { return signature0(convert2(arg0)); // signature: null } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'number,Complex,BigNumber,Fraction,Array,Matrix'); }
...
function factory (type, config, load, typed) {
/**
* Round a value towards zero.
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.fix(x)
*
* Examples:
*
* math.fix(3.2); // returns number 3
* math.fix(3.8); // returns number 3
* math.fix(-4.2); // returns number -4
* math.fix(-4.7); // returns number -4
...
function flatten(arg0) { "use strict"; var name = 'flatten'; if (test0(arg0)) { // type: Array if (arguments.length === 1) { return signature0(arg0); // signature: Array } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: Matrix if (arguments.length === 1) { return signature1(arg0); // signature: Matrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'Array,Matrix'); }
...
* @returns {Array} Array whose data has been formatted to fit the
* specified dimensions
*
* @throws {DimensionError} If the product of the new dimension sizes does
* not equal that of the old ones
*/
exports.reshape = function(array, sizes) {
var flatArray = exports.flatten(array);
var newArray;
var product = function (arr) {
return arr.reduce(function (prev, curr) {
return prev * curr;
});
};
...
function floor(arg0) { "use strict"; var name = 'floor'; if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature0(arg0); // signature: number } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: Complex if (arguments.length === 1) { return signature1(arg0); // signature: Complex } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test2(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature2(arg0); // signature: BigNumber } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test3(arg0)) { // type: Fraction if (arguments.length === 1) { return signature3(arg0); // signature: Fraction } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test4(arg0)) { // type: Array if (arguments.length === 1) { return signature4(arg0); // signature: Array } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test5(arg0)) { // type: Matrix if (arguments.length === 1) { return signature4(arg0); // signature: Matrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test6(arg0)) { // type: string (convert to number) if (arguments.length === 1) { return signature0(convert0(arg0)); // signature: string } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test7(arg0)) { // type: boolean (convert to number) if (arguments.length === 1) { return signature0(convert1(arg0)); // signature: boolean } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test8(arg0)) { // type: null (convert to number) if (arguments.length === 1) { return signature0(convert2(arg0)); // signature: null } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'number,Complex,BigNumber,Fraction,Array,Matrix'); }
...
* ceil, floor, round
*
* @param {number | BigNumber | Fraction | Complex | Array | Matrix} x Number to be rounded
* @return {number | BigNumber | Fraction | Complex | Array | Matrix} Rounded value
*/
var fix = typed('fix', {
'number': function (x) {
return (x > 0) ? Math.floor(x) : Math.ceil(x);
},
'Complex': function (x) {
return new type.Complex(
(x.re > 0) ? Math.floor(x.re) : Math.ceil(x.re),
(x.im > 0) ? Math.floor(x.im) : Math.ceil(x.im)
);
...
function forEach(arg0, arg1) { "use strict"; var name = 'forEach'; if (test0(arg0)) { // type: Array if (test1(arg1)) { // type: function if (arguments.length === 2) { return signature0(arg0, arg1); // signature: Array, function } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'function'); } if (test2(arg0)) { // type: Matrix if (test1(arg1)) { // type: function if (arguments.length === 2) { return signature0(arg0, arg1); // signature: Matrix, function } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'function'); } throw createError(name, arguments.length, 0, arguments[0], 'Array,Matrix'); }
...
if (def.indexOf(keyword) == 0) {
matches.push(def);
}
}
}
// commandline keywords
['exit', 'quit', 'clear'].forEach(function (cmd) {
if (cmd.indexOf(keyword) == 0) {
matches.push(cmd);
}
});
// math functions and constants
var ignore = ['expr', 'type'];
...
function format(arg0, arg1) { "use strict"; var name = 'format'; // type: any if (arguments.length === 1) { return signature0(arg0); // signature: any } if (test0(arg1)) { // type: number if (arguments.length === 2) { return signature0(arg0, arg1); // signature: any, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test1(arg1)) { // type: function if (arguments.length === 2) { return signature0(arg0, arg1); // signature: any, function } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: string (convert to number) if (arguments.length === 2) { return signature0(arg0, convert0(arg1)); // signature: any, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: boolean (convert to number) if (arguments.length === 2) { return signature0(arg0, convert1(arg1)); // signature: any, boolean } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test4(arg1)) { // type: null (convert to number) if (arguments.length === 2) { return signature0(arg0, convert2(arg1)); // signature: any, null } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test5(arg1)) { // type: Object if (arguments.length === 2) { return signature0(arg0, arg1); // signature: any, Object } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'number,function,Object'); throw createError(name, arguments.length, 0, arguments[0], 'any'); }
...
* Helper function to format a value. Regular numbers will be rounded
* to 14 digits to prevent round-off errors from showing up.
* @param {*} value
*/
function format(value) {
var math = getMath();
return math.format(value, {
fn: function (value) {
if (typeof value === 'number') {
// round numbers
return math.format(value, PRECISION);
}
else {
return math.format(value);
...
function fraction(arg0, arg1) { "use strict"; var name = 'fraction'; if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature0(arg0); // signature: number } if (test0(arg1)) { // type: number if (arguments.length === 2) { return signature1(arg0, arg1); // signature: number, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test1(arg1)) { // type: string (convert to number) if (arguments.length === 2) { return signature1(arg0, convert0(arg1)); // signature: number, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: boolean (convert to number) if (arguments.length === 2) { return signature1(arg0, convert1(arg1)); // signature: number, boolean } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: null (convert to number) if (arguments.length === 2) { return signature1(arg0, convert2(arg1)); // signature: number, null } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'number'); } if (test4(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature2(arg0); // signature: BigNumber } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test5(arg0)) { // type: Fraction if (arguments.length === 1) { return signature3(arg0); // signature: Fraction } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: string if (arguments.length === 1) { return signature4(arg0); // signature: string } if (test0(arg1)) { // type: number if (arguments.length === 2) { return signature1(convert0(arg0), arg1); // signature: string, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test1(arg1)) { // type: string (convert to number) if (arguments.length === 2) { return signature1(convert0(arg0), convert0(arg1)); // signature: string, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: boolean (convert to number) if (arguments.length === 2) { return signature1(convert0(arg0), convert1(arg1)); // signature: string, boolean } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: null (convert to number) if (arguments.length === 2) { return signature1(convert0(arg0), convert2(arg1)); // signature: string, null } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'number'); } if (test6(arg0)) { // type: Array if (arguments.length === 1) { return signature5(arg0); // signature: Array } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test7(arg0)) { // type: Matrix if (arguments.length === 1) { return signature5(arg0); // signature: Matrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test2(arg0)) { // type: boolean (convert to number) if (arguments.length === 1) { return signature0(convert1(arg0)); // signature: boolean } if (test0(arg1)) { // type: number if (arguments.length === 2) { return signature1(convert1(arg0), arg1); // signature: bo ...
...
case 'number':
// TODO: replace this with using config.number
var numConfig = defs.math.config().number;
if (numConfig === 'BigNumber') {
return 'math.bignumber("' + this.value + '")';
}
else if (numConfig === 'Fraction') {
return 'math.fraction("' + this.value + '")';
}
else {
// remove leading zeros like '003.2' which are not allowed by JavaScript
return this.value.replace(/^(0*)[0-9]/, function (match, zeros) {
return match.substring(zeros.length);
});
}
...
function gamma(arg0) { "use strict"; var name = 'gamma'; if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature0(arg0); // signature: number } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: Complex if (arguments.length === 1) { return signature1(arg0); // signature: Complex } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test2(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature2(arg0); // signature: BigNumber } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test3(arg0)) { // type: Array if (arguments.length === 1) { return signature3(arg0); // signature: Array } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test4(arg0)) { // type: Matrix if (arguments.length === 1) { return signature3(arg0); // signature: Matrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test5(arg0)) { // type: Fraction (convert to BigNumber) if (arguments.length === 1) { return signature2(convert0(arg0)); // signature: Fraction } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test6(arg0)) { // type: string (convert to number) if (arguments.length === 1) { return signature0(convert1(arg0)); // signature: string } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test7(arg0)) { // type: boolean (convert to number) if (arguments.length === 1) { return signature0(convert2(arg0)); // signature: boolean } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test8(arg0)) { // type: null (convert to number) if (arguments.length === 1) { return signature0(convert3(arg0)); // signature: null } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'number,Complex,BigNumber,Array,Matrix'); }
...
* Compute the gamma function of a value using Lanczos approximation for
* small values, and an extended Stirling approximation for large values.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.gamma(n)
*
* Examples:
*
* math.gamma(5); // returns 24
* math.gamma(-0.5); // returns -3.5449077018110335
* math.gamma(math.i); // returns -0.15494982830180973 - 0.49801566811835596i
*
...
function gcd(arg0, arg1, arg2) { "use strict"; var name = 'gcd'; if (test0(arg0)) { // type: number if (test0(arg1)) { // type: number if (arguments.length === 2) { return signature0(arg0, arg1); // signature: number, number } if (test1(arg2) || test2(arg2) || test0(arg2) || test3(arg2)) { // type: ...Array|Matrix|number|BigNumber var varArgs = [arg2]; for (var i = 3; i < arguments.length; i++) { if (test1(arguments[i]) || test2(arguments[i]) || test0(arguments[i]) || test3(arguments[i])) { varArgs.push(arguments[i]); } else { throw createError(name, arguments.length, i, arguments[i], 'Array,Matrix,number,BigNumber'); } } return signature1(arg0, arg1, varArgs); // signature: number, number, ...Array|Matrix|number|BigNumber } throw createError(name, arguments.length, 2, arguments[2], 'Array,Matrix,number,BigNumber'); } if (test3(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature2(convert0(arg0), arg1); // signature: number, BigNumber } if (test1(arg2) || test2(arg2) || test0(arg2) || test3(arg2)) { // type: ...Array|Matrix|number|BigNumber var varArgs = [arg2]; for (var i = 3; i < arguments.length; i++) { if (test1(arguments[i]) || test2(arguments[i]) || test0(arguments[i]) || test3(arguments[i])) { varArgs.push(arguments[i]); } else { throw createError(name, arguments.length, i, arguments[i], 'Array,Matrix,number,BigNumber'); } } return signature1(arg0, arg1, varArgs); // signature: number, BigNumber, ...Array|Matrix|number|BigNumber } throw createError(name, arguments.length, 2, arguments[2], 'Array,Matrix,number,BigNumber'); } if (test4(arg1)) { // type: Fraction if (arguments.length === 2) { return signature3(convert1(arg0), arg1); // signature: number, Fraction } if (test1(arg2) || test2(arg2) || test0(arg2) || test3(arg2)) { // type: ...Array|Matrix|number|BigNumber var varArgs = [arg2]; for (var i = 3; i < arguments.length; i++) { if (test1(arguments[i]) || test2(arguments[i]) || test0(arguments[i]) || test3(arguments[i])) { varArgs.push(arguments[i]); } else { throw createError(name, arguments.length, i, arguments[i], 'Array,Matrix,number,BigNumber'); } } return signature1(arg0, convert2(arg1), varArgs); // signature: number, Fraction, ...Array|Matrix|number|BigNumber } throw createError(name, arguments.length, 2, arguments[2], 'Array,Matrix,number,BigNumber'); } if (test1(arg1)) { // type: Array if (arguments.length === 2) { return signature4(arg0, arg1); // signature: number, Array } if (test1(arg2) || test2(arg2) || test0(arg2) || test3(arg2)) { // type: ...Array|Matrix|number|BigNumber var varArgs = [arg2]; for (var i = 3; i < arguments.length; i++) { if (test1(arguments[i]) || test2(arguments[i]) || test0(arguments[i]) || test3(arguments[i])) { varArgs.push(arguments[i]); } else { throw createError(name, arguments.length, i, arguments[i], 'Array,Matrix,number,BigNumber'); } } return signature1(arg0, arg1, varArgs); // signature: number, Array, ...Array|Matrix|number|BigNumber } throw createError(name, arguments.length, 2, arguments[2], 'Array,Matrix,number,BigNumber'); } if (test2(arg1)) { // type: Matrix if (arguments.length === 2) { return signature5(arg0, arg1); // signature: number, Matrix } if (test1(arg2) || test2(arg2) || test0(arg2) || test3(arg2)) { // type: ...Array|Matrix|number|BigNumber var varArgs = [arg2]; for (var i = 3; i < arguments.length; i++) { if (test1(arguments[i]) || test2(arguments[i]) || test0(arguments[i]) || test3(arguments[i])) { varArgs.push(arguments[i]); ...
...
/**
* Calculate the greatest common divisor for two or more values or arrays.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.gcd(a, b)
* math.gcd(a, b, c, ...)
*
* Examples:
*
* math.gcd(8, 12); // returns 4
* math.gcd(-4, 6); // returns 2
* math.gcd(25, 15, -10); // returns 5
...
function help(arg0) { "use strict"; var name = 'help'; // type: any if (arguments.length === 1) { return signature0(arg0); // signature: any } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } throw createError(name, arguments.length, 0, arguments[0], 'any'); }
...
* Object | `'Object'` | `math.typeof ({a: 2, b: 3})`
* RegExp | `'RegExp'` | `math.typeof (/a regexp/)`
* undefined | `'undefined'` | `math.typeof(undefined)`
* math.type.BigNumber | `'BigNumber'` | `math.typeof (math.bignumber('2.3e500'))`
* math.type.Chain | `'Chain'` | `math.typeof (math.chain(2))`
* math.type.Complex | `'Complex'` | `math.typeof (math.complex(2, 3))`
* math.type.Fraction | `'Fraction'` | `math.typeof (math.fraction(1, 3))`
* math.type.Help | `'Help'` | `math.typeof (math.help('sqrt
'))`
* math.type.Index | `'Index'` | `math.typeof (math.index(1, 3))`
* math.type.Matrix | `'Matrix'` | `math.typeof (math.matrix([[1,2], [3, 4]]))`
* math.type.Range | `'Range'` | `math.typeof (math.range(0, 10))`
* math.type.Unit | `'Unit'` | `math.typeof (math.unit('45 deg'))`
*
* Syntax:
*
...
function hypot(arg0) { "use strict"; var name = 'hypot'; if (test0(arg0)) { // type: Array if (arguments.length === 1) { return signature0(arg0); // signature: Array } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: Matrix if (arguments.length === 1) { return signature1(arg0); // signature: Matrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test2(arg0) || test3(arg0) || test4(arg0) || test5(arg0) || test5(arg0) || test6(arg0) || test6(arg0) || test7(arg0) || test7 (arg0)) { // type: ...number|BigNumber|Fraction|string|boolean|null var varArgs = [arg0]; for (var i = 1; i < arguments.length; i++) { if (test2(arguments[i]) || test3(arguments[i])) { varArgs.push(arguments[i]); } else if (test4(arguments[i])) { varArgs.push(convert0(arguments[i])); } else if (test5(arguments[i])) { varArgs.push(convert1(arguments[i])); } else if (test5(arguments[i])) { varArgs.push(convert2(arguments[i])); } else if (test6(arguments[i])) { varArgs.push(convert3(arguments[i])); } else if (test6(arguments[i])) { varArgs.push(convert4(arguments[i])); } else if (test7(arguments[i])) { varArgs.push(convert5(arguments[i])); } else if (test7(arguments[i])) { varArgs.push(convert6(arguments[i])); } else { throw createError(name, arguments.length, i, arguments[i], 'number,BigNumber'); } } return signature2(varArgs); // signature: ...number|BigNumber|Fraction|string|boolean|null } throw createError(name, arguments.length, 0, arguments[0], 'Array,Matrix,number,BigNumber'); }
...
*
* hypot(a, b, c, ...) = sqrt(a^2 + b^2 + c^2 + ...)
*
* For matrix input, the hypotenusa is calculated for all values in the matrix.
*
* Syntax:
*
* math.hypot(a, b, ...)
* math.hypot([a, b, c, ...])
*
* Examples:
*
* math.hypot(3, 4); // 5
* math.hypot(3, 4, 5); // 7.0710678118654755
* math.hypot([3, 4, 5]); // 7.0710678118654755
...
function im(arg0) { "use strict"; var name = 'im'; if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature0(arg0); // signature: number } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: Complex if (arguments.length === 1) { return signature1(arg0); // signature: Complex } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test2(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature2(arg0); // signature: BigNumber } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test3(arg0)) { // type: Array if (arguments.length === 1) { return signature3(arg0); // signature: Array } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test4(arg0)) { // type: Matrix if (arguments.length === 1) { return signature3(arg0); // signature: Matrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test5(arg0)) { // type: Fraction (convert to BigNumber) if (arguments.length === 1) { return signature2(convert0(arg0)); // signature: Fraction } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test6(arg0)) { // type: string (convert to number) if (arguments.length === 1) { return signature0(convert1(arg0)); // signature: string } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test7(arg0)) { // type: boolean (convert to number) if (arguments.length === 1) { return signature0(convert2(arg0)); // signature: boolean } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test8(arg0)) { // type: null (convert to number) if (arguments.length === 1) { return signature0(convert3(arg0)); // signature: null } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'number,Complex,BigNumber,Array,Matrix'); }
...
* Get the imaginary part of a complex number.
* For a complex number `a + bi`, the function returns `b`.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.im(x)
*
* Examples:
*
* var a = math.complex(2, 3);
* math.re(a); // returns number 2
* math.im(a); // returns number 3
*
...
function indexTransform() { var args = []; for (var i = 0, ii = arguments.length; i < ii; i++) { var arg = arguments[i]; // change from one-based to zero based, and convert BigNumber to number if (arg && arg.isRange === true) { arg.start--; arg.end -= (arg.step > 0 ? 0 : 2); } else if (arg && arg.isSet === true) { arg = arg.map(function (v) { return v - 1; }); } else if (arg && (arg.isArray === true || arg.isMatrix)) { arg = arg.map(function (v) { return v - 1; }); } else if (typeof arg === 'number') { arg--; } else if (arg && arg.isBigNumber === true) { arg = arg.toNumber() - 1; } else if (typeof arg === 'string') { // leave as is } else { throw new TypeError('Dimension must be an Array, Matrix, number, string, or Range'); } args[i] = arg; } var res = new type.Index(); type.Index.apply(res, args); return res; }
...
'})()'
}
else { // ConstantNode
return range._compile(defs, childArgs);
}
});
return 'math.index(' + dimensions.join(', ') + ')';
};
/**
* Execute a callback for each of the child nodes of this node
* @param {function(child: Node, path: string, parent: Node)} callback
*/
IndexNode.prototype.forEach = function (callback) {
...
function intersect(arg0, arg1, arg2, arg3) { "use strict"; var name = 'intersect'; if (test0(arg0)) { // type: Array if (test0(arg1)) { // type: Array if (test0(arg2)) { // type: Array if (arguments.length === 3) { return signature0(arg0, arg1, arg2); // signature: Array, Array, Array } if (test0(arg3)) { // type: Array if (arguments.length === 4) { return signature1(arg0, arg1, arg2, arg3); // signature: Array, Array, Array, Array } if (arguments.length > 4) { throw createError(name, arguments.length, 4, arguments[4]); } } if (test1(arg3)) { // type: Matrix (convert to Array) if (arguments.length === 4) { return signature1(arg0, arg1, arg2, convert0(arg3)); // signature: Array, Array, Array, Matrix } if (arguments.length > 4) { throw createError(name, arguments.length, 4, arguments[4]); } } throw createError(name, arguments.length, 3, arguments[3], 'Array'); } if (test1(arg2)) { // type: Matrix (convert to Array) if (arguments.length === 3) { return signature0(arg0, arg1, convert0(arg2)); // signature: Array, Array, Matrix } if (test0(arg3)) { // type: Array if (arguments.length === 4) { return signature1(arg0, arg1, convert0(arg2), arg3); // signature: Array, Array, Matrix, Array } if (arguments.length > 4) { throw createError(name, arguments.length, 4, arguments[4]); } } if (test1(arg3)) { // type: Matrix (convert to Array) if (arguments.length === 4) { return signature1(arg0, arg1, convert0(arg2), convert0(arg3)); // signature: Array, Array, Matrix, Matrix } if (arguments.length > 4) { throw createError(name, arguments.length, 4, arguments[4]); } } throw createError(name, arguments.length, 3, arguments[3], 'Array'); } throw createError(name, arguments.length, 2, arguments[2], 'Array'); } if (test1(arg1)) { // type: Matrix if (test0(arg2)) { // type: Array if (arguments.length === 3) { return signature0(arg0, convert0(arg1), arg2); // signature: Array, Matrix, Array } if (test0(arg3)) { // type: Array if (arguments.length === 4) { return signature1(arg0, convert0(arg1), arg2, arg3); // signature: Array, Matrix, Array, Array } if (arguments.length > 4) { throw createError(name, arguments.length, 4, arguments[4]); } } if (test1(arg3)) { // type: Matrix (convert to Array) if (arguments.length === 4) { return signature1(arg0, convert0(arg1), arg2, convert0(arg3)); // signature: Array, Matrix, Array, Matrix } if (arguments.length > 4) { throw createError(name, arguments.length, 4, arguments[4]); } } throw createError(name, arguments.length, 3, arguments[3], 'Array'); } if (test1(arg2)) { // type: Matrix if (arguments.length === 3) { return signature2(convert1(arg0), arg1, arg2); // signature: Array, Matrix, Matrix } if (test0(arg3)) { // type: Array if (arguments.length === 4) { return signature1(arg0, convert0(arg1), convert0(arg2), arg3); // signature: Array, Matrix, Matrix, Array } if (arguments.length > 4) { throw createError(name, arguments.length, 4, arguments[4]); } } if (test1(arg3)) { // type: Matrix if (arguments.length === 4) { return signature3(convert1(arg0), arg1, arg2, arg3); // signature: Array, Matrix, Matrix, Matrix } if (arguments.length > 4) { throw createError(name, arguments.length, 4, arguments[4]); } } throw createError(name, arguments.length, 3, arguments[3], 'Array,Matrix ...
...
* arrays or 1 dimensional matrices. The line intersection functions return null
* if the lines do not meet.
*
* Note: Fill the plane coefficients as `x + y + z = c` and not as `x + y + z + c = 0`.
*
* Syntax:
*
* math.intersect(endPoint1Line1, endPoint2Line1, endPoint1Line2, endPoint2Line2)
* math.intersect(endPoint1, endPoint2, planeCoefficients)
*
* Examples:
*
* math.intersect([0, 0], [10, 10], [10, 0], [0, 10]); // Returns [5, 5]
* math.intersect([0, 0, 0], [10, 10, 0], [10, 0, 0], [0, 10, 0]); // Returns [5, 5, 0]
* math.intersect([1, 0, 1], [4, -2, 2], [1, 1, 1, 6]); // Returns [7, -4, 3]
...
function inv(arg0) { "use strict"; var name = 'inv'; if (test0(arg0)) { // type: Array if (arguments.length === 1) { return signature0(arg0); // signature: Array } } if (test1(arg0)) { // type: Matrix if (arguments.length === 1) { return signature0(arg0); // signature: Matrix } } // type: any if (arguments.length === 1) { return signature1(arg0); // signature: any } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } throw createError(name, arguments.length, 0, arguments[0], 'Array,Matrix,any'); }
...
var eye = load(require('./eye'));
/**
* Calculate the inverse of a square matrix.
*
* Syntax:
*
* math.inv(x)
*
* Examples:
*
* math.inv([[1, 2], [3, 4]]); // returns [[-2, 1], [1.5, -0.5]]
* math.inv(4); // returns 0.25
* 1 / 4; // returns 0.25
*
...
function isInteger(arg0) { "use strict"; var name = 'isInteger'; if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature0(arg0); // signature: number } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature1(arg0); // signature: BigNumber } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test2(arg0)) { // type: Fraction if (arguments.length === 1) { return signature2(arg0); // signature: Fraction } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test3(arg0)) { // type: Array if (arguments.length === 1) { return signature3(arg0); // signature: Array } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test4(arg0)) { // type: Matrix if (arguments.length === 1) { return signature3(arg0); // signature: Matrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test5(arg0)) { // type: string (convert to number) if (arguments.length === 1) { return signature0(convert0(arg0)); // signature: string } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test6(arg0)) { // type: boolean (convert to number) if (arguments.length === 1) { return signature0(convert1(arg0)); // signature: boolean } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test7(arg0)) { // type: null (convert to number) if (arguments.length === 1) { return signature0(convert2(arg0)); // signature: null } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'number,BigNumber,Fraction,Array,Matrix'); }
...
/**
* Test whether index is an integer number with index >= 0 and index < length
* when length is provided
* @param {number} index Zero-based index
* @param {number} [length] Length of the array
*/
exports.validateIndex = function(index, length) {
if (!number.isNumber(index) || !number.isInteger(index)) {
throw new TypeError('Index must be an integer (value: ' + index + ')');
}
if (index < 0 || (typeof length === 'number' && index >= length)) {
throw new IndexError(index, length);
}
};
...
function isNaN(arg0) { "use strict"; var name = 'isNaN'; if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature0(arg0); // signature: number } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: Complex if (arguments.length === 1) { return signature1(arg0); // signature: Complex } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test2(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature2(arg0); // signature: BigNumber } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test3(arg0)) { // type: Fraction if (arguments.length === 1) { return signature3(arg0); // signature: Fraction } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test4(arg0)) { // type: Unit if (arguments.length === 1) { return signature4(arg0); // signature: Unit } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test5(arg0)) { // type: Array if (arguments.length === 1) { return signature5(arg0); // signature: Array } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test6(arg0)) { // type: Matrix if (arguments.length === 1) { return signature5(arg0); // signature: Matrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test7(arg0)) { // type: string (convert to number) if (arguments.length === 1) { return signature0(convert0(arg0)); // signature: string } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test8(arg0)) { // type: boolean (convert to number) if (arguments.length === 1) { return signature0(convert1(arg0)); // signature: boolean } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test9(arg0)) { // type: null (convert to number) if (arguments.length === 1) { return signature0(convert2(arg0)); // signature: null } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'number,Complex,BigNumber,Fraction,Unit,Array,Matrix'); }
...
},
'Complex, Complex': function (x, y) {
return (x.re !== 0 || x.im !== 0) && (y.re !== 0 || y.im !== 0);
},
'BigNumber, BigNumber': function (x, y) {
return !x.isZero() && !y.isZero() && !x.isNaN() && !y
.isNaN();
},
'Unit, Unit': function (x, y) {
return and(x.value, y.value);
},
'Matrix, Matrix': function (x, y) {
...
function isNegative(arg0) { "use strict"; var name = 'isNegative'; if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature0(arg0); // signature: number } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature1(arg0); // signature: BigNumber } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test2(arg0)) { // type: Fraction if (arguments.length === 1) { return signature2(arg0); // signature: Fraction } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test3(arg0)) { // type: Unit if (arguments.length === 1) { return signature3(arg0); // signature: Unit } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test4(arg0)) { // type: Array if (arguments.length === 1) { return signature4(arg0); // signature: Array } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test5(arg0)) { // type: Matrix if (arguments.length === 1) { return signature4(arg0); // signature: Matrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test6(arg0)) { // type: string (convert to number) if (arguments.length === 1) { return signature0(convert0(arg0)); // signature: string } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test7(arg0)) { // type: boolean (convert to number) if (arguments.length === 1) { return signature0(convert1(arg0)); // signature: boolean } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test8(arg0)) { // type: null (convert to number) if (arguments.length === 1) { return signature0(convert2(arg0)); // signature: null } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'number,BigNumber,Fraction,Unit,Array,Matrix'); }
...
return new type.Complex(
(x.re > 0) ? Math.floor(x.re) : Math.ceil(x.re),
(x.im > 0) ? Math.floor(x.im) : Math.ceil(x.im)
);
},
'BigNumber': function (x) {
return x.isNegative() ? x.ceil() : x.floor();
},
'Fraction': function (x) {
return x.s < 0 ? x.ceil() : x.floor();
},
'Array | Matrix': function (x) {
...
function isNumeric(arg0) { "use strict"; var name = 'isNumeric'; if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature0(arg0); // signature: number } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: Complex if (arguments.length === 1) { return signature1(arg0); // signature: Complex } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test2(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature0(arg0); // signature: BigNumber } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test3(arg0)) { // type: Fraction if (arguments.length === 1) { return signature0(arg0); // signature: Fraction } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test4(arg0)) { // type: Unit if (arguments.length === 1) { return signature1(arg0); // signature: Unit } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test5(arg0)) { // type: string if (arguments.length === 1) { return signature1(arg0); // signature: string } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test6(arg0)) { // type: Array if (arguments.length === 1) { return signature2(arg0); // signature: Array } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test7(arg0)) { // type: Matrix if (arguments.length === 1) { return signature2(arg0); // signature: Matrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test8(arg0)) { // type: boolean if (arguments.length === 1) { return signature0(arg0); // signature: boolean } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test9(arg0)) { // type: null (convert to number) if (arguments.length === 1) { return signature0(convert0(arg0)); // signature: null } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'number,Complex,BigNumber,Fraction,Unit,string,Array,Matrix,boolean '); }
...
/**
* Test whether a value is an numeric value.
*
* The function is evaluated element-wise in case of Array or Matrix input.
*
* Syntax:
*
* math.isNumeric(x)
*
* Examples:
*
* math.isNumeric(2); // returns true
* math.isNumeric(0); // returns true
* math.isNumeric(math.bignumber(500)); // returns true
* math.isNumeric(math.fraction(4)); // returns true
...
function isPositive(arg0) { "use strict"; var name = 'isPositive'; if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature0(arg0); // signature: number } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature1(arg0); // signature: BigNumber } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test2(arg0)) { // type: Fraction if (arguments.length === 1) { return signature2(arg0); // signature: Fraction } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test3(arg0)) { // type: Unit if (arguments.length === 1) { return signature3(arg0); // signature: Unit } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test4(arg0)) { // type: Array if (arguments.length === 1) { return signature4(arg0); // signature: Array } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test5(arg0)) { // type: Matrix if (arguments.length === 1) { return signature4(arg0); // signature: Matrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test6(arg0)) { // type: string (convert to number) if (arguments.length === 1) { return signature0(convert0(arg0)); // signature: string } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test7(arg0)) { // type: boolean (convert to number) if (arguments.length === 1) { return signature0(convert1(arg0)); // signature: boolean } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test8(arg0)) { // type: null (convert to number) if (arguments.length === 1) { return signature0(convert2(arg0)); // signature: null } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'number,BigNumber,Fraction,Unit,Array,Matrix'); }
...
* Test whether a value is positive: larger than zero.
* The function supports types `number`, `BigNumber`, `Fraction`, and `Unit`.
*
* The function is evaluated element-wise in case of Array or Matrix input.
*
* Syntax:
*
* math.isPositive(x)
*
* Examples:
*
* math.isPositive(3); // returns true
* math.isPositive(-2); // returns false
* math.isPositive(0); // returns false
* math.isPositive(-0); // returns false
...
function isPrime(arg0) { "use strict"; var name = 'isPrime'; if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature0(arg0); // signature: number } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature1(arg0); // signature: BigNumber } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test2(arg0)) { // type: Array if (arguments.length === 1) { return signature2(arg0); // signature: Array } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test3(arg0)) { // type: Matrix if (arguments.length === 1) { return signature2(arg0); // signature: Matrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test4(arg0)) { // type: Fraction (convert to BigNumber) if (arguments.length === 1) { return signature1(convert0(arg0)); // signature: Fraction } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test5(arg0)) { // type: string (convert to number) if (arguments.length === 1) { return signature0(convert1(arg0)); // signature: string } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test6(arg0)) { // type: boolean (convert to number) if (arguments.length === 1) { return signature0(convert2(arg0)); // signature: boolean } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test7(arg0)) { // type: null (convert to number) if (arguments.length === 1) { return signature0(convert3(arg0)); // signature: null } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'number,BigNumber,Array,Matrix'); }
...
* Test whether a value is prime: has no divisors other than itself and one.
* The function supports type `number`, `bignumber`.
*
* The function is evaluated element-wise in case of Array or Matrix input.
*
* Syntax:
*
* math.isPrime(x)
*
* Examples:
*
* math.isPrime(3); // returns true
* math.isPrime(-2); // returns false
* math.isPrime(0); // returns false
* math.isPrime(-0); // returns false
...
function isZero(arg0) { "use strict"; var name = 'isZero'; if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature0(arg0); // signature: number } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: Complex if (arguments.length === 1) { return signature1(arg0); // signature: Complex } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test2(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature2(arg0); // signature: BigNumber } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test3(arg0)) { // type: Fraction if (arguments.length === 1) { return signature3(arg0); // signature: Fraction } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test4(arg0)) { // type: Unit if (arguments.length === 1) { return signature4(arg0); // signature: Unit } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test5(arg0)) { // type: Array if (arguments.length === 1) { return signature5(arg0); // signature: Array } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test6(arg0)) { // type: Matrix if (arguments.length === 1) { return signature5(arg0); // signature: Matrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test7(arg0)) { // type: string (convert to number) if (arguments.length === 1) { return signature0(convert0(arg0)); // signature: string } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test8(arg0)) { // type: boolean (convert to number) if (arguments.length === 1) { return signature0(convert1(arg0)); // signature: boolean } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test9(arg0)) { // type: null (convert to number) if (arguments.length === 1) { return signature0(convert2(arg0)); // signature: null } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'number,Complex,BigNumber,Fraction,Unit,Array,Matrix'); }
...
},
'number': function (x) {
return !!x;
},
'BigNumber': function (x) {
return !x.isZero();
},
'string': function (x) {
// try case insensitive
var lcase = x.toLowerCase();
if (lcase === 'true') {
return true;
...
function kldivergence(arg0, arg1) { "use strict"; var name = 'kldivergence'; if (test0(arg0)) { // type: Array if (test0(arg1)) { // type: Array if (arguments.length === 2) { return signature0(arg0, arg1); // signature: Array, Array } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test1(arg1)) { // type: Matrix if (arguments.length === 2) { return signature1(arg0, arg1); // signature: Array, Matrix } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'Array,Matrix'); } if (test1(arg0)) { // type: Matrix if (test0(arg1)) { // type: Array if (arguments.length === 2) { return signature2(arg0, arg1); // signature: Matrix, Array } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test1(arg1)) { // type: Matrix if (arguments.length === 2) { return signature3(arg0, arg1); // signature: Matrix, Matrix } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'Array,Matrix'); } throw createError(name, arguments.length, 0, arguments[0], 'Array,Matrix'); }
...
var isNumeric = load(require('../utils/isNumeric'));
/**
* Calculate the Kullback-Leibler (KL) divergence between two distributions
*
* Syntax:
*
* math.kldivergence(x, y)
*
* Examples:
*
* math.kldivergence([0.7,0.5,0.4], [0.2,0.9,0.5]); //returns 0.24376698773121153
*
*
* @param {Array | Matrix} q First vector
...
function kron(arg0, arg1) { "use strict"; var name = 'kron'; if (test0(arg0)) { // type: Array if (test0(arg1)) { // type: Array if (arguments.length === 2) { return signature0(arg0, arg1); // signature: Array, Array } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test1(arg1)) { // type: Matrix if (arguments.length === 2) { return signature1(arg0, arg1); // signature: Array, Matrix } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'Array,Matrix'); } if (test1(arg0)) { // type: Matrix if (test0(arg1)) { // type: Array if (arguments.length === 2) { return signature2(arg0, arg1); // signature: Matrix, Array } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test1(arg1)) { // type: Matrix if (arguments.length === 2) { return signature3(arg0, arg1); // signature: Matrix, Matrix } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'Array,Matrix'); } throw createError(name, arguments.length, 0, arguments[0], 'Array,Matrix'); }
...
*
* NOTE: If a one dimensional vector / matrix is given, it will be
* wrapped so its two dimensions.
* See the examples.
*
* Syntax:
*
* math.kron(x, y)
*
* Examples:
*
* math.kron([[1, 0], [0, 1]], [[1, 2], [3, 4]]);
* // returns [ [ 1, 2, 0, 0 ], [ 3, 4, 0, 0 ], [ 0, 0, 1, 2 ], [ 0, 0, 3, 4 ] ]
*
* math.kron([1,1], [2,3,4]);
...
function larger(arg0, arg1) { "use strict"; var name = 'larger'; if (test0(arg0)) { // type: number if (test0(arg1)) { // type: number if (arguments.length === 2) { return signature0(arg0, arg1); // signature: number, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test1(arg1)) { // type: Complex if (arguments.length === 2) { return signature1(convert0(arg0), arg1); // signature: number, Complex } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature2(convert1(arg0), arg1); // signature: number, BigNumber } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: Fraction if (arguments.length === 2) { return signature3(convert2(arg0), arg1); // signature: number, Fraction } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test4(arg1)) { // type: string (convert to number) if (arguments.length === 2) { return signature0(arg0, convert3(arg1)); // signature: number, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test5(arg1)) { // type: boolean (convert to number) if (arguments.length === 2) { return signature0(arg0, convert4(arg1)); // signature: number, boolean } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test6(arg1)) { // type: null (convert to number) if (arguments.length === 2) { return signature0(arg0, convert5(arg1)); // signature: number, null } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } } if (test1(arg0)) { // type: Complex if (test1(arg1)) { // type: Complex if (arguments.length === 2) { return signature1(arg0, arg1); // signature: Complex, Complex } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test0(arg1)) { // type: number (convert to Complex) if (arguments.length === 2) { return signature1(arg0, convert0(arg1)); // signature: Complex, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: BigNumber (convert to Complex) if (arguments.length === 2) { return signature1(arg0, convert6(arg1)); // signature: Complex, BigNumber } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: Fraction (convert to Complex) if (arguments.length === 2) { return signature1(arg0, convert7(arg1)); // signature: Complex, Fraction } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test4(arg1)) { // type: string (convert to Complex) if (arguments.length === 2) { return signature1(arg0, convert8(arg1)); // signature: Complex, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } } if (test2(arg0)) { // type: BigNumber if (test1(arg1)) { // type: Complex if (arguments.length === 2) { return signature1(convert6(arg0), arg1); // signature: BigNumber, Complex } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature2(arg0, arg1); // signature: BigNumber, BigNu ...
...
*
* Syntax:
*
* math.largerEq(x, y)
*
* Examples:
*
* math.larger(2, 1 + 1); // returns false
* math.largerEq(2, 1 + 1); // returns true
*
* See also:
*
* equal, unequal, smaller, smallerEq, larger, compare
*
* @param {number | BigNumber | Fraction | boolean | Unit | string | Array | Matrix} x First value to compare
...
function largerEq(arg0, arg1) { "use strict"; var name = 'largerEq'; if (test0(arg0)) { // type: number if (test0(arg1)) { // type: number if (arguments.length === 2) { return signature0(arg0, arg1); // signature: number, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test1(arg1)) { // type: Complex if (arguments.length === 2) { return signature1(convert0(arg0), arg1); // signature: number, Complex } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature2(convert1(arg0), arg1); // signature: number, BigNumber } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: Fraction if (arguments.length === 2) { return signature3(convert2(arg0), arg1); // signature: number, Fraction } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test4(arg1)) { // type: string (convert to number) if (arguments.length === 2) { return signature0(arg0, convert3(arg1)); // signature: number, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test5(arg1)) { // type: boolean (convert to number) if (arguments.length === 2) { return signature0(arg0, convert4(arg1)); // signature: number, boolean } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test6(arg1)) { // type: null (convert to number) if (arguments.length === 2) { return signature0(arg0, convert5(arg1)); // signature: number, null } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } } if (test1(arg0)) { // type: Complex if (test1(arg1)) { // type: Complex if (arguments.length === 2) { return signature1(arg0, arg1); // signature: Complex, Complex } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test0(arg1)) { // type: number (convert to Complex) if (arguments.length === 2) { return signature1(arg0, convert0(arg1)); // signature: Complex, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: BigNumber (convert to Complex) if (arguments.length === 2) { return signature1(arg0, convert6(arg1)); // signature: Complex, BigNumber } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: Fraction (convert to Complex) if (arguments.length === 2) { return signature1(arg0, convert7(arg1)); // signature: Complex, Fraction } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test4(arg1)) { // type: string (convert to Complex) if (arguments.length === 2) { return signature1(arg0, convert8(arg1)); // signature: Complex, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } } if (test2(arg0)) { // type: BigNumber if (test1(arg1)) { // type: Complex if (arguments.length === 2) { return signature1(convert6(arg0), arg1); // signature: BigNumber, Complex } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature2(arg0, arg1); // signature: BigNumber, B ...
...
* difference between x and y is smaller than the configured epsilon. The
* function cannot be used to compare values smaller than approximately 2.22e-16.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.largerEq(x, y)
*
* Examples:
*
* math.larger(2, 1 + 1); // returns false
* math.largerEq(2, 1 + 1); // returns true
*
* See also:
...
function lcm(arg0, arg1, arg2) { "use strict"; var name = 'lcm'; if (test0(arg0)) { // type: number if (test0(arg1)) { // type: number if (arguments.length === 2) { return signature0(arg0, arg1); // signature: number, number } if (test1(arg2) || test2(arg2) || test0(arg2) || test3(arg2)) { // type: ...Array|Matrix|number|BigNumber var varArgs = [arg2]; for (var i = 3; i < arguments.length; i++) { if (test1(arguments[i]) || test2(arguments[i]) || test0(arguments[i]) || test3(arguments[i])) { varArgs.push(arguments[i]); } else { throw createError(name, arguments.length, i, arguments[i], 'Array,Matrix,number,BigNumber'); } } return signature1(arg0, arg1, varArgs); // signature: number, number, ...Array|Matrix|number|BigNumber } throw createError(name, arguments.length, 2, arguments[2], 'Array,Matrix,number,BigNumber'); } if (test3(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature2(convert0(arg0), arg1); // signature: number, BigNumber } if (test1(arg2) || test2(arg2) || test0(arg2) || test3(arg2)) { // type: ...Array|Matrix|number|BigNumber var varArgs = [arg2]; for (var i = 3; i < arguments.length; i++) { if (test1(arguments[i]) || test2(arguments[i]) || test0(arguments[i]) || test3(arguments[i])) { varArgs.push(arguments[i]); } else { throw createError(name, arguments.length, i, arguments[i], 'Array,Matrix,number,BigNumber'); } } return signature1(arg0, arg1, varArgs); // signature: number, BigNumber, ...Array|Matrix|number|BigNumber } throw createError(name, arguments.length, 2, arguments[2], 'Array,Matrix,number,BigNumber'); } if (test4(arg1)) { // type: Fraction if (arguments.length === 2) { return signature3(convert1(arg0), arg1); // signature: number, Fraction } if (test1(arg2) || test2(arg2) || test0(arg2) || test3(arg2)) { // type: ...Array|Matrix|number|BigNumber var varArgs = [arg2]; for (var i = 3; i < arguments.length; i++) { if (test1(arguments[i]) || test2(arguments[i]) || test0(arguments[i]) || test3(arguments[i])) { varArgs.push(arguments[i]); } else { throw createError(name, arguments.length, i, arguments[i], 'Array,Matrix,number,BigNumber'); } } return signature1(arg0, convert2(arg1), varArgs); // signature: number, Fraction, ...Array|Matrix|number|BigNumber } throw createError(name, arguments.length, 2, arguments[2], 'Array,Matrix,number,BigNumber'); } if (test1(arg1)) { // type: Array if (arguments.length === 2) { return signature4(arg0, arg1); // signature: number, Array } if (test1(arg2) || test2(arg2) || test0(arg2) || test3(arg2)) { // type: ...Array|Matrix|number|BigNumber var varArgs = [arg2]; for (var i = 3; i < arguments.length; i++) { if (test1(arguments[i]) || test2(arguments[i]) || test0(arguments[i]) || test3(arguments[i])) { varArgs.push(arguments[i]); } else { throw createError(name, arguments.length, i, arguments[i], 'Array,Matrix,number,BigNumber'); } } return signature1(arg0, arg1, varArgs); // signature: number, Array, ...Array|Matrix|number|BigNumber } throw createError(name, arguments.length, 2, arguments[2], 'Array,Matrix,number,BigNumber'); } if (test2(arg1)) { // type: Matrix if (arguments.length === 2) { return signature5(arg0, arg1); // signature: number, Matrix } if (test1(arg2) || test2(arg2) || test0(arg2) || test3(arg2)) { // type: ...Array|Matrix|number|BigNumber var varArgs = [arg2]; for (var i = 3; i < arguments.length; i++) { if (test1(arguments[i]) || test2(arguments[i]) || test0(arguments[i]) || test3(arguments[i])) { varArgs.push(arguments[i]); ...
...
*
* lcm(a, b) = abs(a * b) / gcd(a, b)
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.lcm(a, b)
* math.lcm(a, b, c, ...)
*
* Examples:
*
* math.lcm(4, 6); // returns 12
* math.lcm(6, 21); // returns 42
* math.lcm(6, 21, 5); // returns 210
...
function leftShift(arg0, arg1) { "use strict"; var name = 'leftShift'; if (test0(arg0)) { // type: number if (test0(arg1)) { // type: number if (arguments.length === 2) { return signature0(arg0, arg1); // signature: number, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test1(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature1(convert0(arg0), arg1); // signature: number, BigNumber } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: Array if (arguments.length === 2) { return signature2(arg0, arg1); // signature: number, Array } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: Matrix if (arguments.length === 2) { return signature3(arg0, arg1); // signature: number, Matrix } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test4(arg1)) { // type: Fraction (convert to BigNumber) if (arguments.length === 2) { return signature1(convert0(arg0), convert1(arg1)); // signature: number, Fraction } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test5(arg1)) { // type: string (convert to number) if (arguments.length === 2) { return signature0(arg0, convert2(arg1)); // signature: number, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test6(arg1)) { // type: boolean (convert to number) if (arguments.length === 2) { return signature0(arg0, convert3(arg1)); // signature: number, boolean } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test7(arg1)) { // type: null (convert to number) if (arguments.length === 2) { return signature0(arg0, convert4(arg1)); // signature: number, null } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'number,BigNumber,Array,Matrix'); } if (test1(arg0)) { // type: BigNumber if (test1(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature1(arg0, arg1); // signature: BigNumber, BigNumber } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: Array if (arguments.length === 2) { return signature2(arg0, arg1); // signature: BigNumber, Array } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: Matrix if (arguments.length === 2) { return signature3(arg0, arg1); // signature: BigNumber, Matrix } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test0(arg1)) { // type: number (convert to BigNumber) if (arguments.length === 2) { return signature1(arg0, convert0(arg1)); // signature: BigNumber, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test4(arg1)) { // type: Fraction (convert to BigNumber) if (arguments.length === 2) { return signature1(arg0, convert1(arg1)); // signature: BigNumber, Fraction } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test5(arg1)) { // type: string (convert to BigNumber) if (arguments.length === 2) { return signature1(arg0, conv ...
...
/**
* Bitwise left logical shift of a value x by y number of bits, `x << y`.
* For matrices, the function is evaluated element wise.
* For units, the function is evaluated on the best prefix base.
*
* Syntax:
*
* math.leftShift(x, y)
*
* Examples:
*
* math.leftShift(1, 2); // returns number 4
*
* math.leftShift([1, 2, 3], 4); // returns Array [16, 32, 64]
*
...
function log(arg0, arg1) { "use strict"; var name = 'log'; if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature0(arg0); // signature: number } } if (test1(arg0)) { // type: Complex if (arguments.length === 1) { return signature1(arg0); // signature: Complex } } if (test2(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature2(arg0); // signature: BigNumber } } if (test3(arg0)) { // type: Array if (arguments.length === 1) { return signature3(arg0); // signature: Array } } if (test4(arg0)) { // type: Matrix if (arguments.length === 1) { return signature3(arg0); // signature: Matrix } } if (test5(arg0)) { // type: Fraction (convert to BigNumber) if (arguments.length === 1) { return signature2(convert0(arg0)); // signature: Fraction } } if (test6(arg0)) { // type: string (convert to number) if (arguments.length === 1) { return signature0(convert1(arg0)); // signature: string } } if (test7(arg0)) { // type: boolean (convert to number) if (arguments.length === 1) { return signature0(convert2(arg0)); // signature: boolean } } if (test8(arg0)) { // type: null (convert to number) if (arguments.length === 1) { return signature0(convert3(arg0)); // signature: null } } // type: any // type: any if (arguments.length === 2) { return signature4(arg0, arg1); // signature: any, any } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } throw createError(name, arguments.length, 1, arguments[1], 'any'); throw createError(name, arguments.length, 0, arguments[0], 'number,Complex,BigNumber,Array,Matrix,any'); }
...
```js
// load math.js
var math = require('mathjs');
// functions and constants
math.round(math.e, 3); // 2.718
math.atan2(3, -3) / math.pi; // 0.75
math.log(1000, 10); // 3
math.sqrt(-4); // 2i
math.pow([[-1, 2], [3, 1]], 2); // [[7, 0], [0, 7]]
math.derivative('x^2 + x', 'x'); // 2 * x + 1
// expressions
math.eval('12 / (2.3 + 0.7)'); // 4
math.eval('5.08 cm to inch'); // 2 inch
...
function log10(arg0) { "use strict"; var name = 'log10'; if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature0(arg0); // signature: number } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: Complex if (arguments.length === 1) { return signature1(arg0); // signature: Complex } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test2(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature2(arg0); // signature: BigNumber } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test3(arg0)) { // type: Array if (arguments.length === 1) { return signature3(arg0); // signature: Array } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test4(arg0)) { // type: Matrix if (arguments.length === 1) { return signature3(arg0); // signature: Matrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test5(arg0)) { // type: Fraction (convert to BigNumber) if (arguments.length === 1) { return signature2(convert0(arg0)); // signature: Fraction } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test6(arg0)) { // type: string (convert to number) if (arguments.length === 1) { return signature0(convert1(arg0)); // signature: string } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test7(arg0)) { // type: boolean (convert to number) if (arguments.length === 1) { return signature0(convert2(arg0)); // signature: boolean } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test8(arg0)) { // type: null (convert to number) if (arguments.length === 1) { return signature0(convert3(arg0)); // signature: null } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'number,Complex,BigNumber,Array,Matrix'); }
...
/**
* Calculate the 10-base logarithm of a value. This is the same as calculating `log(x, 10)`.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.log10(x)
*
* Examples:
*
* math.log10(0.00001); // returns -5
* math.log10(10000); // returns 4
* math.log(10000) / math.log(10); // returns 4
* math.pow(10, 4); // returns 10000
...
function lsolve(arg0, arg1) { "use strict"; var name = 'lsolve'; if (test0(arg0)) { // type: Array if (test0(arg1)) { // type: Array if (arguments.length === 2) { return signature0(arg0, arg1); // signature: Array, Array } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test1(arg1)) { // type: Matrix if (arguments.length === 2) { return signature0(arg0, arg1); // signature: Array, Matrix } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'Array,Matrix'); } if (test2(arg0)) { // type: DenseMatrix if (test0(arg1)) { // type: Array if (arguments.length === 2) { return signature1(arg0, arg1); // signature: DenseMatrix, Array } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test1(arg1)) { // type: Matrix if (arguments.length === 2) { return signature1(arg0, arg1); // signature: DenseMatrix, Matrix } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'Array,Matrix'); } if (test3(arg0)) { // type: SparseMatrix if (test0(arg1)) { // type: Array if (arguments.length === 2) { return signature2(arg0, arg1); // signature: SparseMatrix, Array } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test1(arg1)) { // type: Matrix if (arguments.length === 2) { return signature2(arg0, arg1); // signature: SparseMatrix, Matrix } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'Array,Matrix'); } if (test1(arg0)) { // type: Matrix (convert to Array) if (test0(arg1)) { // type: Array if (arguments.length === 2) { return signature0(convert0(arg0), arg1); // signature: Matrix, Array } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test1(arg1)) { // type: Matrix if (arguments.length === 2) { return signature0(convert0(arg0), arg1); // signature: Matrix, Matrix } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'Array,Matrix'); } throw createError(name, arguments.length, 0, arguments[0], 'Array,DenseMatrix,SparseMatrix'); }
n/a
function lup(arg0) { "use strict"; var name = 'lup'; if (test0(arg0)) { // type: Array if (arguments.length === 1) { return signature0(arg0); // signature: Array } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: DenseMatrix if (arguments.length === 1) { return signature1(arg0); // signature: DenseMatrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test2(arg0)) { // type: SparseMatrix if (arguments.length === 1) { return signature2(arg0); // signature: SparseMatrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test3(arg0)) { // type: Matrix (convert to Array) if (arguments.length === 1) { return signature0(convert0(arg0)); // signature: Matrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'Array,DenseMatrix,SparseMatrix'); }
n/a
function lusolve(arg0, arg1, arg2, arg3) { "use strict"; var name = 'lusolve'; if (test0(arg0)) { // type: Array if (test0(arg1)) { // type: Array if (arguments.length === 2) { return signature0(arg0, arg1); // signature: Array, Array } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test1(arg1)) { // type: Matrix if (arguments.length === 2) { return signature0(arg0, arg1); // signature: Array, Matrix } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'Array,Matrix'); } if (test2(arg0)) { // type: DenseMatrix if (test0(arg1)) { // type: Array if (arguments.length === 2) { return signature1(arg0, arg1); // signature: DenseMatrix, Array } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test1(arg1)) { // type: Matrix if (arguments.length === 2) { return signature1(arg0, arg1); // signature: DenseMatrix, Matrix } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'Array,Matrix'); } if (test3(arg0)) { // type: SparseMatrix if (test0(arg1)) { // type: Array if (arguments.length === 2) { return signature2(arg0, arg1); // signature: SparseMatrix, Array } if (test4(arg2)) { // type: number if (test4(arg3)) { // type: number if (arguments.length === 4) { return signature3(arg0, arg1, arg2, arg3); // signature: SparseMatrix, Array, number, number } if (arguments.length > 4) { throw createError(name, arguments.length, 4, arguments[4]); } } if (test5(arg3)) { // type: string (convert to number) if (arguments.length === 4) { return signature3(arg0, arg1, arg2, convert0(arg3)); // signature: SparseMatrix, Array, number, string } if (arguments.length > 4) { throw createError(name, arguments.length, 4, arguments[4]); } } if (test6(arg3)) { // type: boolean (convert to number) if (arguments.length === 4) { return signature3(arg0, arg1, arg2, convert1(arg3)); // signature: SparseMatrix, Array, number, boolean } if (arguments.length > 4) { throw createError(name, arguments.length, 4, arguments[4]); } } if (test7(arg3)) { // type: null (convert to number) if (arguments.length === 4) { return signature3(arg0, arg1, arg2, convert2(arg3)); // signature: SparseMatrix, Array, number, null } if (arguments.length > 4) { throw createError(name, arguments.length, 4, arguments[4]); } } throw createError(name, arguments.length, 3, arguments[3], 'number'); } if (test5(arg2)) { // type: string (convert to number) if (test4(arg3)) { // type: number if (arguments.length === 4) { return signature3(arg0, arg1, convert0(arg2), arg3); // signature: SparseMatrix, Array, string, number } if (arguments.length > 4) { throw createError(name, arguments.length, 4, arguments[4]); } } if (test5(arg3)) { // type: string (convert to number) if (arguments.length === 4) { return signature3(arg0, arg1, convert0(arg2), convert0(arg3)); // signature: SparseMatrix, Array, string, string } if (arguments.length > 4) { throw createError(name, arguments.length, 4, arguments[4]); } } if (test6(arg3)) { // type: boolean (convert to number) if (arguments.length === 4) { return signature3(arg0, arg1, convert0(arg2), convert1(arg3)); ...
n/a
function mad(arg0) { "use strict"; var name = 'mad'; if (test0(arg0)) { // type: Array if (arguments.length === 1) { return signature0(arg0); // signature: Array } } if (test1(arg0)) { // type: Matrix if (arguments.length === 1) { return signature0(arg0); // signature: Matrix } } if (arguments.length > 0) { var varArgs = []; for (var i = 0; i < arguments.length; i++) { varArgs.push(arguments[i]); } return signature1(varArgs); // signature: ...any } throw createError(name, arguments.length, 0, arguments[0], 'Array,Matrix,any'); }
...
/**
* Compute the median absolute deviation of a matrix or a list with values.
* The median absolute deviation is defined as the median of the absolute
* deviations from the median.
*
* Syntax:
*
* math.mad(a, b, c, ...)
* math.mad(A)
*
* Examples:
*
* math.mad(10, 20, 30); // returns 10
* math.mad([1, 2, 3]); // returns 1
* math.mad([[1, 2, 3], [4, 5, 6]]); // returns 1.5
...
function max(arg0, arg1) { "use strict"; var name = 'max'; if (test0(arg0)) { // type: Array if (test1(arg1)) { // type: function if (arguments.length === 2) { return signature0(arg0, arg1); // signature: Array, function } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'function'); } if (test2(arg0)) { // type: Matrix if (test1(arg1)) { // type: function if (arguments.length === 2) { return signature1(arg0, arg1); // signature: Matrix, function } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'function'); } throw createError(name, arguments.length, 0, arguments[0], 'Array,Matrix'); }
...
if (res && res.isResultSet) {
// we can have 0 or 1 results in the ResultSet, as the CLI
// does not allow multiple expressions separated by a return
res = res.entries[0];
node = node.blocks
.filter(function (entry) { return entry.visible; })
.map(function (entry) { return entry.node })[0];
}
if (node) {
if (node.isAssignmentNode) {
var name = findSymbolName(node);
if (name != null) {
scope.ans = scope[name];
...
function matrix(arg0, arg1, arg2) { "use strict"; var name = 'matrix'; if (arguments.length === 0) { return signature0(); // signature: } if (test0(arg0)) { // type: string if (arguments.length === 1) { return signature1(arg0); // signature: string } if (test0(arg1)) { // type: string if (arguments.length === 2) { return signature2(arg0, arg1); // signature: string, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test1(arg1)) { // type: number (convert to string) if (arguments.length === 2) { return signature2(arg0, convert0(arg1)); // signature: string, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: boolean (convert to string) if (arguments.length === 2) { return signature2(arg0, convert1(arg1)); // signature: string, boolean } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: null (convert to string) if (arguments.length === 2) { return signature2(arg0, convert2(arg1)); // signature: string, null } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'string'); } if (test4(arg0)) { // type: Array if (arguments.length === 1) { return signature3(arg0); // signature: Array } if (test0(arg1)) { // type: string if (arguments.length === 2) { return signature4(arg0, arg1); // signature: Array, string } if (test0(arg2)) { // type: string if (arguments.length === 3) { return signature4(arg0, arg1, arg2); // signature: Array, string, string } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } if (test1(arg2)) { // type: number (convert to string) if (arguments.length === 3) { return signature4(arg0, arg1, convert0(arg2)); // signature: Array, string, number } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } if (test2(arg2)) { // type: boolean (convert to string) if (arguments.length === 3) { return signature4(arg0, arg1, convert1(arg2)); // signature: Array, string, boolean } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } if (test3(arg2)) { // type: null (convert to string) if (arguments.length === 3) { return signature4(arg0, arg1, convert2(arg2)); // signature: Array, string, null } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } throw createError(name, arguments.length, 2, arguments[2], 'string'); } if (test1(arg1)) { // type: number (convert to string) if (arguments.length === 2) { return signature4(arg0, convert0(arg1)); // signature: Array, number } if (test0(arg2)) { // type: string if (arguments.length === 3) { return signature4(arg0, convert0(arg1), arg2); // signature: Array, number, string } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } if (test1(arg2)) { // type: number (convert to string) if (arguments.length === 3) { return signature4(arg0, convert0(arg1), convert0(arg2)); // signature: Array, number, number } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } if (test2(arg2)) { // type: boolean (convert to string) if (arguments.length === 3) { return signature4(a ...
...
ArrayNode.prototype._compile = function (defs, args) {
var asMatrix = (defs.math.config().matrix !== 'Array');
var items = this.items.map(function (node) {
return node._compile(defs, args);
});
return (asMatrix ? 'math.matrix([' : '[') +
items.join(',') +
(asMatrix ? '])' : ']');
};
/**
* Execute a callback for each of the child nodes of this node
* @param {function(child: Node, path: string, parent: Node)} callback
...
function max(arg0) { "use strict"; var name = 'max'; if (arguments.length > 0) { var varArgs = []; for (var i = 0; i < arguments.length; i++) { varArgs.push(arguments[i]); } return signature0(varArgs); // signature: ...any } throw createError(name, arguments.length, 0, arguments[0], 'any'); }
...
* @return {number} Returns the maximum number of expected arguments.
* Returns -1 when no signatures where found on the function.
*/
exports.maxArgumentCount = function (fn) {
return Object.keys(fn.signatures || {})
.reduce(function (args, signature) {
var count = (signature.match(/,/g) || []).length + 1;
return Math.max(args, count);
}, -1);
};
...
function mean(arg0) { "use strict"; var name = 'mean'; if (arguments.length > 0) { var varArgs = []; for (var i = 0; i < arguments.length; i++) { varArgs.push(arguments[i]); } return signature0(varArgs); // signature: ...any } throw createError(name, arguments.length, 0, arguments[0], 'any'); }
...
* Compute the mean value of matrix or a list with values.
* In case of a multi dimensional array, the mean of the flattened array
* will be calculated. When `dim` is provided, the maximum over the selected
* dimension will be calculated. Parameter `dim` is zero-based.
*
* Syntax:
*
* math.mean(a, b, c, ...)
* math.mean(A)
* math.mean(A, dim)
*
* Examples:
*
* math.mean(2, 1, 4, 3); // returns 2.5
* math.mean([1, 2.7, 3.2, 4]); // returns 2.725
...
function median(arg0, arg1) { "use strict"; var name = 'median'; if (test0(arg0)) { // type: Array if (arguments.length === 1) { return signature0(arg0); // signature: Array } if (test1(arg1)) { // type: number if (arguments.length === 2) { return signature1(arg0, arg1); // signature: Array, number } } if (test2(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature1(arg0, arg1); // signature: Array, BigNumber } } if (test3(arg1)) { // type: Fraction (convert to BigNumber) if (arguments.length === 2) { return signature1(arg0, convert0(arg1)); // signature: Array, Fraction } } if (test4(arg1)) { // type: string (convert to number) if (arguments.length === 2) { return signature1(arg0, convert1(arg1)); // signature: Array, string } } if (test5(arg1)) { // type: boolean (convert to number) if (arguments.length === 2) { return signature1(arg0, convert2(arg1)); // signature: Array, boolean } } if (test6(arg1)) { // type: null (convert to number) if (arguments.length === 2) { return signature1(arg0, convert3(arg1)); // signature: Array, null } } } if (test7(arg0)) { // type: Matrix if (arguments.length === 1) { return signature0(arg0); // signature: Matrix } if (test1(arg1)) { // type: number if (arguments.length === 2) { return signature1(arg0, arg1); // signature: Matrix, number } } if (test2(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature1(arg0, arg1); // signature: Matrix, BigNumber } } if (test3(arg1)) { // type: Fraction (convert to BigNumber) if (arguments.length === 2) { return signature1(arg0, convert0(arg1)); // signature: Matrix, Fraction } } if (test4(arg1)) { // type: string (convert to number) if (arguments.length === 2) { return signature1(arg0, convert1(arg1)); // signature: Matrix, string } } if (test5(arg1)) { // type: boolean (convert to number) if (arguments.length === 2) { return signature1(arg0, convert2(arg1)); // signature: Matrix, boolean } } if (test6(arg1)) { // type: null (convert to number) if (arguments.length === 2) { return signature1(arg0, convert3(arg1)); // signature: Matrix, null } } } if (arguments.length > 0) { var varArgs = []; for (var i = 0; i < arguments.length; i++) { varArgs.push(arguments[i]); } return signature2(varArgs); // signature: ...any } throw createError(name, arguments.length, 0, arguments[0], 'Array,Matrix,any'); }
...
* Supported types of values are: Number, BigNumber, Unit
*
* In case of a (multi dimensional) array or matrix, the median of all
* elements will be calculated.
*
* Syntax:
*
* math.median(a, b, c, ...)
* math.median(A)
*
* Examples:
*
* math.median(5, 2, 7); // returns 5
* math.median([3, -1, 5, 7]); // returns 4
*
...
function min(arg0) { "use strict"; var name = 'min'; if (arguments.length > 0) { var varArgs = []; for (var i = 0; i < arguments.length; i++) { varArgs.push(arguments[i]); } return signature0(varArgs); // signature: ...any } throw createError(name, arguments.length, 0, arguments[0], 'any'); }
...
* @private
*/
function _resize (array, size, dim, defaultValue) {
var i;
var elem;
var oldLen = array.length;
var newLen = size[dim];
var minLen = Math.min(oldLen, newLen);
// apply new length
array.length = newLen;
if (dim < size.length - 1) {
// non-last dimension
var dimNext = dim + 1;
...
function mod(arg0, arg1) { "use strict"; var name = 'mod'; if (test0(arg0)) { // type: number if (test0(arg1)) { // type: number if (arguments.length === 2) { return signature0(arg0, arg1); // signature: number, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test1(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature1(convert0(arg0), arg1); // signature: number, BigNumber } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: Fraction if (arguments.length === 2) { return signature2(convert1(arg0), arg1); // signature: number, Fraction } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: string (convert to number) if (arguments.length === 2) { return signature0(arg0, convert2(arg1)); // signature: number, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test4(arg1)) { // type: boolean (convert to number) if (arguments.length === 2) { return signature0(arg0, convert3(arg1)); // signature: number, boolean } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test5(arg1)) { // type: null (convert to number) if (arguments.length === 2) { return signature0(arg0, convert4(arg1)); // signature: number, null } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } } if (test1(arg0)) { // type: BigNumber if (test1(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature1(arg0, arg1); // signature: BigNumber, BigNumber } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test0(arg1)) { // type: number (convert to BigNumber) if (arguments.length === 2) { return signature1(arg0, convert0(arg1)); // signature: BigNumber, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: Fraction (convert to BigNumber) if (arguments.length === 2) { return signature1(arg0, convert5(arg1)); // signature: BigNumber, Fraction } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: string (convert to BigNumber) if (arguments.length === 2) { return signature1(arg0, convert6(arg1)); // signature: BigNumber, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test4(arg1)) { // type: boolean (convert to BigNumber) if (arguments.length === 2) { return signature1(arg0, convert7(arg1)); // signature: BigNumber, boolean } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test5(arg1)) { // type: null (convert to BigNumber) if (arguments.length === 2) { return signature1(arg0, convert8(arg1)); // signature: BigNumber, null } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } } if (test2(arg0)) { // type: Fraction if (test1(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature1(convert5(arg0), arg1); // signature: Fraction, BigNumber } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: Fraction if (arguments.length === 2) { return signature2(arg0, ar ...
...
if (!a.isInt() || !b.isInt()) {
throw new Error('Parameters in function gcd must be integer numbers');
}
// http://en.wikipedia.org/wiki/Euclidean_algorithm
var zero = new type.BigNumber(0);
while (!b.isZero()) {
var r = a.mod(b);
a = b;
b = r;
}
return a.lt(zero) ? a.neg() : a;
}
}
...
function mode(arg0) { "use strict"; var name = 'mode'; if (test0(arg0)) { // type: Array if (arguments.length === 1) { return signature0(arg0); // signature: Array } } if (test1(arg0)) { // type: Matrix if (arguments.length === 1) { return signature0(arg0); // signature: Matrix } } if (arguments.length > 0) { var varArgs = []; for (var i = 0; i < arguments.length; i++) { varArgs.push(arguments[i]); } return signature1(varArgs); // signature: ...any } throw createError(name, arguments.length, 0, arguments[0], 'Array,Matrix,any'); }
...
/**
* Computes the mode of a set of numbers or a list with values(numbers or characters).
* If there are more than one modes, it returns a list of those values.
*
* Syntax:
*
* math.mode(a, b, c, ...)
* math.mode(A)
*
* Examples:
*
* math.mode(2, 1, 4, 3, 1); // returns [1]
* math.mode([1, 2.7, 3.2, 4, 2.7]); // returns [2.7]
* math.mode(1, 4, 6, 1, 6) // returns [1, 6]
...
function multinomial(arg0) { "use strict"; var name = 'multinomial'; if (test0(arg0)) { // type: Array if (arguments.length === 1) { return signature0(arg0); // signature: Array } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: Matrix if (arguments.length === 1) { return signature0(arg0); // signature: Matrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'Array,Matrix'); }
...
* Multinomial Coefficients compute the number of ways of picking a1, a2, ..., ai unordered outcomes from `n` possibilities.
*
* multinomial takes one array of integers as an argument.
* The following condition must be enforced: every ai <= 0
*
* Syntax:
*
* math.multinomial(a) // a is an array type
*
* Examples:
*
* math.multinomial([1,2,1]); // returns 12
*
* See also:
*
...
function multiply(arg0, arg1, arg2) { "use strict"; var name = 'multiply'; if (test0(arg0)) { // type: number if (test0(arg1)) { // type: number if (arguments.length === 2) { return signature0(arg0, arg1); // signature: number, number } } if (test1(arg1)) { // type: Complex if (arguments.length === 2) { return signature1(convert0(arg0), arg1); // signature: number, Complex } } if (test2(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature2(convert1(arg0), arg1); // signature: number, BigNumber } } if (test3(arg1)) { // type: Fraction if (arguments.length === 2) { return signature3(convert2(arg0), arg1); // signature: number, Fraction } } if (test4(arg1)) { // type: Unit if (arguments.length === 2) { return signature4(arg0, arg1); // signature: number, Unit } } if (test5(arg1)) { // type: string (convert to number) if (arguments.length === 2) { return signature0(arg0, convert3(arg1)); // signature: number, string } } if (test6(arg1)) { // type: boolean (convert to number) if (arguments.length === 2) { return signature0(arg0, convert4(arg1)); // signature: number, boolean } } if (test7(arg1)) { // type: null (convert to number) if (arguments.length === 2) { return signature0(arg0, convert5(arg1)); // signature: number, null } } } if (test1(arg0)) { // type: Complex if (test1(arg1)) { // type: Complex if (arguments.length === 2) { return signature1(arg0, arg1); // signature: Complex, Complex } } if (test4(arg1)) { // type: Unit if (arguments.length === 2) { return signature4(arg0, arg1); // signature: Complex, Unit } } if (test0(arg1)) { // type: number (convert to Complex) if (arguments.length === 2) { return signature1(arg0, convert0(arg1)); // signature: Complex, number } } if (test2(arg1)) { // type: BigNumber (convert to Complex) if (arguments.length === 2) { return signature1(arg0, convert6(arg1)); // signature: Complex, BigNumber } } if (test3(arg1)) { // type: Fraction (convert to Complex) if (arguments.length === 2) { return signature1(arg0, convert7(arg1)); // signature: Complex, Fraction } } if (test5(arg1)) { // type: string (convert to Complex) if (arguments.length === 2) { return signature1(arg0, convert8(arg1)); // signature: Complex, string } } } if (test2(arg0)) { // type: BigNumber if (test1(arg1)) { // type: Complex if (arguments.length === 2) { return signature1(convert6(arg0), arg1); // signature: BigNumber, Complex } } if (test2(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature2(arg0, arg1); // signature: BigNumber, BigNumber } } if (test4(arg1)) { // type: Unit if (arguments.length === 2) { return signature4(arg0, arg1); // signature: BigNumber, Unit } } if (test0(arg1)) { // type: number (convert to BigNumber) if (arguments.length === 2) { return signature2(arg0, convert1(arg1)); // signature: BigNumber, number } } if (test3(arg1)) { // type: Fraction (convert to BigNumber) if (arguments.length === 2) { return signature2(arg0, convert9(arg1)); // signature: BigNumber, Fraction } } if (test5(arg1)) { // type: string (convert to BigNumber) if (arguments.length === 2) { return signature2(arg0, convert10(arg1)); // signature: BigNumber, string } } if (test6(arg1)) { // type: boolean (convert to BigNumber) if (arguments.length === 2) { return signature2(arg0, convert11(arg1)); // signature: BigNumber, boolean } } if (test7(arg1)) { // type: null (convert to BigNumber) if (arguments.length === 2) { return signature2(arg0, convert12(arg1)); // signature ...
...
math.eval('sin(45 deg) ^ 2'); // 0.5
math.eval('9 / 3 + 2i'); // 3 + 2i
math.eval('det([-1, 2; 3, 1])'); // -7
// chaining
math.chain(3)
.add(4)
.multiply(2)
.done(); // 14
```
## Browser support
Math.js works on any ES5 compatible JavaScript engine: node.js 0.10, and Internet Explorer 9 and newer, and all other browsers (
Chrome, Firefox, Safari). If support for old browsers like Internet Explorer 8 is required, the [es5-shim](https://github.com/kriskowal
/es5-shim) library has to be loaded.
...
function norm(arg0, arg1) { "use strict"; var name = 'norm'; if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature0(arg0); // signature: number } if (test0(arg1)) { // type: number if (arguments.length === 2) { return signature1(arg0, arg1); // signature: number, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test1(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature1(arg0, arg1); // signature: number, BigNumber } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: string if (arguments.length === 2) { return signature1(arg0, arg1); // signature: number, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: Fraction (convert to BigNumber) if (arguments.length === 2) { return signature1(arg0, convert0(arg1)); // signature: number, Fraction } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test4(arg1)) { // type: boolean (convert to number) if (arguments.length === 2) { return signature1(arg0, convert1(arg1)); // signature: number, boolean } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test5(arg1)) { // type: null (convert to number) if (arguments.length === 2) { return signature1(arg0, convert2(arg1)); // signature: number, null } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'number,BigNumber,string'); } if (test6(arg0)) { // type: Complex if (arguments.length === 1) { return signature2(arg0); // signature: Complex } if (test0(arg1)) { // type: number if (arguments.length === 2) { return signature1(arg0, arg1); // signature: Complex, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test1(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature1(arg0, arg1); // signature: Complex, BigNumber } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: string if (arguments.length === 2) { return signature1(arg0, arg1); // signature: Complex, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: Fraction (convert to BigNumber) if (arguments.length === 2) { return signature1(arg0, convert0(arg1)); // signature: Complex, Fraction } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test4(arg1)) { // type: boolean (convert to number) if (arguments.length === 2) { return signature1(arg0, convert1(arg1)); // signature: Complex, boolean } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test5(arg1)) { // type: null (convert to number) if (arguments.length === 2) { return signature1(arg0, convert2(arg1)); // signature: Complex, null } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'number,BigNumber,string'); } if (test1(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature3(arg0); // signature: BigNumber } if (test0(arg1)) { // type: nu ...
...
/**
* Calculate the norm of a number, vector or matrix.
*
* The second parameter p is optional. If not provided, it defaults to 2.
*
* Syntax:
*
* math.norm(x)
* math.norm(x, p)
*
* Examples:
*
* math.abs(-3.5); // returns 3.5
* math.norm(-3.5); // returns 3.5
*
...
function not(arg0) { "use strict"; var name = 'not'; if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature0(arg0); // signature: number } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: Complex if (arguments.length === 1) { return signature1(arg0); // signature: Complex } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test2(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature2(arg0); // signature: BigNumber } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test3(arg0)) { // type: Unit if (arguments.length === 1) { return signature3(arg0); // signature: Unit } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test4(arg0)) { // type: Array if (arguments.length === 1) { return signature4(arg0); // signature: Array } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test5(arg0)) { // type: Matrix if (arguments.length === 1) { return signature4(arg0); // signature: Matrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test6(arg0)) { // type: Fraction (convert to BigNumber) if (arguments.length === 1) { return signature2(convert0(arg0)); // signature: Fraction } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test7(arg0)) { // type: string (convert to number) if (arguments.length === 1) { return signature0(convert1(arg0)); // signature: string } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test8(arg0)) { // type: boolean (convert to number) if (arguments.length === 1) { return signature0(convert2(arg0)); // signature: boolean } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test9(arg0)) { // type: null (convert to number) if (arguments.length === 1) { return signature0(convert3(arg0)); // signature: null } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'number,Complex,BigNumber,Unit,Array,Matrix'); }
...
/**
* Logical `not`. Flips boolean value of a given parameter.
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.not(x)
*
* Examples:
*
* math.not(2); // returns false
* math.not(0); // returns true
* math.not(true); // returns false
*
...
function nthRoot(arg0, arg1) { "use strict"; var name = 'nthRoot'; if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature0(arg0); // signature: number } if (test0(arg1)) { // type: number if (arguments.length === 2) { return signature1(arg0, arg1); // signature: number, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test1(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature2(convert0(arg0), arg1); // signature: number, BigNumber } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: Array if (arguments.length === 2) { return signature3(arg0, arg1); // signature: number, Array } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: Matrix if (arguments.length === 2) { return signature4(arg0, arg1); // signature: number, Matrix } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test4(arg1)) { // type: Fraction (convert to BigNumber) if (arguments.length === 2) { return signature2(convert0(arg0), convert1(arg1)); // signature: number, Fraction } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test5(arg1)) { // type: string (convert to number) if (arguments.length === 2) { return signature1(arg0, convert2(arg1)); // signature: number, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test6(arg1)) { // type: boolean (convert to number) if (arguments.length === 2) { return signature1(arg0, convert3(arg1)); // signature: number, boolean } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test7(arg1)) { // type: null (convert to number) if (arguments.length === 2) { return signature1(arg0, convert4(arg1)); // signature: number, null } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'number,BigNumber,Array,Matrix'); } if (test8(arg0)) { // type: Complex if (arguments.length === 1) { return signature5(arg0); // signature: Complex } if (test0(arg1)) { // type: number if (arguments.length === 2) { return signature6(arg0, arg1); // signature: Complex, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test5(arg1)) { // type: string (convert to number) if (arguments.length === 2) { return signature6(arg0, convert2(arg1)); // signature: Complex, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test6(arg1)) { // type: boolean (convert to number) if (arguments.length === 2) { return signature6(arg0, convert3(arg1)); // signature: Complex, boolean } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test7(arg1)) { // type: null (convert to number) if (arguments.length === 2) { return signature6(arg0, convert4(arg1)); // signature: Complex, null } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'number'); } if (test1(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature7(arg0); // signature: BigNumber } if ...
...
*
* x^root = A
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.nthRoot(a)
* math.nthRoot(a, root)
*
* Examples:
*
* math.nthRoot(9, 2); // returns 3, as 3^2 == 9
* math.sqrt(9); // returns 3, as 3^2 == 9
* math.nthRoot(64, 3); // returns 4, as 4^3 == 64
...
function number(arg0, arg1) { "use strict"; var name = 'number'; if (arguments.length === 0) { return signature0(); // signature: } if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature1(arg0); // signature: number } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature2(arg0); // signature: BigNumber } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test2(arg0)) { // type: Fraction if (arguments.length === 1) { return signature3(arg0); // signature: Fraction } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test3(arg0)) { // type: Unit if (arguments.length === 1) { return signature4(arg0); // signature: Unit } if (test3(arg1)) { // type: Unit if (arguments.length === 2) { return signature5(arg0, arg1); // signature: Unit, Unit } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test4(arg1)) { // type: string if (arguments.length === 2) { return signature5(arg0, arg1); // signature: Unit, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test0(arg1)) { // type: number (convert to string) if (arguments.length === 2) { return signature5(arg0, convert0(arg1)); // signature: Unit, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test5(arg1)) { // type: boolean (convert to string) if (arguments.length === 2) { return signature5(arg0, convert1(arg1)); // signature: Unit, boolean } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test6(arg1)) { // type: null (convert to string) if (arguments.length === 2) { return signature5(arg0, convert2(arg1)); // signature: Unit, null } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'Unit,string'); } if (test4(arg0)) { // type: string if (arguments.length === 1) { return signature6(arg0); // signature: string } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test7(arg0)) { // type: Array if (arguments.length === 1) { return signature7(arg0); // signature: Array } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test8(arg0)) { // type: Matrix if (arguments.length === 1) { return signature7(arg0); // signature: Matrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test5(arg0)) { // type: boolean (convert to number) if (arguments.length === 1) { return signature1(convert3(arg0)); // signature: boolean } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test6(arg0)) { // type: null (convert to number) if (arguments.length === 1) { return signature1(convert4(arg0)); // signature: null } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'number,BigNumber,Fraction,Unit,string,Array,Matrix'); }
...
function factory (type, config, load, typed) {
/**
* Create a number or convert a string, boolean, or unit to a number.
* When value is a matrix, all elements will be converted to number.
*
* Syntax:
*
* math.number(value)
* math.number(unit, valuelessUnit)
*
* Examples:
*
* math.number(2); // returns number 2
* math.number('7.2'); // returns number 7.2
* math.number(true); // returns number 1
...
function ones(arg0, arg1) { "use strict"; var name = 'ones'; if (arguments.length === 0) { return signature0(); // signature: } if (test0(arg0)) { // type: Array if (arguments.length === 1) { return signature1(arg0); // signature: Array } if (test1(arg1)) { // type: string if (arguments.length === 2) { return signature2(arg0, arg1); // signature: Array, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: number (convert to string) if (arguments.length === 2) { return signature2(arg0, convert0(arg1)); // signature: Array, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: boolean (convert to string) if (arguments.length === 2) { return signature2(arg0, convert1(arg1)); // signature: Array, boolean } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test4(arg1)) { // type: null (convert to string) if (arguments.length === 2) { return signature2(arg0, convert2(arg1)); // signature: Array, null } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'string'); } if (test5(arg0)) { // type: Matrix if (arguments.length === 1) { return signature3(arg0); // signature: Matrix } if (test1(arg1)) { // type: string if (arguments.length === 2) { return signature2(arg0, arg1); // signature: Matrix, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: number (convert to string) if (arguments.length === 2) { return signature2(arg0, convert0(arg1)); // signature: Matrix, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: boolean (convert to string) if (arguments.length === 2) { return signature2(arg0, convert1(arg1)); // signature: Matrix, boolean } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test4(arg1)) { // type: null (convert to string) if (arguments.length === 2) { return signature2(arg0, convert2(arg1)); // signature: Matrix, null } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'string'); } if (test2(arg0) || test6(arg0) || test1(arg0) || test7(arg0) || test3(arg0) || test3(arg0) || test3(arg0) || test4(arg0) || test4 (arg0) || test4(arg0)) { // type: ...number|BigNumber|string|Fraction|boolean|null var varArgs = [arg0]; for (var i = 1; i < arguments.length; i++) { if (test2(arguments[i]) || test6(arguments[i]) || test1(arguments[i])) { varArgs.push(arguments[i]); } else if (test7(arguments[i])) { varArgs.push(convert3(arguments[i])); } else if (test3(arguments[i])) { varArgs.push(convert4(arguments[i])); } else if (test3(arguments[i])) { varArgs.push(convert5(arguments[i])); } else if (test3(arguments[i])) { varArgs.push(convert1(arguments[i])); } else if (test4(arguments[i])) { varArgs.push(convert6(arguments[i])); } else if (test4(arguments[i])) { varArgs.push(convert2(arguments[i])); } else if (test4(arguments[i])) { varArgs.push(convert7(arguments[i])); } else { throw createError(name, arguments.length, i, arguments[i], 'number,BigNumber,string'); } } return signature4(varArgs); // signature: ...number|BigNum ...
...
/**
* Create a matrix filled with ones. The created matrix can have one or
* multiple dimensions.
*
* Syntax:
*
* math.ones(m)
* math.ones(m, format)
* math.ones(m, n)
* math.ones(m, n, format)
* math.ones([m, n])
* math.ones([m, n], format)
* math.ones([m, n, p, ...])
* math.ones([m, n, p, ...], format)
...
function or(arg0, arg1) { "use strict"; var name = 'or'; if (test0(arg0)) { // type: number if (test0(arg1)) { // type: number if (arguments.length === 2) { return signature0(arg0, arg1); // signature: number, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test1(arg1)) { // type: Complex if (arguments.length === 2) { return signature1(convert0(arg0), arg1); // signature: number, Complex } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature2(convert1(arg0), arg1); // signature: number, BigNumber } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: Fraction (convert to BigNumber) if (arguments.length === 2) { return signature2(convert1(arg0), convert2(arg1)); // signature: number, Fraction } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test4(arg1)) { // type: string (convert to number) if (arguments.length === 2) { return signature0(arg0, convert3(arg1)); // signature: number, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test5(arg1)) { // type: boolean (convert to number) if (arguments.length === 2) { return signature0(arg0, convert4(arg1)); // signature: number, boolean } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test6(arg1)) { // type: null (convert to number) if (arguments.length === 2) { return signature0(arg0, convert5(arg1)); // signature: number, null } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } } if (test1(arg0)) { // type: Complex if (test1(arg1)) { // type: Complex if (arguments.length === 2) { return signature1(arg0, arg1); // signature: Complex, Complex } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test0(arg1)) { // type: number (convert to Complex) if (arguments.length === 2) { return signature1(arg0, convert0(arg1)); // signature: Complex, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: BigNumber (convert to Complex) if (arguments.length === 2) { return signature1(arg0, convert6(arg1)); // signature: Complex, BigNumber } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: Fraction (convert to Complex) if (arguments.length === 2) { return signature1(arg0, convert7(arg1)); // signature: Complex, Fraction } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test4(arg1)) { // type: string (convert to Complex) if (arguments.length === 2) { return signature1(arg0, convert8(arg1)); // signature: Complex, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } } if (test2(arg0)) { // type: BigNumber if (test1(arg1)) { // type: Complex if (arguments.length === 2) { return signature1(convert6(arg0), arg1); // signature: BigNumber, Complex } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature2(arg0, arg1); // si ...
...
/**
* Logical `or`. Test if at least one value is defined with a nonzero/nonempty value.
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.or(x, y)
*
* Examples:
*
* math.or(2, 4); // returns true
*
* a = [2, 5, 0];
* b = [0, 22, 0];
...
function parse(expr, options) { if (arguments.length != 1 && arguments.length != 2) { throw new ArgumentsError('parse', arguments.length, 1, 2); } // pass extra nodes extra_nodes = (options && options.nodes) ? options.nodes : {}; if (typeof expr === 'string') { // parse a single expression expression = expr; return parseStart(); } else if (Array.isArray(expr) || expr instanceof type.Matrix) { // parse an array or matrix with expressions return deepMap(expr, function (elem) { if (typeof elem !== 'string') throw new TypeError('String expected'); expression = elem; return parseStart(); }); } else { // oops throw new TypeError('String or matrix expected'); } }
...
if (!expr) {
break;
}
switch (mode) {
case 'eval':
// evaluate expression
try {
var node = math.parse(expr);
var res = node.eval(scope);
if (res && res.isResultSet) {
// we can have 0 or 1 results in the ResultSet, as the CLI
// does not allow multiple expressions separated by a return
res = res.entries[0];
node = node.blocks
...
function parser() { "use strict"; var name = 'parser'; if (arguments.length === 0) { return signature0(); // signature: } if (arguments.length > 0) { throw createError(name, arguments.length, 0, arguments[0]); } }
...
* parser.remove(name); // clear a variable from the
* // parsers scope
* parser.clear(); // clear the parsers scope
*
* Example usage:
* var parser = new Parser();
* // Note: there is a convenience method which can be used instead:
* // var parser = new math.parser();
*
* // evaluate expressions
* parser.eval('sqrt(3^2 + 4^2)'); // 5
* parser.eval('sqrt(-4)'); // 2i
* parser.eval('2 inch in cm'); // 5.08 cm
* parser.eval('cos(45 deg)'); // 0.7071067811865476
*
...
function partitionSelect(arg0, arg1, arg2) { "use strict"; var name = 'partitionSelect'; if (test0(arg0)) { // type: Array if (test1(arg1)) { // type: number if (arguments.length === 2) { return signature0(arg0, arg1); // signature: Array, number } if (test2(arg2)) { // type: string if (arguments.length === 3) { return signature1(arg0, arg1, arg2); // signature: Array, number, string } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } if (test3(arg2)) { // type: function if (arguments.length === 3) { return signature2(arg0, arg1, arg2); // signature: Array, number, function } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } if (test1(arg2)) { // type: number (convert to string) if (arguments.length === 3) { return signature1(arg0, arg1, convert0(arg2)); // signature: Array, number, number } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } if (test4(arg2)) { // type: boolean (convert to string) if (arguments.length === 3) { return signature1(arg0, arg1, convert1(arg2)); // signature: Array, number, boolean } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } if (test5(arg2)) { // type: null (convert to string) if (arguments.length === 3) { return signature1(arg0, arg1, convert2(arg2)); // signature: Array, number, null } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } throw createError(name, arguments.length, 2, arguments[2], 'string,function'); } if (test2(arg1)) { // type: string (convert to number) if (arguments.length === 2) { return signature0(arg0, convert3(arg1)); // signature: Array, string } if (test2(arg2)) { // type: string if (arguments.length === 3) { return signature1(arg0, convert3(arg1), arg2); // signature: Array, string, string } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } if (test3(arg2)) { // type: function if (arguments.length === 3) { return signature2(arg0, convert3(arg1), arg2); // signature: Array, string, function } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } if (test1(arg2)) { // type: number (convert to string) if (arguments.length === 3) { return signature1(arg0, convert3(arg1), convert0(arg2)); // signature: Array, string, number } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } if (test4(arg2)) { // type: boolean (convert to string) if (arguments.length === 3) { return signature1(arg0, convert3(arg1), convert1(arg2)); // signature: Array, string, boolean } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } if (test5(arg2)) { // type: null (convert to string) if (arguments.length === 3) { return signature1(arg0, convert3(arg1), convert2(arg2)); // signature: Array, string, null } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } throw createError(name, arguments.length, 2, arguments[2], 'string,function'); } if (test4(arg1)) { // type: boolean (convert to number) if (arguments.length === 2) { return signature0(arg0, convert4(arg1)); // signature: Array, boolean } if (test2(arg2)) { // type: string if (arguments.length === 3) { ...
...
/**
* Partition-based selection of an array or 1D matrix.
* Will find the kth smallest value, and mutates the input array.
* Uses Quickselect.
*
* Syntax:
*
* math.partitionSelect(x, k)
* math.partitionSelect(x, k, compare)
*
* Examples:
*
* math.partitionSelect([5, 10, 1], 2); // returns 10
* math.partitionSelect(['C', 'B', 'A', 'D'], 1); // returns 'B'
*
...
function permutations(arg0, arg1) { "use strict"; var name = 'permutations'; if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature0(arg0); // signature: number } if (test0(arg1)) { // type: number if (arguments.length === 2) { return signature1(arg0, arg1); // signature: number, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test1(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature2(convert0(arg0), arg1); // signature: number, BigNumber } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: Fraction (convert to BigNumber) if (arguments.length === 2) { return signature2(convert0(arg0), convert1(arg1)); // signature: number, Fraction } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: string (convert to number) if (arguments.length === 2) { return signature1(arg0, convert2(arg1)); // signature: number, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test4(arg1)) { // type: boolean (convert to number) if (arguments.length === 2) { return signature1(arg0, convert3(arg1)); // signature: number, boolean } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test5(arg1)) { // type: null (convert to number) if (arguments.length === 2) { return signature1(arg0, convert4(arg1)); // signature: number, null } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'number,BigNumber'); } if (test1(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature0(arg0); // signature: BigNumber } if (test1(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature2(arg0, arg1); // signature: BigNumber, BigNumber } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test0(arg1)) { // type: number (convert to BigNumber) if (arguments.length === 2) { return signature2(arg0, convert0(arg1)); // signature: BigNumber, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: Fraction (convert to BigNumber) if (arguments.length === 2) { return signature2(arg0, convert1(arg1)); // signature: BigNumber, Fraction } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: string (convert to BigNumber) if (arguments.length === 2) { return signature2(arg0, convert5(arg1)); // signature: BigNumber, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test4(arg1)) { // type: boolean (convert to BigNumber) if (arguments.length === 2) { return signature2(arg0, convert6(arg1)); // signature: BigNumber, boolean } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test5(arg1)) { // type: null (convert to BigNumber) if (arguments.length === 2) { return signature2(arg0, convert7(arg1)); // signature: BigNumber, null } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'BigNumber'); } if (test2(arg0)) { // type: Fracti ...
...
* from a set of `n` elements.
*
* Permutations only takes integer arguments.
* The following condition must be enforced: k <= n.
*
* Syntax:
*
* math.permutations(n)
* math.permutations(n, k)
*
* Examples:
*
* math.permutations(5); // 120
* math.permutations(5, 3); // 60
*
...
function pow(arg0, arg1) { "use strict"; var name = 'pow'; if (test0(arg0)) { // type: number if (test0(arg1)) { // type: number if (arguments.length === 2) { return signature0(arg0, arg1); // signature: number, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test1(arg1)) { // type: Complex if (arguments.length === 2) { return signature1(convert0(arg0), arg1); // signature: number, Complex } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature2(convert1(arg0), arg1); // signature: number, BigNumber } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: Fraction if (arguments.length === 2) { return signature3(convert2(arg0), arg1); // signature: number, Fraction } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test4(arg1)) { // type: string (convert to number) if (arguments.length === 2) { return signature0(arg0, convert3(arg1)); // signature: number, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test5(arg1)) { // type: boolean (convert to number) if (arguments.length === 2) { return signature0(arg0, convert4(arg1)); // signature: number, boolean } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test6(arg1)) { // type: null (convert to number) if (arguments.length === 2) { return signature0(arg0, convert5(arg1)); // signature: number, null } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'number,Complex,BigNumber,Fraction'); } if (test1(arg0)) { // type: Complex if (test1(arg1)) { // type: Complex if (arguments.length === 2) { return signature1(arg0, arg1); // signature: Complex, Complex } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test0(arg1)) { // type: number (convert to Complex) if (arguments.length === 2) { return signature1(arg0, convert0(arg1)); // signature: Complex, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: BigNumber (convert to Complex) if (arguments.length === 2) { return signature1(arg0, convert6(arg1)); // signature: Complex, BigNumber } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: Fraction (convert to Complex) if (arguments.length === 2) { return signature1(arg0, convert7(arg1)); // signature: Complex, Fraction } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test4(arg1)) { // type: string (convert to Complex) if (arguments.length === 2) { return signature1(arg0, convert8(arg1)); // signature: Complex, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'Complex'); } if (test2(arg0)) { // type: BigNumber if (test1(arg1)) { // type: Complex if (arguments.length === 2) { return signature1(convert6(arg0), arg1); // signature: BigNumber, Complex } if (arguments.length > 2) { throw createError(name, arguments.length, 2, argume ...
...
var math = require('mathjs');
// functions and constants
math.round(math.e, 3); // 2.718
math.atan2(3, -3) / math.pi; // 0.75
math.log(1000, 10); // 3
math.sqrt(-4); // 2i
math.pow([[-1, 2], [3, 1]], 2); // [[7, 0], [0, 7]]
math.derivative('x^2 + x', 'x'); // 2 * x + 1
// expressions
math.eval('12 / (2.3 + 0.7)'); // 4
math.eval('5.08 cm to inch'); // 2 inch
math.eval('sin(45 deg) ^ 2'); // 0.5
math.eval('9 / 3 + 2i'); // 3 + 2i
...
function print(arg0, arg1, arg2) { "use strict"; var name = 'print'; if (test0(arg0)) { // type: string if (test1(arg1)) { // type: Object if (arguments.length === 2) { return signature0(arg0, arg1); // signature: string, Object } if (test2(arg2)) { // type: number if (arguments.length === 3) { return signature0(arg0, arg1, arg2); // signature: string, Object, number } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } if (test0(arg2)) { // type: string (convert to number) if (arguments.length === 3) { return signature0(arg0, arg1, convert0(arg2)); // signature: string, Object, string } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } if (test3(arg2)) { // type: boolean (convert to number) if (arguments.length === 3) { return signature0(arg0, arg1, convert1(arg2)); // signature: string, Object, boolean } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } if (test4(arg2)) { // type: null (convert to number) if (arguments.length === 3) { return signature0(arg0, arg1, convert2(arg2)); // signature: string, Object, null } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } if (test1(arg2)) { // type: Object if (arguments.length === 3) { return signature0(arg0, arg1, arg2); // signature: string, Object, Object } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } throw createError(name, arguments.length, 2, arguments[2], 'number,Object'); } throw createError(name, arguments.length, 1, arguments[1], 'Object'); } if (test2(arg0)) { // type: number (convert to string) if (test1(arg1)) { // type: Object if (arguments.length === 2) { return signature0(convert3(arg0), arg1); // signature: number, Object } if (test2(arg2)) { // type: number if (arguments.length === 3) { return signature0(convert3(arg0), arg1, arg2); // signature: number, Object, number } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } if (test0(arg2)) { // type: string (convert to number) if (arguments.length === 3) { return signature0(convert3(arg0), arg1, convert0(arg2)); // signature: number, Object, string } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } if (test3(arg2)) { // type: boolean (convert to number) if (arguments.length === 3) { return signature0(convert3(arg0), arg1, convert1(arg2)); // signature: number, Object, boolean } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } if (test4(arg2)) { // type: null (convert to number) if (arguments.length === 3) { return signature0(convert3(arg0), arg1, convert2(arg2)); // signature: number, Object, null } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } if (test1(arg2)) { // type: Object if (arguments.length === 3) { return signature0(convert3(arg0), arg1, arg2); // signature: number, Object, Object } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } throw createError(name, arguments.length, 2, arguments[2], 'number,Object'); } throw createError(name, arguments.length, 1, arguments[1], 'Object'); } if (test3(arg0)) { // type: boolean (convert to string) if (test1(arg1)) { // typ ...
...
function factory (type, config, load, typed) {
/**
* Interpolate values into a string template.
*
* Syntax:
*
* math.print(template, values)
* math.print(template, values, precision)
* math.print(template, values, options)
*
* Example usage:
*
* // the following outputs: 'Lucy is 5 years old'
* math.print('Lucy is $age years old', {age: 5});
...
function prod(arg0, arg1) { "use strict"; var name = 'prod'; if (test0(arg0)) { // type: Array if (arguments.length === 1) { return signature0(arg0); // signature: Array } if (test1(arg1)) { // type: number if (arguments.length === 2) { return signature1(arg0, arg1); // signature: Array, number } } if (test2(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature1(arg0, arg1); // signature: Array, BigNumber } } if (test3(arg1)) { // type: Fraction (convert to BigNumber) if (arguments.length === 2) { return signature1(arg0, convert0(arg1)); // signature: Array, Fraction } } if (test4(arg1)) { // type: string (convert to number) if (arguments.length === 2) { return signature1(arg0, convert1(arg1)); // signature: Array, string } } if (test5(arg1)) { // type: boolean (convert to number) if (arguments.length === 2) { return signature1(arg0, convert2(arg1)); // signature: Array, boolean } } if (test6(arg1)) { // type: null (convert to number) if (arguments.length === 2) { return signature1(arg0, convert3(arg1)); // signature: Array, null } } } if (test7(arg0)) { // type: Matrix if (arguments.length === 1) { return signature0(arg0); // signature: Matrix } if (test1(arg1)) { // type: number if (arguments.length === 2) { return signature1(arg0, arg1); // signature: Matrix, number } } if (test2(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature1(arg0, arg1); // signature: Matrix, BigNumber } } if (test3(arg1)) { // type: Fraction (convert to BigNumber) if (arguments.length === 2) { return signature1(arg0, convert0(arg1)); // signature: Matrix, Fraction } } if (test4(arg1)) { // type: string (convert to number) if (arguments.length === 2) { return signature1(arg0, convert1(arg1)); // signature: Matrix, string } } if (test5(arg1)) { // type: boolean (convert to number) if (arguments.length === 2) { return signature1(arg0, convert2(arg1)); // signature: Matrix, boolean } } if (test6(arg1)) { // type: null (convert to number) if (arguments.length === 2) { return signature1(arg0, convert3(arg1)); // signature: Matrix, null } } } if (arguments.length > 0) { var varArgs = []; for (var i = 0; i < arguments.length; i++) { varArgs.push(arguments[i]); } return signature2(varArgs); // signature: ...any } throw createError(name, arguments.length, 0, arguments[0], 'Array,Matrix,any'); }
...
/**
* Compute the product of a matrix or a list with values.
* In case of a (multi dimensional) array or matrix, the sum of all
* elements will be calculated.
*
* Syntax:
*
* math.prod(a, b, c, ...)
* math.prod(A)
*
* Examples:
*
* math.multiply(2, 3); // returns 6
* math.prod(2, 3); // returns 6
* math.prod(2, 3, 4); // returns 24
...
function qr(arg0) { "use strict"; var name = 'qr'; if (test0(arg0)) { // type: Array if (arguments.length === 1) { return signature0(arg0); // signature: Array } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: DenseMatrix if (arguments.length === 1) { return signature1(arg0); // signature: DenseMatrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test2(arg0)) { // type: SparseMatrix if (arguments.length === 1) { return signature2(arg0); // signature: SparseMatrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test3(arg0)) { // type: Matrix (convert to Array) if (arguments.length === 1) { return signature0(convert0(arg0)); // signature: Matrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'Array,DenseMatrix,SparseMatrix'); }
n/a
function quantileSeq(data, probOrN, sorted) { var probArr, dataArr, one; if (arguments.length < 2 || arguments.length > 3) { throw new SyntaxError('Function quantileSeq requires two or three parameters'); } if (isCollection(data)) { sorted = sorted || false; if (typeof sorted === 'boolean') { dataArr = data.valueOf(); if (isNumber(probOrN)) { if (probOrN < 0) { throw new Error('N/prob must be non-negative'); } if (probOrN <= 1) { // quantileSeq([a, b, c, d, ...], prob[,sorted]) return _quantileSeq(dataArr, probOrN, sorted); } if (probOrN > 1) { // quantileSeq([a, b, c, d, ...], N[,sorted]) if (!isInteger(probOrN)) { throw new Error('N must be a positive integer'); } var nPlusOne = probOrN + 1; probArr = new Array(probOrN); for (var i = 0; i < probOrN;) { probArr[i] = _quantileSeq(dataArr, (++i) / nPlusOne, sorted); } return probArr; } } if (probOrN && probOrN.isBigNumber) { if (probOrN.isNegative()) { throw new Error('N/prob must be non-negative'); } one = new probOrN.constructor(1); if (probOrN.lte(one)) { // quantileSeq([a, b, c, d, ...], prob[,sorted]) return _quantileSeq(dataArr, probOrN, sorted); } if (probOrN.gt(one)) { // quantileSeq([a, b, c, d, ...], N[,sorted]) if (!probOrN.isInteger()) { throw new Error('N must be a positive integer'); } // largest possible Array length is 2^32-1; // 2^32 < 10^15, thus safe conversion guaranteed var intN = probOrN.toNumber(); if (intN > 4294967295) { throw new Error('N must be less than or equal to 2^32-1, as that is the maximum length of an Array'); } var nPlusOne = new type.BigNumber(intN + 1); probArr = new Array(intN); for (var i = 0; i < intN;) { probArr[i] = _quantileSeq(dataArr, new type.BigNumber(++i).div(nPlusOne), sorted); } return probArr; } } if (Array.isArray(probOrN)) { // quantileSeq([a, b, c, d, ...], [prob1, prob2, ...][,sorted]) probArr = new Array(probOrN.length); for (var i = 0; i < probArr.length; ++i) { var currProb = probOrN[i]; if (isNumber(currProb)) { if (currProb < 0 || currProb > 1) { throw new Error('Probability must be between 0 and 1, inclusive'); } } else if (currProb && currProb.isBigNumber) { one = new currProb.constructor(1); if (currProb.isNegative() || currProb.gt(one)) { throw new Error('Probability must be between 0 and 1, inclusive'); } } else { throw new TypeError('Unexpected type of argument in function quantileSeq'); // FIXME: becomes redundant when converted to typed-function } probArr[i] = _quantileSeq(dataArr, currProb, sorted); } return probArr; } throw new TypeError('Unexpected type of argument in function quantileSeq'); // FIXME: becomes redundant when converted to typed-function } throw new TypeError('Unexpected type of argument in function quantileSeq'); // FIXME: becomes redundant when converted to typed -function } throw new TypeError('Unexpected type of argument in function quantileSeq'); // FIXME: becomes redundant when converted to typed -function }
...
* Supported types of probability are: Number, BigNumber
*
* In case of a (multi dimensional) array or matrix, the prob order quantile
* of all elements will be calculated.
*
* Syntax:
*
* math.quantileSeq(A, prob[, sorted])
* math.quantileSeq(A, [prob1, prob2, ...][, sorted])
* math.quantileSeq(A, N[, sorted])
*
* Examples:
*
* math.quantileSeq([3, -1, 5, 7], 0.5); // returns 4
* math.quantileSeq([3, -1, 5, 7], [1/3, 2/3]); // returns [3, 5]
...
function range(arg0) { "use strict"; var name = 'range'; if (arguments.length > 0) { var varArgs = []; for (var i = 0; i < arguments.length; i++) { varArgs.push(arguments[i]); } return signature0(varArgs); // signature: ...any } throw createError(name, arguments.length, 0, arguments[0], 'any'); }
...
* the name of the argument, and the value is `true`.
* The object may not be mutated, but must be
* extended instead.
* @return {string} js
* @private
*/
RangeNode.prototype._compile = function (defs, args) {
return 'math.range(' +
this.start._compile(defs, args) + ', ' +
this.end._compile(defs, args) +
(this.step ? (', ' + this.step._compile(defs, args)) : '') +
')';
};
/**
...
function re(arg0) { "use strict"; var name = 're'; if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature0(arg0); // signature: number } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: Complex if (arguments.length === 1) { return signature1(arg0); // signature: Complex } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test2(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature2(arg0); // signature: BigNumber } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test3(arg0)) { // type: Array if (arguments.length === 1) { return signature3(arg0); // signature: Array } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test4(arg0)) { // type: Matrix if (arguments.length === 1) { return signature3(arg0); // signature: Matrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test5(arg0)) { // type: Fraction (convert to BigNumber) if (arguments.length === 1) { return signature2(convert0(arg0)); // signature: Fraction } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test6(arg0)) { // type: string (convert to number) if (arguments.length === 1) { return signature0(convert1(arg0)); // signature: string } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test7(arg0)) { // type: boolean (convert to number) if (arguments.length === 1) { return signature0(convert2(arg0)); // signature: boolean } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test8(arg0)) { // type: null (convert to number) if (arguments.length === 1) { return signature0(convert3(arg0)); // signature: null } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'number,Complex,BigNumber,Array,Matrix'); }
...
* Syntax:
*
* math.im(x)
*
* Examples:
*
* var a = math.complex(2, 3);
* math.re(a); // returns number 2
* math.im(a); // returns number 3
*
* math.re(math.complex('-5.2i')); // returns number -5.2
* math.re(math.complex(2.4)); // returns number 0
*
* See also:
*
...
function reshape(arg0, arg1) { "use strict"; var name = 'reshape'; if (test0(arg0)) { // type: Array if (test0(arg1)) { // type: Array if (arguments.length === 2) { return signature0(arg0, arg1); // signature: Array, Array } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test1(arg1)) { // type: Matrix (convert to Array) if (arguments.length === 2) { return signature0(arg0, convert0(arg1)); // signature: Array, Matrix } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'Array'); } if (test1(arg0)) { // type: Matrix if (test0(arg1)) { // type: Array if (arguments.length === 2) { return signature1(arg0, arg1); // signature: Matrix, Array } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test1(arg1)) { // type: Matrix (convert to Array) if (arguments.length === 2) { return signature1(arg0, convert0(arg1)); // signature: Matrix, Matrix } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'Array'); } throw createError(name, arguments.length, 0, arguments[0], 'Array,Matrix'); }
...
var matrix = load(require('../../type/matrix/function/matrix'));
/**
* Reshape a multi dimensional array to fit the specified dimensions
*
* Syntax:
*
* math.reshape(x, sizes)
*
* Examples:
*
* math.reshape([1, 2, 3, 4, 5, 6], [2, 3]);
* // returns Array [[1, 2, 3], [4, 5, 6]]
*
* math.reshape([[1, 2], [3, 4]], [1, 4]);
...
function resize(x, size, defaultValue) { if (arguments.length != 2 && arguments.length != 3) { throw new ArgumentsError('resize', arguments.length, 2, 3); } if (size && size.isMatrix === true) { size = size.valueOf(); // get Array } if (size.length && size[0] && size[0].isBigNumber === true) { // convert bignumbers to numbers size = size.map(function (value) { return (value && value.isBigNumber === true) ? value.toNumber() : value; }); } // check x is a Matrix if (x && x.isMatrix === true) { // use optimized matrix implementation, return copy return x.resize(size, defaultValue, true); } if (typeof x === 'string') { // resize string return _resizeString(x, size, defaultValue); } // check result should be a matrix var asMatrix = Array.isArray(x) ? false : (config.matrix !== 'Array'); if (size.length == 0) { // output a scalar while (Array.isArray(x)) { x = x[0]; } return clone(x); } else { // output an array/matrix if (!Array.isArray(x)) { x = [x]; } x = clone(x); var res = array.resize(x, size, defaultValue); return asMatrix ? matrix(res) : res; } }
...
// get matrix storage constructor
var F = type.Matrix.storage(format);
// create diagonal matrix (use optimized implementation for storage format)
return F.diagonal(size, one, 0, defaultValue);
}
// create and resize array
var res = array.resize([], size, defaultValue);
// fill in ones on the diagonal
var minimum = rows < cols ? rows : cols;
// fill diagonal
for (var d = 0; d < minimum; d++) {
res[d][d] = one;
}
return res;
...
function reviver(key, value) { var constructor = type[value && value.mathjs]; if (constructor && typeof constructor.fromJSON === 'function') { return constructor.fromJSON(value); } return value; }
n/a
function rightArithShift(arg0, arg1) { "use strict"; var name = 'rightArithShift'; if (test0(arg0)) { // type: number if (test0(arg1)) { // type: number if (arguments.length === 2) { return signature0(arg0, arg1); // signature: number, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test1(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature1(convert0(arg0), arg1); // signature: number, BigNumber } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: Array if (arguments.length === 2) { return signature2(arg0, arg1); // signature: number, Array } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: Matrix if (arguments.length === 2) { return signature3(arg0, arg1); // signature: number, Matrix } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test4(arg1)) { // type: Fraction (convert to BigNumber) if (arguments.length === 2) { return signature1(convert0(arg0), convert1(arg1)); // signature: number, Fraction } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test5(arg1)) { // type: string (convert to number) if (arguments.length === 2) { return signature0(arg0, convert2(arg1)); // signature: number, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test6(arg1)) { // type: boolean (convert to number) if (arguments.length === 2) { return signature0(arg0, convert3(arg1)); // signature: number, boolean } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test7(arg1)) { // type: null (convert to number) if (arguments.length === 2) { return signature0(arg0, convert4(arg1)); // signature: number, null } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'number,BigNumber,Array,Matrix'); } if (test1(arg0)) { // type: BigNumber if (test1(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature1(arg0, arg1); // signature: BigNumber, BigNumber } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: Array if (arguments.length === 2) { return signature2(arg0, arg1); // signature: BigNumber, Array } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: Matrix if (arguments.length === 2) { return signature3(arg0, arg1); // signature: BigNumber, Matrix } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test0(arg1)) { // type: number (convert to BigNumber) if (arguments.length === 2) { return signature1(arg0, convert0(arg1)); // signature: BigNumber, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test4(arg1)) { // type: Fraction (convert to BigNumber) if (arguments.length === 2) { return signature1(arg0, convert1(arg1)); // signature: BigNumber, Fraction } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test5(arg1)) { // type: string (convert to BigNumber) if (arguments.length === 2) { return signature ...
...
/**
* Bitwise right arithmetic shift of a value x by y number of bits, `x >> y`.
* For matrices, the function is evaluated element wise.
* For units, the function is evaluated on the best prefix base.
*
* Syntax:
*
* math.rightArithShift(x, y)
*
* Examples:
*
* math.rightArithShift(4, 2); // returns number 1
*
* math.rightArithShift([16, -32, 64], 4); // returns Array [1, -2, 3]
*
...
function rightLogShift(arg0, arg1) { "use strict"; var name = 'rightLogShift'; if (test0(arg0)) { // type: number if (test0(arg1)) { // type: number if (arguments.length === 2) { return signature0(arg0, arg1); // signature: number, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test1(arg1)) { // type: Array if (arguments.length === 2) { return signature1(arg0, arg1); // signature: number, Array } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: Matrix if (arguments.length === 2) { return signature2(arg0, arg1); // signature: number, Matrix } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: string (convert to number) if (arguments.length === 2) { return signature0(arg0, convert0(arg1)); // signature: number, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test4(arg1)) { // type: boolean (convert to number) if (arguments.length === 2) { return signature0(arg0, convert1(arg1)); // signature: number, boolean } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test5(arg1)) { // type: null (convert to number) if (arguments.length === 2) { return signature0(arg0, convert2(arg1)); // signature: number, null } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'number,Array,Matrix'); } if (test6(arg0)) { // type: BigNumber if (test1(arg1)) { // type: Array if (arguments.length === 2) { return signature1(arg0, arg1); // signature: BigNumber, Array } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: Matrix if (arguments.length === 2) { return signature2(arg0, arg1); // signature: BigNumber, Matrix } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'Array,Matrix'); } if (test1(arg0)) { // type: Array if (test0(arg1)) { // type: number if (arguments.length === 2) { return signature3(arg0, arg1); // signature: Array, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test6(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature3(arg0, arg1); // signature: Array, BigNumber } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test1(arg1)) { // type: Array if (arguments.length === 2) { return signature4(arg0, arg1); // signature: Array, Array } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: Matrix if (arguments.length === 2) { return signature5(arg0, arg1); // signature: Array, Matrix } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test7(arg1)) { // type: Fraction (convert to BigNumber) if (arguments.length === 2) { return signature3(arg0, convert3(arg1)); // signature: Array, Fraction } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: string (convert to number) if (arguments.length === 2) { return signature3(arg0, c ...
...
/**
* Bitwise right logical shift of value x by y number of bits, `x >>> y`.
* For matrices, the function is evaluated element wise.
* For units, the function is evaluated on the best prefix base.
*
* Syntax:
*
* math.rightLogShift(x, y)
*
* Examples:
*
* math.rightLogShift(4, 2); // returns number 1
*
* math.rightLogShift([16, -32, 64], 4); // returns Array [1, 2, 3]
*
...
function round(arg0, arg1) { "use strict"; var name = 'round'; if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature0(arg0); // signature: number } if (test0(arg1)) { // type: number if (arguments.length === 2) { return signature1(arg0, arg1); // signature: number, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test1(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature2(arg0, arg1); // signature: number, BigNumber } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: Array if (arguments.length === 2) { return signature3(arg0, arg1); // signature: number, Array } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: Matrix if (arguments.length === 2) { return signature4(arg0, arg1); // signature: number, Matrix } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test4(arg1)) { // type: Fraction (convert to BigNumber) if (arguments.length === 2) { return signature2(arg0, convert0(arg1)); // signature: number, Fraction } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test5(arg1)) { // type: string (convert to number) if (arguments.length === 2) { return signature1(arg0, convert1(arg1)); // signature: number, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test6(arg1)) { // type: boolean (convert to number) if (arguments.length === 2) { return signature1(arg0, convert2(arg1)); // signature: number, boolean } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test7(arg1)) { // type: null (convert to number) if (arguments.length === 2) { return signature1(arg0, convert3(arg1)); // signature: number, null } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'number,BigNumber,Array,Matrix'); } if (test8(arg0)) { // type: Complex if (arguments.length === 1) { return signature5(arg0); // signature: Complex } if (test0(arg1)) { // type: number if (arguments.length === 2) { return signature6(arg0, arg1); // signature: Complex, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test1(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature7(arg0, arg1); // signature: Complex, BigNumber } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: Array if (arguments.length === 2) { return signature3(arg0, arg1); // signature: Complex, Array } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: Matrix if (arguments.length === 2) { return signature4(arg0, arg1); // signature: Complex, Matrix } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test4(arg1)) { // type: Fraction (convert to BigNumber) if (arguments.length === 2) { return signature7(arg0, convert0(arg1)); // signature: Complex, Fraction } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test5(arg1)) { ...
...
[chained operations](http://mathjs.org/docs/chained_operations.html).
```js
// load math.js
var math = require('mathjs');
// functions and constants
math.round(math.e, 3); // 2.718
math.atan2(3, -3) / math.pi; // 0.75
math.log(1000, 10); // 3
math.sqrt(-4); // 2i
math.pow([[-1, 2], [3, 1]], 2); // [[7, 0], [0, 7]]
math.derivative('x^2 + x', 'x'); // 2 * x + 1
// expressions
...
function sec(arg0) { "use strict"; var name = 'sec'; if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature0(arg0); // signature: number } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: Complex if (arguments.length === 1) { return signature1(arg0); // signature: Complex } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test2(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature2(arg0); // signature: BigNumber } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test3(arg0)) { // type: Unit if (arguments.length === 1) { return signature3(arg0); // signature: Unit } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test4(arg0)) { // type: Array if (arguments.length === 1) { return signature4(arg0); // signature: Array } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test5(arg0)) { // type: Matrix if (arguments.length === 1) { return signature4(arg0); // signature: Matrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test6(arg0)) { // type: Fraction (convert to BigNumber) if (arguments.length === 1) { return signature2(convert0(arg0)); // signature: Fraction } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test7(arg0)) { // type: string (convert to number) if (arguments.length === 1) { return signature0(convert1(arg0)); // signature: string } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test8(arg0)) { // type: boolean (convert to number) if (arguments.length === 1) { return signature0(convert2(arg0)); // signature: boolean } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test9(arg0)) { // type: null (convert to number) if (arguments.length === 1) { return signature0(convert3(arg0)); // signature: null } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'number,Complex,BigNumber,Unit,Array,Matrix'); }
...
* Syntax:
*
* math.asec(x)
*
* Examples:
*
* math.asec(0.5); // returns 1.0471975511965979
* math.asec(math.sec(1.5)); // returns 1.5
*
* math.asec(2); // returns 0 + 1.3169578969248166 i
*
* See also:
*
* acos, acot, acsc
*
...
function sech(arg0) { "use strict"; var name = 'sech'; if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature0(arg0); // signature: number } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: Complex if (arguments.length === 1) { return signature1(arg0); // signature: Complex } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test2(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature2(arg0); // signature: BigNumber } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test3(arg0)) { // type: Unit if (arguments.length === 1) { return signature3(arg0); // signature: Unit } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test4(arg0)) { // type: Array if (arguments.length === 1) { return signature4(arg0); // signature: Array } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test5(arg0)) { // type: Matrix if (arguments.length === 1) { return signature4(arg0); // signature: Matrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test6(arg0)) { // type: Fraction (convert to BigNumber) if (arguments.length === 1) { return signature2(convert0(arg0)); // signature: Fraction } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test7(arg0)) { // type: string (convert to number) if (arguments.length === 1) { return signature0(convert1(arg0)); // signature: string } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test8(arg0)) { // type: boolean (convert to number) if (arguments.length === 1) { return signature0(convert2(arg0)); // signature: boolean } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test9(arg0)) { // type: null (convert to number) if (arguments.length === 1) { return signature0(convert3(arg0)); // signature: null } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'number,Complex,BigNumber,Unit,Array,Matrix'); }
...
* Calculate the hyperbolic secant of a value,
* defined as `sech(x) = 1 / cosh(x)`.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.sech(x)
*
* Examples:
*
* // sech(x) = 1/ cosh(x)
* math.sech(0.5); // returns 0.886818883970074
* 1 / math.cosh(0.5); // returns 0.886818883970074
*
...
function sign(arg0) { "use strict"; var name = 'sign'; if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature0(arg0); // signature: number } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: Complex if (arguments.length === 1) { return signature1(arg0); // signature: Complex } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test2(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature2(arg0); // signature: BigNumber } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test3(arg0)) { // type: Fraction if (arguments.length === 1) { return signature3(arg0); // signature: Fraction } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test4(arg0)) { // type: Unit if (arguments.length === 1) { return signature4(arg0); // signature: Unit } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test5(arg0)) { // type: Array if (arguments.length === 1) { return signature5(arg0); // signature: Array } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test6(arg0)) { // type: Matrix if (arguments.length === 1) { return signature5(arg0); // signature: Matrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test7(arg0)) { // type: string (convert to number) if (arguments.length === 1) { return signature0(convert0(arg0)); // signature: string } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test8(arg0)) { // type: boolean (convert to number) if (arguments.length === 1) { return signature0(convert1(arg0)); // signature: boolean } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test9(arg0)) { // type: null (convert to number) if (arguments.length === 1) { return signature0(convert2(arg0)); // signature: null } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'number,Complex,BigNumber,Fraction,Unit,Array,Matrix'); }
...
* - -1 when x < 0
* - 0 when x == 0
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.sign(x)
*
* Examples:
*
* math.sign(3.5); // returns 1
* math.sign(-4.2); // returns -1
* math.sign(0); // returns 0
*
...
function simplify(arg0, arg1) { "use strict"; var name = 'simplify'; if (test0(arg0)) { // type: string if (arguments.length === 1) { return signature0(arg0); // signature: string } if (test1(arg1)) { // type: Array if (arguments.length === 2) { return signature1(arg0, arg1); // signature: string, Array } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: Matrix (convert to Array) if (arguments.length === 2) { return signature1(arg0, convert0(arg1)); // signature: string, Matrix } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'Array'); } if (test3(arg0)) { // type: Node if (arguments.length === 1) { return signature2(arg0); // signature: Node } if (test1(arg1)) { // type: Array if (arguments.length === 2) { return signature3(arg0, arg1); // signature: Node, Array } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: Matrix (convert to Array) if (arguments.length === 2) { return signature3(arg0, convert0(arg1)); // signature: Node, Matrix } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'Array'); } if (test4(arg0)) { // type: number (convert to string) if (arguments.length === 1) { return signature0(convert1(arg0)); // signature: number } if (test1(arg1)) { // type: Array if (arguments.length === 2) { return signature1(convert1(arg0), arg1); // signature: number, Array } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: Matrix (convert to Array) if (arguments.length === 2) { return signature1(convert1(arg0), convert0(arg1)); // signature: number, Matrix } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'Array'); } if (test5(arg0)) { // type: boolean (convert to string) if (arguments.length === 1) { return signature0(convert2(arg0)); // signature: boolean } if (test1(arg1)) { // type: Array if (arguments.length === 2) { return signature1(convert2(arg0), arg1); // signature: boolean, Array } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: Matrix (convert to Array) if (arguments.length === 2) { return signature1(convert2(arg0), convert0(arg1)); // signature: boolean, Matrix } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'Array'); } if (test6(arg0)) { // type: null (convert to string) if (arguments.length === 1) { return signature0(convert3(arg0)); // signature: null } if (test1(arg1)) { // type: Array if (arguments.length === 2) { return signature1(convert3(arg0), arg1); // signature: null, Array } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: Matrix (convert to Array) if (arguments.length === 2) { return signature1(convert3(arg0), convert0(arg1)); // signature: null, Matrix } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'Array'); } throw createError(name, arguments.length, 0, arg ...
...
* Syntax:
*
* simplify(expr)
* simplify(expr, rules)
*
* Examples:
*
* math.simplify('2 * 1 * x ^ (2 - 1)'); // Node {2 * x}
* var f = math.parse('2 * 1 * x ^ (2 - 1)');
* math.simplify(f); // Node {2 * x}
*
* See also:
*
* derivative, parse, eval
*
...
function sin(arg0) { "use strict"; var name = 'sin'; if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature0(arg0); // signature: number } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: Complex if (arguments.length === 1) { return signature1(arg0); // signature: Complex } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test2(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature2(arg0); // signature: BigNumber } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test3(arg0)) { // type: Unit if (arguments.length === 1) { return signature3(arg0); // signature: Unit } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test4(arg0)) { // type: Array if (arguments.length === 1) { return signature4(arg0); // signature: Array } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test5(arg0)) { // type: Matrix if (arguments.length === 1) { return signature4(arg0); // signature: Matrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test6(arg0)) { // type: Fraction (convert to BigNumber) if (arguments.length === 1) { return signature2(convert0(arg0)); // signature: Fraction } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test7(arg0)) { // type: string (convert to number) if (arguments.length === 1) { return signature0(convert1(arg0)); // signature: string } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test8(arg0)) { // type: boolean (convert to number) if (arguments.length === 1) { return signature0(convert2(arg0)); // signature: boolean } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test9(arg0)) { // type: null (convert to number) if (arguments.length === 1) { return signature0(convert3(arg0)); // signature: null } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'number,Complex,BigNumber,Unit,Array,Matrix'); }
...
res = 1; // 0! is per definition 1
}
return res;
}
if (n < 0.5) {
return Math.PI / (Math.sin(Math.PI * n) * gamma(1-n));
}
if (n >= 171.35) {
return Infinity; // will overflow
}
if (n > 85.0) { // Extended Stirling Approx
...
function sinh(arg0) { "use strict"; var name = 'sinh'; if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature0(arg0); // signature: number } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: Complex if (arguments.length === 1) { return signature1(arg0); // signature: Complex } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test2(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature2(arg0); // signature: BigNumber } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test3(arg0)) { // type: Unit if (arguments.length === 1) { return signature3(arg0); // signature: Unit } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test4(arg0)) { // type: Array if (arguments.length === 1) { return signature4(arg0); // signature: Array } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test5(arg0)) { // type: Matrix if (arguments.length === 1) { return signature4(arg0); // signature: Matrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test6(arg0)) { // type: Fraction (convert to BigNumber) if (arguments.length === 1) { return signature2(convert0(arg0)); // signature: Fraction } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test7(arg0)) { // type: string (convert to number) if (arguments.length === 1) { return signature0(convert1(arg0)); // signature: string } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test8(arg0)) { // type: boolean (convert to number) if (arguments.length === 1) { return signature0(convert2(arg0)); // signature: boolean } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test9(arg0)) { // type: null (convert to number) if (arguments.length === 1) { return signature0(convert3(arg0)); // signature: null } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'number,Complex,BigNumber,Unit,Array,Matrix'); }
...
*
* math.csch(x)
*
* Examples:
*
* // csch(x) = 1/ sinh(x)
* math.csch(0.5); // returns 1.9190347513349437
* 1 / math.sinh(0.5); // returns 1.9190347513349437
*
* See also:
*
* sinh, sech, coth
*
* @param {number | Complex | Unit | Array | Matrix} x Function input
* @return {number | Complex | Array | Matrix} Hyperbolic cosecant of x
...
function size(arg0) { "use strict"; var name = 'size'; if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature0(arg0); // signature: number } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: Complex if (arguments.length === 1) { return signature0(arg0); // signature: Complex } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test2(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature0(arg0); // signature: BigNumber } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test3(arg0)) { // type: Unit if (arguments.length === 1) { return signature0(arg0); // signature: Unit } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test4(arg0)) { // type: string if (arguments.length === 1) { return signature1(arg0); // signature: string } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test5(arg0)) { // type: Array if (arguments.length === 1) { return signature2(arg0); // signature: Array } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test6(arg0)) { // type: Matrix if (arguments.length === 1) { return signature3(arg0); // signature: Matrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test7(arg0)) { // type: boolean if (arguments.length === 1) { return signature0(arg0); // signature: boolean } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test8(arg0)) { // type: null if (arguments.length === 1) { return signature0(arg0); // signature: null } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test9(arg0)) { // type: Fraction (convert to BigNumber) if (arguments.length === 1) { return signature0(convert0(arg0)); // signature: Fraction } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'number,Complex,BigNumber,Unit,string,Array,Matrix,boolean,null'); }
...
};
if (!Array.isArray(array) || !Array.isArray(sizes)) {
throw new TypeError('Array expected');
}
if (sizes.length === 0) {
throw new DimensionError(0, product(exports.size(array)), '!=');
}
try {
newArray = _reshape(flatArray, sizes);
} catch (e) {
if (e instanceof DimensionError) {
throw new DimensionError(
...
function slu(arg0, arg1, arg2) { "use strict"; var name = 'slu'; if (test0(arg0)) { // type: SparseMatrix if (test1(arg1)) { // type: number if (test1(arg2)) { // type: number if (arguments.length === 3) { return signature0(arg0, arg1, arg2); // signature: SparseMatrix, number, number } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } if (test2(arg2)) { // type: string (convert to number) if (arguments.length === 3) { return signature0(arg0, arg1, convert0(arg2)); // signature: SparseMatrix, number, string } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } if (test3(arg2)) { // type: boolean (convert to number) if (arguments.length === 3) { return signature0(arg0, arg1, convert1(arg2)); // signature: SparseMatrix, number, boolean } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } if (test4(arg2)) { // type: null (convert to number) if (arguments.length === 3) { return signature0(arg0, arg1, convert2(arg2)); // signature: SparseMatrix, number, null } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } throw createError(name, arguments.length, 2, arguments[2], 'number'); } if (test2(arg1)) { // type: string (convert to number) if (test1(arg2)) { // type: number if (arguments.length === 3) { return signature0(arg0, convert0(arg1), arg2); // signature: SparseMatrix, string, number } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } if (test2(arg2)) { // type: string (convert to number) if (arguments.length === 3) { return signature0(arg0, convert0(arg1), convert0(arg2)); // signature: SparseMatrix, string, string } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } if (test3(arg2)) { // type: boolean (convert to number) if (arguments.length === 3) { return signature0(arg0, convert0(arg1), convert1(arg2)); // signature: SparseMatrix, string, boolean } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } if (test4(arg2)) { // type: null (convert to number) if (arguments.length === 3) { return signature0(arg0, convert0(arg1), convert2(arg2)); // signature: SparseMatrix, string, null } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } throw createError(name, arguments.length, 2, arguments[2], 'number'); } if (test3(arg1)) { // type: boolean (convert to number) if (test1(arg2)) { // type: number if (arguments.length === 3) { return signature0(arg0, convert1(arg1), arg2); // signature: SparseMatrix, boolean, number } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } if (test2(arg2)) { // type: string (convert to number) if (arguments.length === 3) { return signature0(arg0, convert1(arg1), convert0(arg2)); // signature: SparseMatrix, boolean, string } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } if (test3(arg2)) { // type: boolean (convert to number) if (arguments.length === 3) { return signature0(arg0, convert1(arg1), convert1(arg2)); // signature: SparseMatrix, boolean, boolean } if (arguments.length > 3) { throw createError(name, arguments.length, 3, arguments[3]); } } if (test4(ar ...
n/a
function smaller(arg0, arg1) { "use strict"; var name = 'smaller'; if (test0(arg0)) { // type: number if (test0(arg1)) { // type: number if (arguments.length === 2) { return signature0(arg0, arg1); // signature: number, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test1(arg1)) { // type: Complex if (arguments.length === 2) { return signature1(convert0(arg0), arg1); // signature: number, Complex } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature2(convert1(arg0), arg1); // signature: number, BigNumber } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: Fraction if (arguments.length === 2) { return signature3(convert2(arg0), arg1); // signature: number, Fraction } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test4(arg1)) { // type: string (convert to number) if (arguments.length === 2) { return signature0(arg0, convert3(arg1)); // signature: number, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test5(arg1)) { // type: boolean (convert to number) if (arguments.length === 2) { return signature0(arg0, convert4(arg1)); // signature: number, boolean } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test6(arg1)) { // type: null (convert to number) if (arguments.length === 2) { return signature0(arg0, convert5(arg1)); // signature: number, null } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } } if (test1(arg0)) { // type: Complex if (test1(arg1)) { // type: Complex if (arguments.length === 2) { return signature1(arg0, arg1); // signature: Complex, Complex } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test0(arg1)) { // type: number (convert to Complex) if (arguments.length === 2) { return signature1(arg0, convert0(arg1)); // signature: Complex, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: BigNumber (convert to Complex) if (arguments.length === 2) { return signature1(arg0, convert6(arg1)); // signature: Complex, BigNumber } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: Fraction (convert to Complex) if (arguments.length === 2) { return signature1(arg0, convert7(arg1)); // signature: Complex, Fraction } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test4(arg1)) { // type: string (convert to Complex) if (arguments.length === 2) { return signature1(arg0, convert8(arg1)); // signature: Complex, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } } if (test2(arg0)) { // type: BigNumber if (test1(arg1)) { // type: Complex if (arguments.length === 2) { return signature1(convert6(arg0), arg1); // signature: BigNumber, Complex } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature2(arg0, arg1); // signature: BigNumber, Big ...
...
*
* Syntax:
*
* math.smallerEq(x, y)
*
* Examples:
*
* math.smaller(1 + 2, 3); // returns false
* math.smallerEq(1 + 2, 3); // returns true
*
* See also:
*
* equal, unequal, smaller, larger, largerEq, compare
*
* @param {number | BigNumber | Fraction | boolean | Unit | string | Array | Matrix} x First value to compare
...
function smallerEq(arg0, arg1) { "use strict"; var name = 'smallerEq'; if (test0(arg0)) { // type: number if (test0(arg1)) { // type: number if (arguments.length === 2) { return signature0(arg0, arg1); // signature: number, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test1(arg1)) { // type: Complex if (arguments.length === 2) { return signature1(convert0(arg0), arg1); // signature: number, Complex } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature2(convert1(arg0), arg1); // signature: number, BigNumber } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: Fraction if (arguments.length === 2) { return signature3(convert2(arg0), arg1); // signature: number, Fraction } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test4(arg1)) { // type: string (convert to number) if (arguments.length === 2) { return signature0(arg0, convert3(arg1)); // signature: number, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test5(arg1)) { // type: boolean (convert to number) if (arguments.length === 2) { return signature0(arg0, convert4(arg1)); // signature: number, boolean } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test6(arg1)) { // type: null (convert to number) if (arguments.length === 2) { return signature0(arg0, convert5(arg1)); // signature: number, null } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } } if (test1(arg0)) { // type: Complex if (test1(arg1)) { // type: Complex if (arguments.length === 2) { return signature1(arg0, arg1); // signature: Complex, Complex } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test0(arg1)) { // type: number (convert to Complex) if (arguments.length === 2) { return signature1(arg0, convert0(arg1)); // signature: Complex, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: BigNumber (convert to Complex) if (arguments.length === 2) { return signature1(arg0, convert6(arg1)); // signature: Complex, BigNumber } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: Fraction (convert to Complex) if (arguments.length === 2) { return signature1(arg0, convert7(arg1)); // signature: Complex, Fraction } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test4(arg1)) { // type: string (convert to Complex) if (arguments.length === 2) { return signature1(arg0, convert8(arg1)); // signature: Complex, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } } if (test2(arg0)) { // type: BigNumber if (test1(arg1)) { // type: Complex if (arguments.length === 2) { return signature1(convert6(arg0), arg1); // signature: BigNumber, Complex } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature2(arg0, arg1); // signature: BigNumber, ...
...
* The function returns true when x is smaller than y or the relative
* difference between x and y is smaller than the configured epsilon. The
* function cannot be used to compare values smaller than approximately 2.22e-16.
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.smallerEq(x, y)
*
* Examples:
*
* math.smaller(1 + 2, 3); // returns false
* math.smallerEq(1 + 2, 3); // returns true
*
* See also:
...
function sort(arg0, arg1) { "use strict"; var name = 'sort'; if (test0(arg0)) { // type: Array if (arguments.length === 1) { return signature0(arg0); // signature: Array } if (test1(arg1)) { // type: string if (arguments.length === 2) { return signature1(arg0, arg1); // signature: Array, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: function if (arguments.length === 2) { return signature2(arg0, arg1); // signature: Array, function } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: number (convert to string) if (arguments.length === 2) { return signature1(arg0, convert0(arg1)); // signature: Array, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test4(arg1)) { // type: boolean (convert to string) if (arguments.length === 2) { return signature1(arg0, convert1(arg1)); // signature: Array, boolean } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test5(arg1)) { // type: null (convert to string) if (arguments.length === 2) { return signature1(arg0, convert2(arg1)); // signature: Array, null } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'string,function'); } if (test6(arg0)) { // type: Matrix if (arguments.length === 1) { return signature3(arg0); // signature: Matrix } if (test1(arg1)) { // type: string if (arguments.length === 2) { return signature4(arg0, arg1); // signature: Matrix, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: function if (arguments.length === 2) { return signature5(arg0, arg1); // signature: Matrix, function } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: number (convert to string) if (arguments.length === 2) { return signature4(arg0, convert0(arg1)); // signature: Matrix, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test4(arg1)) { // type: boolean (convert to string) if (arguments.length === 2) { return signature4(arg0, convert1(arg1)); // signature: Matrix, boolean } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test5(arg1)) { // type: null (convert to string) if (arguments.length === 2) { return signature4(arg0, convert2(arg1)); // signature: Matrix, null } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'string,function'); } throw createError(name, arguments.length, 0, arguments[0], 'Array,Matrix'); }
...
};
/**
* Sort the items in a matrix.
*
* Syntax:
*
* math.sort(x)
* math.sort(x, compare)
*
* Examples:
*
* math.sort([5, 10, 1]); // returns [1, 5, 10]
* math.sort(['C', 'B', 'A', 'D']); // returns ['A', 'B', 'C
', 'D']
*
...
function sparse(arg0, arg1) { "use strict"; var name = 'sparse'; if (arguments.length === 0) { return signature0(); // signature: } if (test0(arg0)) { // type: string if (arguments.length === 1) { return signature1(arg0); // signature: string } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: Array if (arguments.length === 1) { return signature2(arg0); // signature: Array } if (test0(arg1)) { // type: string if (arguments.length === 2) { return signature3(arg0, arg1); // signature: Array, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: number (convert to string) if (arguments.length === 2) { return signature3(arg0, convert0(arg1)); // signature: Array, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: boolean (convert to string) if (arguments.length === 2) { return signature3(arg0, convert1(arg1)); // signature: Array, boolean } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test4(arg1)) { // type: null (convert to string) if (arguments.length === 2) { return signature3(arg0, convert2(arg1)); // signature: Array, null } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'string'); } if (test5(arg0)) { // type: Matrix if (arguments.length === 1) { return signature2(arg0); // signature: Matrix } if (test0(arg1)) { // type: string if (arguments.length === 2) { return signature3(arg0, arg1); // signature: Matrix, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: number (convert to string) if (arguments.length === 2) { return signature3(arg0, convert0(arg1)); // signature: Matrix, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: boolean (convert to string) if (arguments.length === 2) { return signature3(arg0, convert1(arg1)); // signature: Matrix, boolean } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test4(arg1)) { // type: null (convert to string) if (arguments.length === 2) { return signature3(arg0, convert2(arg1)); // signature: Matrix, null } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'string'); } if (test2(arg0)) { // type: number (convert to string) if (arguments.length === 1) { return signature1(convert0(arg0)); // signature: number } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test3(arg0)) { // type: boolean (convert to string) if (arguments.length === 1) { return signature1(convert1(arg0)); // signature: boolean } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test4(arg0)) { // type: null (convert to string) if (arguments.length === 1) { return signature1(convert2(arg0)); // signature: null } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'string,Array,Matrix'); }
n/a
function splitUnit(arg0, arg1) { "use strict"; var name = 'splitUnit'; if (test0(arg0)) { // type: Unit if (test1(arg1)) { // type: Array if (arguments.length === 2) { return signature0(arg0, arg1); // signature: Unit, Array } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: Matrix (convert to Array) if (arguments.length === 2) { return signature0(arg0, convert0(arg1)); // signature: Unit, Matrix } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'Array'); } throw createError(name, arguments.length, 0, arguments[0], 'Unit'); }
...
* Returns an array of units whose sum is equal to this unit
* @memberof Unit
* @param {Array} [parts] An array of strings or valueless units.
*
* Example:
*
* var u = new Unit(1, 'm');
* u.splitUnit(['feet', 'inch']);
* [ 3 feet, 3.3700787401575 inch ]
*
* @return {Array} An array of units.
*/
Unit.prototype.splitUnit = function(parts) {
var x = this.clone();
...
function sqrt(arg0) { "use strict"; var name = 'sqrt'; if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature0(arg0); // signature: number } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: Complex if (arguments.length === 1) { return signature1(arg0); // signature: Complex } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test2(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature2(arg0); // signature: BigNumber } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test3(arg0)) { // type: Unit if (arguments.length === 1) { return signature3(arg0); // signature: Unit } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test4(arg0)) { // type: Array if (arguments.length === 1) { return signature4(arg0); // signature: Array } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test5(arg0)) { // type: Matrix if (arguments.length === 1) { return signature4(arg0); // signature: Matrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test6(arg0)) { // type: Fraction (convert to BigNumber) if (arguments.length === 1) { return signature2(convert0(arg0)); // signature: Fraction } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test7(arg0)) { // type: string (convert to number) if (arguments.length === 1) { return signature0(convert1(arg0)); // signature: string } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test8(arg0)) { // type: boolean (convert to number) if (arguments.length === 1) { return signature0(convert2(arg0)); // signature: boolean } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test9(arg0)) { // type: null (convert to number) if (arguments.length === 1) { return signature0(convert3(arg0)); // signature: null } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'number,Complex,BigNumber,Unit,Array,Matrix'); }
...
// load math.js
var math = require('mathjs');
// functions and constants
math.round(math.e, 3); // 2.718
math.atan2(3, -3) / math.pi; // 0.75
math.log(1000, 10); // 3
math.sqrt(-4); // 2i
math.pow([[-1, 2], [3, 1]], 2); // [[7, 0], [0, 7]]
math.derivative('x^2 + x', 'x'); // 2 * x + 1
// expressions
math.eval('12 / (2.3 + 0.7)'); // 4
math.eval('5.08 cm to inch'); // 2 inch
math.eval('sin(45 deg) ^ 2'); // 0.5
...
function square(arg0) { "use strict"; var name = 'square'; if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature0(arg0); // signature: number } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: Complex if (arguments.length === 1) { return signature1(arg0); // signature: Complex } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test2(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature2(arg0); // signature: BigNumber } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test3(arg0)) { // type: Fraction if (arguments.length === 1) { return signature3(arg0); // signature: Fraction } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test4(arg0)) { // type: Unit if (arguments.length === 1) { return signature4(arg0); // signature: Unit } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test5(arg0)) { // type: Array if (arguments.length === 1) { return signature5(arg0); // signature: Array } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test6(arg0)) { // type: Matrix if (arguments.length === 1) { return signature5(arg0); // signature: Matrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test7(arg0)) { // type: string (convert to number) if (arguments.length === 1) { return signature0(convert0(arg0)); // signature: string } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test8(arg0)) { // type: boolean (convert to number) if (arguments.length === 1) { return signature0(convert1(arg0)); // signature: boolean } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test9(arg0)) { // type: null (convert to number) if (arguments.length === 1) { return signature0(convert2(arg0)); // signature: null } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'number,Complex,BigNumber,Fraction,Unit,Array,Matrix'); }
...
* Syntax:
*
* math.sqrt(x)
*
* Examples:
*
* math.sqrt(25); // returns 5
* math.square(5); // returns 25
* math.sqrt(-4); // returns Complex 2i
*
* See also:
*
* square, multiply, cube, cbrt
*
* @param {number | BigNumber | Complex | Array | Matrix | Unit} x
...
function squeeze(arg0) { "use strict"; var name = 'squeeze'; if (test0(arg0)) { // type: Array if (arguments.length === 1) { return signature0(arg0); // signature: Array } } if (test1(arg0)) { // type: Matrix if (arguments.length === 1) { return signature1(arg0); // signature: Matrix } } // type: any if (arguments.length === 1) { return signature2(arg0); // signature: any } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } throw createError(name, arguments.length, 0, arguments[0], 'Array,Matrix,any'); }
...
* @param {Array} y Second vector
* @returns {Array} Returns the cross product of x and y
* @private
*/
function _cross(x, y) {
var highestDimension = Math.max(array.size(x).length, array.size(y).length);
x = array.squeeze(x);
y = array.squeeze(y);
var xSize = array.size(x);
var ySize = array.size(y);
if (xSize.length != 1 || ySize.length != 1 || xSize[0] != 3 || ySize[0] != 3) {
throw new RangeError('Vectors with length 3 expected ' +
...
function std(arg0, arg1) { "use strict"; var name = 'std'; if (test0(arg0)) { // type: Array if (arguments.length === 1) { return signature0(arg0); // signature: Array } if (test1(arg1)) { // type: string if (arguments.length === 2) { return signature0(arg0, arg1); // signature: Array, string } } if (test2(arg1)) { // type: number (convert to string) if (arguments.length === 2) { return signature0(arg0, convert0(arg1)); // signature: Array, number } } if (test3(arg1)) { // type: boolean (convert to string) if (arguments.length === 2) { return signature0(arg0, convert1(arg1)); // signature: Array, boolean } } if (test4(arg1)) { // type: null (convert to string) if (arguments.length === 2) { return signature0(arg0, convert2(arg1)); // signature: Array, null } } } if (test5(arg0)) { // type: Matrix if (arguments.length === 1) { return signature0(arg0); // signature: Matrix } if (test1(arg1)) { // type: string if (arguments.length === 2) { return signature0(arg0, arg1); // signature: Matrix, string } } if (test2(arg1)) { // type: number (convert to string) if (arguments.length === 2) { return signature0(arg0, convert0(arg1)); // signature: Matrix, number } } if (test3(arg1)) { // type: boolean (convert to string) if (arguments.length === 2) { return signature0(arg0, convert1(arg1)); // signature: Matrix, boolean } } if (test4(arg1)) { // type: null (convert to string) if (arguments.length === 2) { return signature0(arg0, convert2(arg1)); // signature: Matrix, null } } } if (arguments.length > 0) { var varArgs = []; for (var i = 0; i < arguments.length; i++) { varArgs.push(arguments[i]); } return signature1(varArgs); // signature: ...any } throw createError(name, arguments.length, 0, arguments[0], 'Array,Matrix,any'); }
...
*
* - 'unbiased' (default) The sum of squared errors is divided by (n - 1)
* - 'uncorrected' The sum of squared errors is divided by n
* - 'biased' The sum of squared errors is divided by (n + 1)
*
* Syntax:
*
* math.std(a, b, c, ...)
* math.std(A)
* math.std(A, normalization)
*
* Examples:
*
* math.std(2, 4, 6); // returns 2
* math.std([2, 4, 6, 8]); // returns 2.581988897471611
...
function stirlingS2(arg0, arg1) { "use strict"; var name = 'stirlingS2'; if (test0(arg0)) { // type: number if (test0(arg1)) { // type: number if (arguments.length === 2) { return signature0(arg0, arg1); // signature: number, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test1(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature0(arg0, arg1); // signature: number, BigNumber } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: Fraction (convert to BigNumber) if (arguments.length === 2) { return signature0(arg0, convert0(arg1)); // signature: number, Fraction } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: string (convert to number) if (arguments.length === 2) { return signature0(arg0, convert1(arg1)); // signature: number, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test4(arg1)) { // type: boolean (convert to number) if (arguments.length === 2) { return signature0(arg0, convert2(arg1)); // signature: number, boolean } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test5(arg1)) { // type: null (convert to number) if (arguments.length === 2) { return signature0(arg0, convert3(arg1)); // signature: number, null } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'number,BigNumber'); } if (test1(arg0)) { // type: BigNumber if (test0(arg1)) { // type: number if (arguments.length === 2) { return signature0(arg0, arg1); // signature: BigNumber, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test1(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature0(arg0, arg1); // signature: BigNumber, BigNumber } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: Fraction (convert to BigNumber) if (arguments.length === 2) { return signature0(arg0, convert0(arg1)); // signature: BigNumber, Fraction } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: string (convert to number) if (arguments.length === 2) { return signature0(arg0, convert1(arg1)); // signature: BigNumber, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test4(arg1)) { // type: boolean (convert to number) if (arguments.length === 2) { return signature0(arg0, convert2(arg1)); // signature: BigNumber, boolean } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test5(arg1)) { // type: null (convert to number) if (arguments.length === 2) { return signature0(arg0, convert3(arg1)); // signature: BigNumber, null } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'number,BigNumber'); } if (test2(arg0)) { // type: Fraction (convert to BigNumber) if (test0(arg1)) { // type: number if (arguments.length === 2) { return signature0(convert0(arg0), arg1); // signature: Fraction, number } if (arguments.length > 2) { throw createErr ...
...
* stirlingS2 only takes integer arguments.
* The following condition must be enforced: k <= n.
*
* If n = k or k = 1, then s(n,k) = 1
*
* Syntax:
*
* math.stirlingS2(n, k)
*
* Examples:
*
* math.stirlingS2(5, 3); //returns 25
*
* See also:
*
...
function string(arg0) { "use strict"; var name = 'string'; if (arguments.length === 0) { return signature0(); // signature: } if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature1(arg0); // signature: number } } if (test1(arg0)) { // type: string if (arguments.length === 1) { return signature2(arg0); // signature: string } } if (test2(arg0)) { // type: Array if (arguments.length === 1) { return signature3(arg0); // signature: Array } } if (test3(arg0)) { // type: Matrix if (arguments.length === 1) { return signature3(arg0); // signature: Matrix } } if (test4(arg0)) { // type: boolean if (arguments.length === 1) { return signature4(arg0); // signature: boolean } } if (test5(arg0)) { // type: null if (arguments.length === 1) { return signature5(arg0); // signature: null } } // type: any if (arguments.length === 1) { return signature6(arg0); // signature: any } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } throw createError(name, arguments.length, 0, arguments[0], 'number,string,Array,Matrix,boolean,null,any'); }
...
function factory (type, config, load, typed) {
/**
* Create a string or convert any object into a string.
* Elements of Arrays and Matrices are processed element wise.
*
* Syntax:
*
* math.string(value)
*
* Examples:
*
* math.string(4.2); // returns string '4.2'
* math.string(math.complex(3, 2); // returns string '3 + 2i'
*
* var u = math.unit(5, 'km');
...
function subset(arg0) { "use strict"; var name = 'subset'; if (arguments.length > 0) { var varArgs = []; for (var i = 0; i < arguments.length; i++) { varArgs.push(arguments[i]); } return signature0(varArgs); // signature: ...any } throw createError(name, arguments.length, 0, arguments[0], 'any'); }
...
function factory (type, config, load, typed) {
var matrix = load(require('../../type/matrix/function/matrix'));
/**
* Get or set a subset of a matrix or string.
*
* Syntax:
* math.subset(value, index) // retrieve a subset
* math.subset(value, index, replacement [, defaultValue]) // replace a subset
*
* Examples:
*
* // get a subset
* var d = [[1, 2], [3, 4]];
* math.subset(d, math.index(1, 0)); // returns 3
...
function subtract(arg0, arg1) { "use strict"; var name = 'subtract'; if (test0(arg0)) { // type: number if (test0(arg1)) { // type: number if (arguments.length === 2) { return signature0(arg0, arg1); // signature: number, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test1(arg1)) { // type: Complex if (arguments.length === 2) { return signature1(convert0(arg0), arg1); // signature: number, Complex } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature2(convert1(arg0), arg1); // signature: number, BigNumber } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: Fraction if (arguments.length === 2) { return signature3(convert2(arg0), arg1); // signature: number, Fraction } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test4(arg1)) { // type: string (convert to number) if (arguments.length === 2) { return signature0(arg0, convert3(arg1)); // signature: number, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test5(arg1)) { // type: boolean (convert to number) if (arguments.length === 2) { return signature0(arg0, convert4(arg1)); // signature: number, boolean } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test6(arg1)) { // type: null (convert to number) if (arguments.length === 2) { return signature0(arg0, convert5(arg1)); // signature: number, null } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } } if (test1(arg0)) { // type: Complex if (test1(arg1)) { // type: Complex if (arguments.length === 2) { return signature1(arg0, arg1); // signature: Complex, Complex } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test0(arg1)) { // type: number (convert to Complex) if (arguments.length === 2) { return signature1(arg0, convert0(arg1)); // signature: Complex, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: BigNumber (convert to Complex) if (arguments.length === 2) { return signature1(arg0, convert6(arg1)); // signature: Complex, BigNumber } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: Fraction (convert to Complex) if (arguments.length === 2) { return signature1(arg0, convert7(arg1)); // signature: Complex, Fraction } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test4(arg1)) { // type: string (convert to Complex) if (arguments.length === 2) { return signature1(arg0, convert8(arg1)); // signature: Complex, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } } if (test2(arg0)) { // type: BigNumber if (test1(arg1)) { // type: Complex if (arguments.length === 2) { return signature1(convert6(arg0), arg1); // signature: BigNumber, Complex } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature2(arg0, arg1); // signature: BigNumber, B ...
...
/**
* Subtract two values, `x - y`.
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.subtract(x, y)
*
* Examples:
*
* math.subtract(5.3, 2); // returns number 3.3
*
* var a = math.complex(2, 3);
* var b = math.complex(4, 1);
...
function sum(arg0, arg1) { "use strict"; var name = 'sum'; if (test0(arg0)) { // type: Array if (arguments.length === 1) { return signature0(arg0); // signature: Array } if (test1(arg1)) { // type: number if (arguments.length === 2) { return signature1(arg0, arg1); // signature: Array, number } } if (test2(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature1(arg0, arg1); // signature: Array, BigNumber } } if (test3(arg1)) { // type: Fraction (convert to BigNumber) if (arguments.length === 2) { return signature1(arg0, convert0(arg1)); // signature: Array, Fraction } } if (test4(arg1)) { // type: string (convert to number) if (arguments.length === 2) { return signature1(arg0, convert1(arg1)); // signature: Array, string } } if (test5(arg1)) { // type: boolean (convert to number) if (arguments.length === 2) { return signature1(arg0, convert2(arg1)); // signature: Array, boolean } } if (test6(arg1)) { // type: null (convert to number) if (arguments.length === 2) { return signature1(arg0, convert3(arg1)); // signature: Array, null } } } if (test7(arg0)) { // type: Matrix if (arguments.length === 1) { return signature0(arg0); // signature: Matrix } if (test1(arg1)) { // type: number if (arguments.length === 2) { return signature1(arg0, arg1); // signature: Matrix, number } } if (test2(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature1(arg0, arg1); // signature: Matrix, BigNumber } } if (test3(arg1)) { // type: Fraction (convert to BigNumber) if (arguments.length === 2) { return signature1(arg0, convert0(arg1)); // signature: Matrix, Fraction } } if (test4(arg1)) { // type: string (convert to number) if (arguments.length === 2) { return signature1(arg0, convert1(arg1)); // signature: Matrix, string } } if (test5(arg1)) { // type: boolean (convert to number) if (arguments.length === 2) { return signature1(arg0, convert2(arg1)); // signature: Matrix, boolean } } if (test6(arg1)) { // type: null (convert to number) if (arguments.length === 2) { return signature1(arg0, convert3(arg1)); // signature: Matrix, null } } } if (arguments.length > 0) { var varArgs = []; for (var i = 0; i < arguments.length; i++) { varArgs.push(arguments[i]); } return signature2(varArgs); // signature: ...any } throw createError(name, arguments.length, 0, arguments[0], 'Array,Matrix,any'); }
...
/**
* Compute the sum of a matrix or a list with values.
* In case of a (multi dimensional) array or matrix, the sum of all
* elements will be calculated.
*
* Syntax:
*
* math.sum(a, b, c, ...)
* math.sum(A)
*
* Examples:
*
* math.sum(2, 1, 4, 3); // returns 10
* math.sum([2, 1, 4, 3]); // returns 10
* math.sum([[2, 5], [4, 3], [1, 7]]); // returns 22
...
function tan(arg0) { "use strict"; var name = 'tan'; if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature0(arg0); // signature: number } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: Complex if (arguments.length === 1) { return signature1(arg0); // signature: Complex } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test2(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature2(arg0); // signature: BigNumber } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test3(arg0)) { // type: Unit if (arguments.length === 1) { return signature3(arg0); // signature: Unit } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test4(arg0)) { // type: Array if (arguments.length === 1) { return signature4(arg0); // signature: Array } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test5(arg0)) { // type: Matrix if (arguments.length === 1) { return signature4(arg0); // signature: Matrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test6(arg0)) { // type: Fraction (convert to BigNumber) if (arguments.length === 1) { return signature2(convert0(arg0)); // signature: Fraction } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test7(arg0)) { // type: string (convert to number) if (arguments.length === 1) { return signature0(convert1(arg0)); // signature: string } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test8(arg0)) { // type: boolean (convert to number) if (arguments.length === 1) { return signature0(convert2(arg0)); // signature: boolean } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test9(arg0)) { // type: null (convert to number) if (arguments.length === 1) { return signature0(convert3(arg0)); // signature: null } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'number,Complex,BigNumber,Unit,Array,Matrix'); }
...
* Syntax:
*
* math.atan(x)
*
* Examples:
*
* math.atan(0.5); // returns number 0.4636476090008061
* math.atan(math.tan(1.5)); // returns number 1.5
*
* math.atan(2); // returns Complex 1.5707963267948966 -1.3169578969248166 i
*
* See also:
*
* tan, asin, acos
*
...
function tanh(arg0) { "use strict"; var name = 'tanh'; if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature0(arg0); // signature: number } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: Complex if (arguments.length === 1) { return signature1(arg0); // signature: Complex } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test2(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature2(arg0); // signature: BigNumber } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test3(arg0)) { // type: Unit if (arguments.length === 1) { return signature3(arg0); // signature: Unit } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test4(arg0)) { // type: Array if (arguments.length === 1) { return signature4(arg0); // signature: Array } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test5(arg0)) { // type: Matrix if (arguments.length === 1) { return signature4(arg0); // signature: Matrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test6(arg0)) { // type: Fraction (convert to BigNumber) if (arguments.length === 1) { return signature2(convert0(arg0)); // signature: Fraction } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test7(arg0)) { // type: string (convert to number) if (arguments.length === 1) { return signature0(convert1(arg0)); // signature: string } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test8(arg0)) { // type: boolean (convert to number) if (arguments.length === 1) { return signature0(convert2(arg0)); // signature: boolean } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test9(arg0)) { // type: null (convert to number) if (arguments.length === 1) { return signature0(convert3(arg0)); // signature: null } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'number,Complex,BigNumber,Unit,Array,Matrix'); }
...
*
* math.coth(x)
*
* Examples:
*
* // coth(x) = 1 / tanh(x)
* math.coth(2); // returns 1.0373147207275482
* 1 / math.tanh(2); // returns 1.0373147207275482
*
* See also:
*
* sinh, tanh, cosh
*
* @param {number | Complex | Unit | Array | Matrix} x Function input
* @return {number | Complex | Array | Matrix} Hyperbolic cotangent of x
...
function to(arg0, arg1) { "use strict"; var name = 'to'; if (test0(arg0)) { // type: Unit if (test0(arg1)) { // type: Unit if (arguments.length === 2) { return signature0(arg0, arg1); // signature: Unit, Unit } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test1(arg1)) { // type: string if (arguments.length === 2) { return signature0(arg0, arg1); // signature: Unit, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: number (convert to string) if (arguments.length === 2) { return signature0(arg0, convert0(arg1)); // signature: Unit, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: boolean (convert to string) if (arguments.length === 2) { return signature0(arg0, convert1(arg1)); // signature: Unit, boolean } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test4(arg1)) { // type: null (convert to string) if (arguments.length === 2) { return signature0(arg0, convert2(arg1)); // signature: Unit, null } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } } if (test5(arg0)) { // type: Array if (test5(arg1)) { // type: Array if (arguments.length === 2) { return signature1(arg0, arg1); // signature: Array, Array } } if (test6(arg1)) { // type: Matrix if (arguments.length === 2) { return signature2(arg0, arg1); // signature: Array, Matrix } } // type: any if (arguments.length === 2) { return signature3(arg0, arg1); // signature: Array, any } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test6(arg0)) { // type: Matrix if (test5(arg1)) { // type: Array if (arguments.length === 2) { return signature4(arg0, arg1); // signature: Matrix, Array } } if (test6(arg1)) { // type: Matrix if (arguments.length === 2) { return signature5(arg0, arg1); // signature: Matrix, Matrix } } // type: any if (arguments.length === 2) { return signature6(arg0, arg1); // signature: Matrix, any } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } // type: any if (test5(arg1)) { // type: Array if (arguments.length === 2) { return signature7(arg0, arg1); // signature: any, Array } } if (test6(arg1)) { // type: Matrix if (arguments.length === 2) { return signature8(arg0, arg1); // signature: any, Matrix } } throw createError(name, arguments.length, 1, arguments[1], 'Array,Matrix'); throw createError(name, arguments.length, 0, arguments[0], 'Unit,Array,Matrix,any'); }
...
*
* Examples:
*
* math.string(4.2); // returns string '4.2'
* math.string(math.complex(3, 2); // returns string '3 + 2i'
*
* var u = math.unit(5, 'km');
* math.string(u.to('m')); // returns string '5000 m'
*
* math.string([true, false]); // returns ['true', 'false']
*
* See also:
*
* bignumber, boolean, complex, index, matrix, number, unit
*
...
function trace(arg0) { "use strict"; var name = 'trace'; if (test0(arg0)) { // type: Array if (arguments.length === 1) { return signature0(arg0); // signature: Array } } if (test1(arg0)) { // type: Matrix if (arguments.length === 1) { return signature1(arg0); // signature: Matrix } } // type: any if (arguments.length === 1) { return signature2(arg0); // signature: any } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } throw createError(name, arguments.length, 0, arguments[0], 'Array,Matrix,any'); }
...
/**
* Calculate the trace of a matrix: the sum of the elements on the main
* diagonal of a square matrix.
*
* Syntax:
*
* math.trace(x)
*
* Examples:
*
* math.trace([[1, 2], [3, 4]]); // returns 5
*
* var A = [
* [1, 2, 3],
...
function transpose(arg0) { "use strict"; var name = 'transpose'; if (test0(arg0)) { // type: Array if (arguments.length === 1) { return signature0(arg0); // signature: Array } } if (test1(arg0)) { // type: Matrix if (arguments.length === 1) { return signature1(arg0); // signature: Matrix } } // type: any if (arguments.length === 1) { return signature2(arg0); // signature: any } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } throw createError(name, arguments.length, 0, arguments[0], 'Array,Matrix,any'); }
...
* Transpose a matrix. All values of the matrix are reflected over its
* main diagonal. Only applicable to two dimensional matrices containing
* a vector (i.e. having size `[1,n]` or `[n,1]`). One dimensional
* vectors and scalars return the input unchanged.
*
* Syntax:
*
* math.transpose(x)
*
* Examples:
*
* var A = [[1, 2, 3], [4, 5, 6]];
* math.transpose(A); // returns [[1, 4], [2, 5], [3, 6]]
*
* See also:
...
function _typeof(arg0) { "use strict"; var name = '_typeof'; // type: any if (arguments.length === 1) { return signature0(arg0); // signature: any } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } throw createError(name, arguments.length, 0, arguments[0], 'any'); }
...
/**
* Determine the type of a variable.
*
* Function `typeof` recognizes the following types of objects:
*
* Object | Returns | Example
* ---------------------- | ------------- | ------------------------------------------
* null | `'null'` | `math.typeof(null)`
* number | `'number'` | `math.typeof(3.5)`
* boolean | `'boolean'` | `math.typeof (true)`
* string | `'string'` | `math.typeof ('hello world')`
* Array | `'Array'` | `math.typeof ([1, 2, 3])`
* Date | `'Date'` | `math.typeof (new Date())`
* Function | `'Function'` | `math.typeof (function () {})`
* Object | `'Object'` | `math.typeof ({a: 2, b: 3})`
...
function unaryMinus(arg0) { "use strict"; var name = 'unaryMinus'; if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature0(arg0); // signature: number } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: Complex if (arguments.length === 1) { return signature1(arg0); // signature: Complex } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test2(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature2(arg0); // signature: BigNumber } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test3(arg0)) { // type: Fraction if (arguments.length === 1) { return signature3(arg0); // signature: Fraction } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test4(arg0)) { // type: Unit if (arguments.length === 1) { return signature4(arg0); // signature: Unit } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test5(arg0)) { // type: Array if (arguments.length === 1) { return signature5(arg0); // signature: Array } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test6(arg0)) { // type: Matrix if (arguments.length === 1) { return signature5(arg0); // signature: Matrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test7(arg0)) { // type: string (convert to number) if (arguments.length === 1) { return signature0(convert0(arg0)); // signature: string } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test8(arg0)) { // type: boolean (convert to number) if (arguments.length === 1) { return signature0(convert1(arg0)); // signature: boolean } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test9(arg0)) { // type: null (convert to number) if (arguments.length === 1) { return signature0(convert2(arg0)); // signature: null } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'number,Complex,BigNumber,Fraction,Unit,Array,Matrix'); }
...
*
* For matrices, the function is evaluated element wise. Boolean values and
* strings will be converted to a number. For complex numbers, both real and
* complex value are inverted.
*
* Syntax:
*
* math.unaryMinus(x)
*
* Examples:
*
* math.unaryMinus(3.5); // returns -3.5
* math.unaryMinus(-4.2); // returns 4.2
*
* See also:
...
function unaryPlus(arg0) { "use strict"; var name = 'unaryPlus'; if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature0(arg0); // signature: number } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test1(arg0)) { // type: Complex if (arguments.length === 1) { return signature1(arg0); // signature: Complex } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test2(arg0)) { // type: BigNumber if (arguments.length === 1) { return signature2(arg0); // signature: BigNumber } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test3(arg0)) { // type: Fraction if (arguments.length === 1) { return signature3(arg0); // signature: Fraction } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test4(arg0)) { // type: Unit if (arguments.length === 1) { return signature4(arg0); // signature: Unit } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test5(arg0)) { // type: string if (arguments.length === 1) { return signature5(arg0); // signature: string } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test6(arg0)) { // type: Array if (arguments.length === 1) { return signature6(arg0); // signature: Array } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test7(arg0)) { // type: Matrix if (arguments.length === 1) { return signature6(arg0); // signature: Matrix } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test8(arg0)) { // type: boolean if (arguments.length === 1) { return signature5(arg0); // signature: boolean } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } if (test9(arg0)) { // type: null if (arguments.length === 1) { return signature5(arg0); // signature: null } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'number,Complex,BigNumber,Fraction,Unit,string,Array,Matrix,boolean ,null'); }
...
* Unary plus operation.
* Boolean values and strings will be converted to a number, numeric values will be returned as is.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.unaryPlus(x)
*
* Examples:
*
* math.unaryPlus(3.5); // returns 3.5
* math.unaryPlus(1); // returns 1
*
* See also:
...
function unequal(arg0, arg1) { "use strict"; var name = 'unequal'; if (test0(arg0)) { // type: Array if (test0(arg1)) { // type: Array if (arguments.length === 2) { return signature0(arg0, arg1); // signature: Array, Array } } if (test1(arg1)) { // type: Matrix if (arguments.length === 2) { return signature1(arg0, arg1); // signature: Array, Matrix } } // type: any if (arguments.length === 2) { return signature2(arg0, arg1); // signature: Array, any } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test1(arg0)) { // type: Matrix if (test0(arg1)) { // type: Array if (arguments.length === 2) { return signature3(arg0, arg1); // signature: Matrix, Array } } if (test1(arg1)) { // type: Matrix if (arguments.length === 2) { return signature4(arg0, arg1); // signature: Matrix, Matrix } } // type: any if (arguments.length === 2) { return signature5(arg0, arg1); // signature: Matrix, any } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } // type: any if (test0(arg1)) { // type: Array if (arguments.length === 2) { return signature6(arg0, arg1); // signature: any, Array } } if (test1(arg1)) { // type: Matrix if (arguments.length === 2) { return signature7(arg0, arg1); // signature: any, Matrix } } // type: any if (arguments.length === 2) { return signature8(arg0, arg1); // signature: any, any } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } throw createError(name, arguments.length, 1, arguments[1], 'Array,Matrix,any'); throw createError(name, arguments.length, 0, arguments[0], 'Array,Matrix,any'); }
...
*
* Values `null` and `undefined` are compared strictly, thus `null` is unequal
* with everything except `null`, and `undefined` is unequal with everying
* except. `undefined`.
*
* Syntax:
*
* math.unequal(x, y)
*
* Examples:
*
* math.unequal(2 + 2, 3); // returns true
* math.unequal(2 + 2, 4); // returns false
*
* var a = math.unit('50 cm');
...
function unit(arg0, arg1) { "use strict"; var name = 'unit'; if (test0(arg0)) { // type: number if (arguments.length === 1) { return signature0(convert0(arg0)); // signature: number } if (test1(arg1)) { // type: string if (arguments.length === 2) { return signature1(arg0, arg1); // signature: number, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test0(arg1)) { // type: number (convert to string) if (arguments.length === 2) { return signature1(arg0, convert0(arg1)); // signature: number, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: boolean (convert to string) if (arguments.length === 2) { return signature1(arg0, convert1(arg1)); // signature: number, boolean } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: null (convert to string) if (arguments.length === 2) { return signature1(arg0, convert2(arg1)); // signature: number, null } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'string'); } if (test4(arg0)) { // type: Complex if (test1(arg1)) { // type: string if (arguments.length === 2) { return signature1(arg0, arg1); // signature: Complex, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test0(arg1)) { // type: number (convert to string) if (arguments.length === 2) { return signature1(arg0, convert0(arg1)); // signature: Complex, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: boolean (convert to string) if (arguments.length === 2) { return signature1(arg0, convert1(arg1)); // signature: Complex, boolean } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: null (convert to string) if (arguments.length === 2) { return signature1(arg0, convert2(arg1)); // signature: Complex, null } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'string'); } if (test5(arg0)) { // type: BigNumber if (test1(arg1)) { // type: string if (arguments.length === 2) { return signature1(arg0, arg1); // signature: BigNumber, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test0(arg1)) { // type: number (convert to string) if (arguments.length === 2) { return signature1(arg0, convert0(arg1)); // signature: BigNumber, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: boolean (convert to string) if (arguments.length === 2) { return signature1(arg0, convert1(arg1)); // signature: BigNumber, boolean } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: null (convert to string) if (arguments.length === 2) { return signature1(arg0, convert2(arg1)); // signature: BigNumber, null } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'string'); } if (test6(arg0)) { // type: Fraction if (test1(arg1)) { // type: string if (argument ...
...
*
* Examples:
*
* math.number(2); // returns number 2
* math.number('7.2'); // returns number 7.2
* math.number(true); // returns number 1
* math.number([true, false, true, true]); // returns [1, 0, 1, 1]
* math.number(math.unit('52cm'), 'm'); // returns 0.52
*
* See also:
*
* bignumber, boolean, complex, index, matrix, string, unit
*
* @param {string | number | BigNumber | Fraction | boolean | Array | Matrix | Unit | null} [value] Value to be converted
* @param {Unit | string} [valuelessUnit] A valueless unit, used to convert a unit to a number
...
function usolve(arg0, arg1) { "use strict"; var name = 'usolve'; if (test0(arg0)) { // type: Array if (test0(arg1)) { // type: Array if (arguments.length === 2) { return signature0(arg0, arg1); // signature: Array, Array } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test1(arg1)) { // type: Matrix if (arguments.length === 2) { return signature0(arg0, arg1); // signature: Array, Matrix } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'Array,Matrix'); } if (test2(arg0)) { // type: DenseMatrix if (test0(arg1)) { // type: Array if (arguments.length === 2) { return signature1(arg0, arg1); // signature: DenseMatrix, Array } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test1(arg1)) { // type: Matrix if (arguments.length === 2) { return signature1(arg0, arg1); // signature: DenseMatrix, Matrix } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'Array,Matrix'); } if (test3(arg0)) { // type: SparseMatrix if (test0(arg1)) { // type: Array if (arguments.length === 2) { return signature2(arg0, arg1); // signature: SparseMatrix, Array } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test1(arg1)) { // type: Matrix if (arguments.length === 2) { return signature2(arg0, arg1); // signature: SparseMatrix, Matrix } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'Array,Matrix'); } if (test1(arg0)) { // type: Matrix (convert to Array) if (test0(arg1)) { // type: Array if (arguments.length === 2) { return signature0(convert0(arg0), arg1); // signature: Matrix, Array } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test1(arg1)) { // type: Matrix if (arguments.length === 2) { return signature0(convert0(arg0), arg1); // signature: Matrix, Matrix } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'Array,Matrix'); } throw createError(name, arguments.length, 0, arguments[0], 'Array,DenseMatrix,SparseMatrix'); }
n/a
function variance(arg0, arg1) { "use strict"; var name = 'variance'; if (test0(arg0)) { // type: Array if (arguments.length === 1) { return signature0(arg0); // signature: Array } if (test1(arg1)) { // type: string if (arguments.length === 2) { return signature1(arg0, arg1); // signature: Array, string } } if (test2(arg1)) { // type: number (convert to string) if (arguments.length === 2) { return signature1(arg0, convert0(arg1)); // signature: Array, number } } if (test3(arg1)) { // type: boolean (convert to string) if (arguments.length === 2) { return signature1(arg0, convert1(arg1)); // signature: Array, boolean } } if (test4(arg1)) { // type: null (convert to string) if (arguments.length === 2) { return signature1(arg0, convert2(arg1)); // signature: Array, null } } } if (test5(arg0)) { // type: Matrix if (arguments.length === 1) { return signature0(arg0); // signature: Matrix } if (test1(arg1)) { // type: string if (arguments.length === 2) { return signature1(arg0, arg1); // signature: Matrix, string } } if (test2(arg1)) { // type: number (convert to string) if (arguments.length === 2) { return signature1(arg0, convert0(arg1)); // signature: Matrix, number } } if (test3(arg1)) { // type: boolean (convert to string) if (arguments.length === 2) { return signature1(arg0, convert1(arg1)); // signature: Matrix, boolean } } if (test4(arg1)) { // type: null (convert to string) if (arguments.length === 2) { return signature1(arg0, convert2(arg1)); // signature: Matrix, null } } } if (arguments.length > 0) { var varArgs = []; for (var i = 0; i < arguments.length; i++) { varArgs.push(arguments[i]); } return signature2(varArgs); // signature: ...any } throw createError(name, arguments.length, 0, arguments[0], 'Array,Matrix,any'); }
...
*
* - 'unbiased' (default) The sum of squared errors is divided by (n - 1)
* - 'uncorrected' The sum of squared errors is divided by n
* - 'biased' The sum of squared errors is divided by (n + 1)
*
* Note that older browser may not like the variable name `var`. In that
* case, the function can be called as `math['var'](...)` instead of
* `math.var(...)`.
*
* Syntax:
*
* math.var(a, b, c, ...)
* math.var(A)
* math.var(A, normalization)
*
...
function xgcd(arg0, arg1) { "use strict"; var name = 'xgcd'; if (test0(arg0)) { // type: number if (test0(arg1)) { // type: number if (arguments.length === 2) { return signature0(arg0, arg1); // signature: number, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test1(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature1(convert0(arg0), arg1); // signature: number, BigNumber } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: Fraction (convert to BigNumber) if (arguments.length === 2) { return signature1(convert0(arg0), convert1(arg1)); // signature: number, Fraction } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: string (convert to number) if (arguments.length === 2) { return signature0(arg0, convert2(arg1)); // signature: number, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test4(arg1)) { // type: boolean (convert to number) if (arguments.length === 2) { return signature0(arg0, convert3(arg1)); // signature: number, boolean } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test5(arg1)) { // type: null (convert to number) if (arguments.length === 2) { return signature0(arg0, convert4(arg1)); // signature: number, null } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'number,BigNumber'); } if (test1(arg0)) { // type: BigNumber if (test1(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature1(arg0, arg1); // signature: BigNumber, BigNumber } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test0(arg1)) { // type: number (convert to BigNumber) if (arguments.length === 2) { return signature1(arg0, convert0(arg1)); // signature: BigNumber, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: Fraction (convert to BigNumber) if (arguments.length === 2) { return signature1(arg0, convert1(arg1)); // signature: BigNumber, Fraction } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: string (convert to BigNumber) if (arguments.length === 2) { return signature1(arg0, convert5(arg1)); // signature: BigNumber, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test4(arg1)) { // type: boolean (convert to BigNumber) if (arguments.length === 2) { return signature1(arg0, convert6(arg1)); // signature: BigNumber, boolean } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test5(arg1)) { // type: null (convert to BigNumber) if (arguments.length === 2) { return signature1(arg0, convert7(arg1)); // signature: BigNumber, null } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'BigNumber'); } if (test2(arg0)) { // type: Fraction (convert to BigNumber) if (test1(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature1(convert1(arg0), arg1); // signature: Fraction, BigNumber } if ...
...
/**
* Calculate the extended greatest common divisor for two values.
* See http://en.wikipedia.org/wiki/Extended_Euclidean_algorithm.
*
* Syntax:
*
* math.xgcd(a, b)
*
* Examples:
*
* math.xgcd(8, 12); // returns [4, -1, 1]
* math.gcd(8, 12); // returns 4
* math.xgcd(36163, 21199); // returns [1247, -7, 12]
*
...
function xor(arg0, arg1) { "use strict"; var name = 'xor'; if (test0(arg0)) { // type: number if (test0(arg1)) { // type: number if (arguments.length === 2) { return signature0(arg0, arg1); // signature: number, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test1(arg1)) { // type: Complex if (arguments.length === 2) { return signature1(convert0(arg0), arg1); // signature: number, Complex } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature2(convert1(arg0), arg1); // signature: number, BigNumber } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: Fraction (convert to BigNumber) if (arguments.length === 2) { return signature2(convert1(arg0), convert2(arg1)); // signature: number, Fraction } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test4(arg1)) { // type: string (convert to number) if (arguments.length === 2) { return signature0(arg0, convert3(arg1)); // signature: number, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test5(arg1)) { // type: boolean (convert to number) if (arguments.length === 2) { return signature0(arg0, convert4(arg1)); // signature: number, boolean } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test6(arg1)) { // type: null (convert to number) if (arguments.length === 2) { return signature0(arg0, convert5(arg1)); // signature: number, null } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } } if (test1(arg0)) { // type: Complex if (test1(arg1)) { // type: Complex if (arguments.length === 2) { return signature1(arg0, arg1); // signature: Complex, Complex } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test0(arg1)) { // type: number (convert to Complex) if (arguments.length === 2) { return signature1(arg0, convert0(arg1)); // signature: Complex, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: BigNumber (convert to Complex) if (arguments.length === 2) { return signature1(arg0, convert6(arg1)); // signature: Complex, BigNumber } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: Fraction (convert to Complex) if (arguments.length === 2) { return signature1(arg0, convert7(arg1)); // signature: Complex, Fraction } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test4(arg1)) { // type: string (convert to Complex) if (arguments.length === 2) { return signature1(arg0, convert8(arg1)); // signature: Complex, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } } if (test2(arg0)) { // type: BigNumber if (test1(arg1)) { // type: Complex if (arguments.length === 2) { return signature1(convert6(arg0), arg1); // signature: BigNumber, Complex } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: BigNumber if (arguments.length === 2) { return signature2(arg0, arg1); // ...
...
/**
* Logical `xor`. Test whether one and only one value is defined with a nonzero/nonempty value.
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.xor(x, y)
*
* Examples:
*
* math.xor(2, 4); // returns false
*
* a = [2, 0, 0];
* b = [2, 7, 0];
...
function zeros(arg0, arg1) { "use strict"; var name = 'zeros'; if (arguments.length === 0) { return signature0(); // signature: } if (test0(arg0)) { // type: Array if (arguments.length === 1) { return signature1(arg0); // signature: Array } if (test1(arg1)) { // type: string if (arguments.length === 2) { return signature2(arg0, arg1); // signature: Array, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: number (convert to string) if (arguments.length === 2) { return signature2(arg0, convert0(arg1)); // signature: Array, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: boolean (convert to string) if (arguments.length === 2) { return signature2(arg0, convert1(arg1)); // signature: Array, boolean } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test4(arg1)) { // type: null (convert to string) if (arguments.length === 2) { return signature2(arg0, convert2(arg1)); // signature: Array, null } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'string'); } if (test5(arg0)) { // type: Matrix if (arguments.length === 1) { return signature3(arg0); // signature: Matrix } if (test1(arg1)) { // type: string if (arguments.length === 2) { return signature2(arg0, arg1); // signature: Matrix, string } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test2(arg1)) { // type: number (convert to string) if (arguments.length === 2) { return signature2(arg0, convert0(arg1)); // signature: Matrix, number } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test3(arg1)) { // type: boolean (convert to string) if (arguments.length === 2) { return signature2(arg0, convert1(arg1)); // signature: Matrix, boolean } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } if (test4(arg1)) { // type: null (convert to string) if (arguments.length === 2) { return signature2(arg0, convert2(arg1)); // signature: Matrix, null } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'string'); } if (test2(arg0) || test6(arg0) || test1(arg0) || test7(arg0) || test3(arg0) || test3(arg0) || test3(arg0) || test4(arg0) || test4 (arg0) || test4(arg0)) { // type: ...number|BigNumber|string|Fraction|boolean|null var varArgs = [arg0]; for (var i = 1; i < arguments.length; i++) { if (test2(arguments[i]) || test6(arguments[i]) || test1(arguments[i])) { varArgs.push(arguments[i]); } else if (test7(arguments[i])) { varArgs.push(convert3(arguments[i])); } else if (test3(arguments[i])) { varArgs.push(convert4(arguments[i])); } else if (test3(arguments[i])) { varArgs.push(convert5(arguments[i])); } else if (test3(arguments[i])) { varArgs.push(convert1(arguments[i])); } else if (test4(arguments[i])) { varArgs.push(convert6(arguments[i])); } else if (test4(arguments[i])) { varArgs.push(convert2(arguments[i])); } else if (test4(arguments[i])) { varArgs.push(convert7(arguments[i])); } else { throw createError(name, arguments.length, i, arguments[i], 'number,BigNumber,string'); } } return signature4(varArgs); // signature: ...number|BigN ...
...
* math.squeeze(x)
*
* Examples:
*
* math.squeeze([3]); // returns 3
* math.squeeze([[3]]); // returns 3
*
* var A = math.zeros(3, 1); // returns [[0], [0], [0]] (size 3x1)
* math.squeeze(A); // returns [0, 0, 0] (size 3)
*
* var B = math.zeros(1, 3); // returns [[0, 0, 0]] (size 1x3)
* math.squeeze(B); // returns [0, 0, 0] (size 3)
*
* // only inner and outer dimensions are removed
* var C = math.zeros(2, 1, 3); // returns [[[0, 0, 0]], [[0, 0, 0]]] (size 2x1x3)
...
_compile = function (defs, args) { defs.access = access; defs.getSafeProperty = getSafeProperty; var object = this.object._compile(defs, args); var index = this.index._compile(defs, args); if (this.index.isObjectProperty()) { var prop = this.index.getObjectProperty(); return 'getSafeProperty(' + object + ', "' + prop + '")'; } else if (this.index.needsSize()) { // if some parameters use the 'end' parameter, we need to calculate the size return '(function () {' + ' var object = ' + object + ';' + ' var size = math.size(object).valueOf();' + ' return access(object, ' + index + ');' + '})()'; } else { return 'access(' + object + ', ' + index + ')'; } }
...
* @return {string} js
* @private
*/
AccessorNode.prototype._compile = function (defs, args) {
defs.access = access;
defs.getSafeProperty = getSafeProperty;
var object = this.object._compile(defs, args);
var index = this.index._compile(defs, args);
if (this.index.isObjectProperty()) {
var prop = this.index.getObjectProperty();
return 'getSafeProperty(' + object + ', "' + prop + '")';
}
else if (this.index.needsSize()) {
...
_toString = function (options) { var object = this.object.toString(options); if (needParenthesis(this.object)) { object = '(' + object + ')'; } return object + this.index.toString(options); }
...
}
}
if (typeof customString !== 'undefined') {
return customString;
}
return this._toString(options);
};
/**
* Internal function to generate the string output.
* This has to be implemented by every Node
*
* @throws {Error}
...
_toTex = function (options) { var object = this.object.toTex(options); if (needParenthesis(this.object)) { object = '\\left(' + object + '\\right)'; } return object + this.index.toTex(options); }
...
}
}
if (typeof customTex !== 'undefined') {
return customTex;
}
return this._toTex(options);
};
/**
* Internal function to generate the LaTeX output.
* This has to be implemented by every Node
*
* @param {Object} [options]
...
clone = function () { return new AccessorNode(this.object, this.index); }
...
return desc;
};
/**
* Export the help object to JSON
*/
Help.prototype.toJSON = function () {
var obj = object.clone(this.doc);
obj.mathjs = 'Help';
return obj;
};
/**
* Instantiate a Help object from a JSON object
* @param {Object} json
...
forEach = function (callback) { callback(this.object, 'object', this); callback(this.index, 'index', this); }
...
if (def.indexOf(keyword) == 0) {
matches.push(def);
}
}
}
// commandline keywords
['exit', 'quit', 'clear'].forEach(function (cmd) {
if (cmd.indexOf(keyword) == 0) {
matches.push(cmd);
}
});
// math functions and constants
var ignore = ['expr', 'type'];
...
map = function (callback) { return new AccessorNode( this._ifNode(callback(this.object, 'object', this)), this._ifNode(callback(this.index, 'index', this)) ); }
...
if (res && res.isResultSet) {
// we can have 0 or 1 results in the ResultSet, as the CLI
// does not allow multiple expressions separated by a return
res = res.entries[0];
node = node.blocks
.filter(function (entry) { return entry.visible; })
.map(function (entry) { return entry.node })[0];
}
if (node) {
if (node.isAssignmentNode) {
var name = findSymbolName(node);
if (name != null) {
scope.ans = scope[name];
...
_compile = function (defs, args) { var asMatrix = (defs.math.config().matrix !== 'Array'); var items = this.items.map(function (node) { return node._compile(defs, args); }); return (asMatrix ? 'math.matrix([' : '[') + items.join(',') + (asMatrix ? '])' : ']'); }
...
* @return {string} js
* @private
*/
AccessorNode.prototype._compile = function (defs, args) {
defs.access = access;
defs.getSafeProperty = getSafeProperty;
var object = this.object._compile(defs, args);
var index = this.index._compile(defs, args);
if (this.index.isObjectProperty()) {
var prop = this.index.getObjectProperty();
return 'getSafeProperty(' + object + ', "' + prop + '")';
}
else if (this.index.needsSize()) {
...
_toString = function (options) { var items = this.items.map(function (node) { return node.toString(options); }); return '[' + items.join(', ') + ']'; }
...
}
}
if (typeof customString !== 'undefined') {
return customString;
}
return this._toString(options);
};
/**
* Internal function to generate the string output.
* This has to be implemented by every Node
*
* @throws {Error}
...
_toTex = function (options) { var s = '\\begin{bmatrix}'; this.items.forEach(function(node) { if (node.items) { s += node.items.map(function(childNode) { return childNode.toTex(options); }).join('&'); } else { s += node.toTex(options); } // new line s += '\\\\'; }); s += '\\end{bmatrix}'; return s; }
...
}
}
if (typeof customTex !== 'undefined') {
return customTex;
}
return this._toTex(options);
};
/**
* Internal function to generate the LaTeX output.
* This has to be implemented by every Node
*
* @param {Object} [options]
...
clone = function () { return new ArrayNode(this.items.slice(0)); }
...
return desc;
};
/**
* Export the help object to JSON
*/
Help.prototype.toJSON = function () {
var obj = object.clone(this.doc);
obj.mathjs = 'Help';
return obj;
};
/**
* Instantiate a Help object from a JSON object
* @param {Object} json
...
forEach = function (callback) { for (var i = 0; i < this.items.length; i++) { var node = this.items[i]; callback(node, 'items[' + i + ']', this); } }
...
if (def.indexOf(keyword) == 0) {
matches.push(def);
}
}
}
// commandline keywords
['exit', 'quit', 'clear'].forEach(function (cmd) {
if (cmd.indexOf(keyword) == 0) {
matches.push(cmd);
}
});
// math functions and constants
var ignore = ['expr', 'type'];
...
map = function (callback) { var items = []; for (var i = 0; i < this.items.length; i++) { items[i] = this._ifNode(callback(this.items[i], 'items[' + i + ']', this)); } return new ArrayNode(items); }
...
if (res && res.isResultSet) {
// we can have 0 or 1 results in the ResultSet, as the CLI
// does not allow multiple expressions separated by a return
res = res.entries[0];
node = node.blocks
.filter(function (entry) { return entry.visible; })
.map(function (entry) { return entry.node })[0];
}
if (node) {
if (node.isAssignmentNode) {
var name = findSymbolName(node);
if (name != null) {
scope.ans = scope[name];
...
_compile = function (defs, args) { defs.assign = assign; defs.access = access; defs.getSafeProperty = getSafeProperty; defs.setSafeProperty = setSafeProperty; var size; var object = this.object._compile(defs, args); var index = this.index ? this.index._compile(defs, args) : null; var value = this.value._compile(defs, args); if (!this.index) { // apply a variable to the scope, for example `a=2` if (!this.object.isSymbolNode) { throw new TypeError('SymbolNode expected as object'); } return 'setSafeProperty(scope, "' + this.object.name + '", ' + value + ')'; } else if (this.index.isObjectProperty()) { // apply an object property for example `a.b=2` return 'setSafeProperty(' + object + ', "' + this.index.getObjectProperty() + '", ' + value + ')'; } else if (this.object.isSymbolNode) { // update a matrix subset, for example `a[2]=3` size = this.index.needsSize() ? 'var size = math.size(object).valueOf();' : ''; // apply updated object to scope return '(function () {' + ' var object = ' + object + ';' + ' var value = ' + value + ';' + ' ' + size + ' setSafeProperty(scope, "' + this.object.name + '", assign(object, ' + index + ', value));' + ' return value;' + '})()'; } else { // this.object.isAccessorNode === true // update a matrix subset, for example `a.b[2]=3` size = this.index.needsSize() ? 'var size = math.size(object).valueOf();' : ''; // we will not use the _compile of the AccessorNode, but compile it // ourselves here as we need the parent object of the AccessorNode: // wee need to apply the updated object to parent object var parentObject = this.object.object._compile(defs, args); if (this.object.index.isObjectProperty()) { var parentProperty = '"' + this.object.index.getObjectProperty() + '"'; return '(function () {' + ' var parent = ' + parentObject + ';' + ' var object = getSafeProperty(parent, ' + parentProperty + ');' + // parentIndex is a property ' var value = ' + value + ';' + size + ' setSafeProperty(parent, ' + parentProperty + ', assign(object, ' + index + ', value));' + ' return value;' + '})()'; } else { // if some parameters use the 'end' parameter, we need to calculate the size var parentSize = this.object.index.needsSize() ? 'var size = math.size(parent).valueOf();' : ''; var parentIndex = this.object.index._compile(defs, args); return '(function () {' + ' var parent = ' + parentObject + ';' + ' ' + parentSize + ' var parentIndex = ' + parentIndex + ';' + ' var object = access(parent, parentIndex);' + ' var value = ' + value + ';' + ' ' + size + ' assign(parent, parentIndex, assign(object, ' + index + ', value));' + ' return value;' + '})()'; } } }
...
* @return {string} js
* @private
*/
AccessorNode.prototype._compile = function (defs, args) {
defs.access = access;
defs.getSafeProperty = getSafeProperty;
var object = this.object._compile(defs, args);
var index = this.index._compile(defs, args);
if (this.index.isObjectProperty()) {
var prop = this.index.getObjectProperty();
return 'getSafeProperty(' + object + ', "' + prop + '")';
}
else if (this.index.needsSize()) {
...
_toString = function (options) { var object = this.object.toString(options); var index = this.index ? this.index.toString(options) : ''; var value = this.value.toString(options); if (needParenthesis(this, options && options.parenthesis)) { value = '(' + value + ')'; } return object + index + ' = ' + value; }
...
}
}
if (typeof customString !== 'undefined') {
return customString;
}
return this._toString(options);
};
/**
* Internal function to generate the string output.
* This has to be implemented by every Node
*
* @throws {Error}
...
_toTex = function (options) { var object = this.object.toTex(options); var index = this.index ? this.index.toTex(options) : ''; var value = this.value.toTex(options); if (needParenthesis(this, options && options.parenthesis)) { value = '\\left(' + value + '\\right)'; } return object + index + ':=' + value; }
...
}
}
if (typeof customTex !== 'undefined') {
return customTex;
}
return this._toTex(options);
};
/**
* Internal function to generate the LaTeX output.
* This has to be implemented by every Node
*
* @param {Object} [options]
...
clone = function () { return new AssignmentNode(this.object, this.index, this.value); }
...
return desc;
};
/**
* Export the help object to JSON
*/
Help.prototype.toJSON = function () {
var obj = object.clone(this.doc);
obj.mathjs = 'Help';
return obj;
};
/**
* Instantiate a Help object from a JSON object
* @param {Object} json
...
forEach = function (callback) { callback(this.object, 'object', this); if (this.index) { callback(this.index, 'index', this); } callback(this.value, 'value', this); }
...
if (def.indexOf(keyword) == 0) {
matches.push(def);
}
}
}
// commandline keywords
['exit', 'quit', 'clear'].forEach(function (cmd) {
if (cmd.indexOf(keyword) == 0) {
matches.push(cmd);
}
});
// math functions and constants
var ignore = ['expr', 'type'];
...
map = function (callback) { var object = this._ifNode(callback(this.object, 'object', this)); var index = this.index ? this._ifNode(callback(this.index, 'index', this)) : null; var value = this._ifNode(callback(this.value, 'value', this)); return new AssignmentNode(object, index, value); }
...
if (res && res.isResultSet) {
// we can have 0 or 1 results in the ResultSet, as the CLI
// does not allow multiple expressions separated by a return
res = res.entries[0];
node = node.blocks
.filter(function (entry) { return entry.visible; })
.map(function (entry) { return entry.node })[0];
}
if (node) {
if (node.isAssignmentNode) {
var name = findSymbolName(node);
if (name != null) {
scope.ans = scope[name];
...
_compile = function (defs, args) { defs.ResultSet = ResultSet; var blocks = this.blocks.map(function (param) { var js = param.node._compile(defs, args); if (param.visible) { return 'results.push(' + js + ');'; } else { return js + ';'; } }); return '(function () {' + 'var results = [];' + blocks.join('') + 'return new ResultSet(results);' + '})()'; }
...
* @return {string} js
* @private
*/
AccessorNode.prototype._compile = function (defs, args) {
defs.access = access;
defs.getSafeProperty = getSafeProperty;
var object = this.object._compile(defs, args);
var index = this.index._compile(defs, args);
if (this.index.isObjectProperty()) {
var prop = this.index.getObjectProperty();
return 'getSafeProperty(' + object + ', "' + prop + '")';
}
else if (this.index.needsSize()) {
...
_toString = function (options) { return this.blocks.map(function (param) { return param.node.toString(options) + (param.visible ? '' : ';'); }).join('\n'); }
...
}
}
if (typeof customString !== 'undefined') {
return customString;
}
return this._toString(options);
};
/**
* Internal function to generate the string output.
* This has to be implemented by every Node
*
* @throws {Error}
...
_toTex = function (options) { return this.blocks.map(function (param) { return param.node.toTex(options) + (param.visible ? '' : ';'); }).join('\\;\\;\n'); }
...
}
}
if (typeof customTex !== 'undefined') {
return customTex;
}
return this._toTex(options);
};
/**
* Internal function to generate the LaTeX output.
* This has to be implemented by every Node
*
* @param {Object} [options]
...
clone = function () { var blocks = this.blocks.map(function (block) { return { node: block.node, visible: block.visible }; }); return new BlockNode(blocks); }
...
return desc;
};
/**
* Export the help object to JSON
*/
Help.prototype.toJSON = function () {
var obj = object.clone(this.doc);
obj.mathjs = 'Help';
return obj;
};
/**
* Instantiate a Help object from a JSON object
* @param {Object} json
...
forEach = function (callback) { for (var i = 0; i < this.blocks.length; i++) { callback(this.blocks[i].node, 'blocks[' + i + '].node', this); } }
...
if (def.indexOf(keyword) == 0) {
matches.push(def);
}
}
}
// commandline keywords
['exit', 'quit', 'clear'].forEach(function (cmd) {
if (cmd.indexOf(keyword) == 0) {
matches.push(cmd);
}
});
// math functions and constants
var ignore = ['expr', 'type'];
...
map = function (callback) { var blocks = []; for (var i = 0; i < this.blocks.length; i++) { var block = this.blocks[i]; var node = this._ifNode(callback(block.node, 'blocks[' + i + '].node', this)); blocks[i] = { node: node, visible: block.visible }; } return new BlockNode(blocks); }
...
if (res && res.isResultSet) {
// we can have 0 or 1 results in the ResultSet, as the CLI
// does not allow multiple expressions separated by a return
res = res.entries[0];
node = node.blocks
.filter(function (entry) { return entry.visible; })
.map(function (entry) { return entry.node })[0];
}
if (node) {
if (node.isAssignmentNode) {
var name = findSymbolName(node);
if (name != null) {
scope.ans = scope[name];
...
_compile = function (defs, args) {
/**
* Test whether a condition is met
* @param {*} condition
* @returns {boolean} true if condition is true or non-zero, else false
*/
defs.testCondition = function (condition) {
if (typeof condition === 'number'
|| typeof condition === 'boolean'
|| typeof condition === 'string') {
return condition ? true : false;
}
if (condition) {
if (condition.isBigNumber === true) {
return condition.isZero() ? false : true;
}
if (condition.isComplex === true) {
return (condition.re || condition.im) ? true : false;
}
if (condition.isUnit === true) {
return condition.value ? true : false;
}
}
if (condition === null || condition === undefined) {
return false;
}
throw new TypeError('Unsupported type of condition "' + defs.math['typeof'](condition) + '"');
};
return (
'testCondition(' + this.condition._compile(defs, args) + ') ? ' +
'( ' + this.trueExpr._compile(defs, args) + ') : ' +
'( ' + this.falseExpr._compile(defs, args) + ')'
);
}
...
* @return {string} js
* @private
*/
AccessorNode.prototype._compile = function (defs, args) {
defs.access = access;
defs.getSafeProperty = getSafeProperty;
var object = this.object._compile(defs, args);
var index = this.index._compile(defs, args);
if (this.index.isObjectProperty()) {
var prop = this.index.getObjectProperty();
return 'getSafeProperty(' + object + ', "' + prop + '")';
}
else if (this.index.needsSize()) {
...
_toString = function (options) { var parenthesis = (options && options.parenthesis) ? options.parenthesis : 'keep'; var precedence = operators.getPrecedence(this, parenthesis); //Enclose Arguments in parentheses if they are an OperatorNode //or have lower or equal precedence //NOTE: enclosing all OperatorNodes in parentheses is a decision //purely based on aesthetics and readability var condition = this.condition.toString(options); var conditionPrecedence = operators.getPrecedence(this.condition, parenthesis); if ((parenthesis === 'all') || (this.condition.type === 'OperatorNode') || ((conditionPrecedence !== null) && (conditionPrecedence <= precedence))) { condition = '(' + condition + ')'; } var trueExpr = this.trueExpr.toString(options); var truePrecedence = operators.getPrecedence(this.trueExpr, parenthesis); if ((parenthesis === 'all') || (this.trueExpr.type === 'OperatorNode') || ((truePrecedence !== null) && (truePrecedence <= precedence))) { trueExpr = '(' + trueExpr + ')'; } var falseExpr = this.falseExpr.toString(options); var falsePrecedence = operators.getPrecedence(this.falseExpr, parenthesis); if ((parenthesis === 'all') || (this.falseExpr.type === 'OperatorNode') || ((falsePrecedence !== null) && (falsePrecedence <= precedence))) { falseExpr = '(' + falseExpr + ')'; } return condition + ' ? ' + trueExpr + ' : ' + falseExpr; }
...
}
}
if (typeof customString !== 'undefined') {
return customString;
}
return this._toString(options);
};
/**
* Internal function to generate the string output.
* This has to be implemented by every Node
*
* @throws {Error}
...
_toTex = function (options) { return '\\begin{cases} {' + this.trueExpr.toTex(options) + '}, &\\quad{\\text{if }\\;' + this.condition.toTex(options) + '}\\\\{' + this.falseExpr.toTex(options) + '}, &\\quad{\\text{otherwise}}\\end{cases}'; }
...
}
}
if (typeof customTex !== 'undefined') {
return customTex;
}
return this._toTex(options);
};
/**
* Internal function to generate the LaTeX output.
* This has to be implemented by every Node
*
* @param {Object} [options]
...
clone = function () { return new ConditionalNode(this.condition, this.trueExpr, this.falseExpr); }
...
return desc;
};
/**
* Export the help object to JSON
*/
Help.prototype.toJSON = function () {
var obj = object.clone(this.doc);
obj.mathjs = 'Help';
return obj;
};
/**
* Instantiate a Help object from a JSON object
* @param {Object} json
...
forEach = function (callback) { callback(this.condition, 'condition', this); callback(this.trueExpr, 'trueExpr', this); callback(this.falseExpr, 'falseExpr', this); }
...
if (def.indexOf(keyword) == 0) {
matches.push(def);
}
}
}
// commandline keywords
['exit', 'quit', 'clear'].forEach(function (cmd) {
if (cmd.indexOf(keyword) == 0) {
matches.push(cmd);
}
});
// math functions and constants
var ignore = ['expr', 'type'];
...
map = function (callback) { return new ConditionalNode( this._ifNode(callback(this.condition, 'condition', this)), this._ifNode(callback(this.trueExpr, 'trueExpr', this)), this._ifNode(callback(this.falseExpr, 'falseExpr', this)) ); }
...
if (res && res.isResultSet) {
// we can have 0 or 1 results in the ResultSet, as the CLI
// does not allow multiple expressions separated by a return
res = res.entries[0];
node = node.blocks
.filter(function (entry) { return entry.visible; })
.map(function (entry) { return entry.node })[0];
}
if (node) {
if (node.isAssignmentNode) {
var name = findSymbolName(node);
if (name != null) {
scope.ans = scope[name];
...
_compile = function (defs, args) { switch (this.valueType) { case 'number': // TODO: replace this with using config.number var numConfig = defs.math.config().number; if (numConfig === 'BigNumber') { return 'math.bignumber("' + this.value + '")'; } else if (numConfig === 'Fraction') { return 'math.fraction("' + this.value + '")'; } else { // remove leading zeros like '003.2' which are not allowed by JavaScript return this.value.replace(/^(0*)[0-9]/, function (match, zeros) { return match.substring(zeros.length); }); } case 'string': return '"' + this.value + '"'; case 'boolean': return this.value; case 'undefined': return this.value; case 'null': return this.value; default: // TODO: move this error to the constructor? throw new TypeError('Unsupported type of constant "' + this.valueType + '"'); } }
...
* @return {string} js
* @private
*/
AccessorNode.prototype._compile = function (defs, args) {
defs.access = access;
defs.getSafeProperty = getSafeProperty;
var object = this.object._compile(defs, args);
var index = this.index._compile(defs, args);
if (this.index.isObjectProperty()) {
var prop = this.index.getObjectProperty();
return 'getSafeProperty(' + object + ', "' + prop + '")';
}
else if (this.index.needsSize()) {
...
_toString = function (options) { switch (this.valueType) { case 'string': return '"' + this.value + '"'; default: return this.value; } }
...
}
}
if (typeof customString !== 'undefined') {
return customString;
}
return this._toString(options);
};
/**
* Internal function to generate the string output.
* This has to be implemented by every Node
*
* @throws {Error}
...
_toTex = function (options) { var value = this.value, index; switch (this.valueType) { case 'string': return '\\mathtt{"' + value + '"}'; case 'number': index = value.toLowerCase().indexOf('e'); if (index !== -1) { return value.substring(0, index) + '\\cdot10^{' + value.substring(index + 1) + '}'; } return value; default: return value; } }
...
}
}
if (typeof customTex !== 'undefined') {
return customTex;
}
return this._toTex(options);
};
/**
* Internal function to generate the LaTeX output.
* This has to be implemented by every Node
*
* @param {Object} [options]
...
clone = function () { return new ConstantNode(this.value, this.valueType); }
...
return desc;
};
/**
* Export the help object to JSON
*/
Help.prototype.toJSON = function () {
var obj = object.clone(this.doc);
obj.mathjs = 'Help';
return obj;
};
/**
* Instantiate a Help object from a JSON object
* @param {Object} json
...
forEach = function (callback) { // nothing to do, we don't have childs }
...
if (def.indexOf(keyword) == 0) {
matches.push(def);
}
}
}
// commandline keywords
['exit', 'quit', 'clear'].forEach(function (cmd) {
if (cmd.indexOf(keyword) == 0) {
matches.push(cmd);
}
});
// math functions and constants
var ignore = ['expr', 'type'];
...
map = function (callback) { return this.clone(); }
...
if (res && res.isResultSet) {
// we can have 0 or 1 results in the ResultSet, as the CLI
// does not allow multiple expressions separated by a return
res = res.entries[0];
node = node.blocks
.filter(function (entry) { return entry.visible; })
.map(function (entry) { return entry.node })[0];
}
if (node) {
if (node.isAssignmentNode) {
var name = findSymbolName(node);
if (name != null) {
scope.ans = scope[name];
...
_compile = function (defs, args) { defs.typed = typed; defs.setSafeProperty = setSafeProperty; // we extend the original args and add the args to the child object var childArgs = Object.create(args); this.params.forEach(function (variable) { childArgs[variable] = true; }); // compile the function expression with the child args var jsExpr = this.expr._compile(defs, childArgs); return 'setSafeProperty(scope, "' + this.name + '", ' + ' (function () {' + ' var fn = typed("' + this.name + '", {' + ' "' + this.types.join(',') + '": function (' + this.params.join(',') + ') {' + ' return ' + jsExpr + '' + ' }' + ' });' + ' fn.syntax = "' + this.name + '(' + this.params.join(', ') + ')";' + ' return fn;' + ' })())'; }
...
* @return {string} js
* @private
*/
AccessorNode.prototype._compile = function (defs, args) {
defs.access = access;
defs.getSafeProperty = getSafeProperty;
var object = this.object._compile(defs, args);
var index = this.index._compile(defs, args);
if (this.index.isObjectProperty()) {
var prop = this.index.getObjectProperty();
return 'getSafeProperty(' + object + ', "' + prop + '")';
}
else if (this.index.needsSize()) {
...
_toString = function (options) { var parenthesis = (options && options.parenthesis) ? options.parenthesis : 'keep'; var expr = this.expr.toString(options); if (needParenthesis(this, parenthesis)) { expr = '(' + expr + ')'; } return this.name + '(' + this.params.join(', ') + ') = ' + expr; }
...
}
}
if (typeof customString !== 'undefined') {
return customString;
}
return this._toString(options);
};
/**
* Internal function to generate the string output.
* This has to be implemented by every Node
*
* @throws {Error}
...
_toTex = function (options) { var parenthesis = (options && options.parenthesis) ? options.parenthesis : 'keep'; var expr = this.expr.toTex(options); if (needParenthesis(this, parenthesis)) { expr = '\\left(' + expr + '\\right)'; } return '\\mathrm{' + this.name + '}\\left(' + this.params.map(latex.toSymbol).join(',') + '\\right):=' + expr; }
...
}
}
if (typeof customTex !== 'undefined') {
return customTex;
}
return this._toTex(options);
};
/**
* Internal function to generate the LaTeX output.
* This has to be implemented by every Node
*
* @param {Object} [options]
...
clone = function () { return new FunctionAssignmentNode(this.name, this.params.slice(0), this.expr); }
...
return desc;
};
/**
* Export the help object to JSON
*/
Help.prototype.toJSON = function () {
var obj = object.clone(this.doc);
obj.mathjs = 'Help';
return obj;
};
/**
* Instantiate a Help object from a JSON object
* @param {Object} json
...
forEach = function (callback) { callback(this.expr, 'expr', this); }
...
if (def.indexOf(keyword) == 0) {
matches.push(def);
}
}
}
// commandline keywords
['exit', 'quit', 'clear'].forEach(function (cmd) {
if (cmd.indexOf(keyword) == 0) {
matches.push(cmd);
}
});
// math functions and constants
var ignore = ['expr', 'type'];
...
map = function (callback) { var expr = this._ifNode(callback(this.expr, 'expr', this)); return new FunctionAssignmentNode(this.name, this.params.slice(0), expr); }
...
if (res && res.isResultSet) {
// we can have 0 or 1 results in the ResultSet, as the CLI
// does not allow multiple expressions separated by a return
res = res.entries[0];
node = node.blocks
.filter(function (entry) { return entry.visible; })
.map(function (entry) { return entry.node })[0];
}
if (node) {
if (node.isAssignmentNode) {
var name = findSymbolName(node);
if (name != null) {
scope.ans = scope[name];
...
_compile = function (defs, args) { // compile fn and arguments var jsFn = this.fn._compile(defs, args); var jsArgs = this.args.map(function (arg) { return arg._compile(defs, args); }); var jsScope = this._compileScope(defs, args); var argsName; if (this.fn.isSymbolNode) { // we can statically determine whether the function has an rawArgs property var name = this.fn.name; var fn = defs.math[name]; var isRaw = (typeof fn === 'function') && (fn.rawArgs == true); if (isRaw) { // pass unevaluated parameters (nodes) to the function argsName = this._getUniqueArgumentsName(defs); defs[argsName] = this.args; return jsFn + '(' + argsName + ', math, ' + jsScope + ')'; } else { // "regular" evaluation return jsFn + '(' + jsArgs.join(', ') + ')'; } } else if (this.fn.isAccessorNode && this.fn.index.isObjectProperty()) { // execute the function with the right context: the object of the AccessorNode argsName = this._getUniqueArgumentsName(defs); defs[argsName] = this.args; defs.validateSafeMethod = validateSafeMethod var jsObject = this.fn.object._compile(defs, args); var prop = this.fn.index.getObjectProperty(); return '(function () {' + 'var object = ' + jsObject + ';' + 'validateSafeMethod(object, "' + prop + '");' + 'return (object["' + prop + '"] && object["' + prop + '"].rawArgs) ' + ' ? object["' + prop + '"](' + argsName + ', math, ' + jsScope + ')' + ' : object["' + prop + '"](' + jsArgs.join(', ') + ')' + '})()'; } else { // this.fn.isAccessorNode && !this.fn.index.isObjectProperty() // we have to dynamically determine whether the function has a rawArgs property argsName = this._getUniqueArgumentsName(defs); defs[argsName] = this.args; return '(function () {' + 'var fn = ' + jsFn + ';' + 'return (fn && fn.rawArgs) ' + ' ? fn(' + argsName + ', math, ' + jsScope + ')' + ' : fn(' + jsArgs.join(', ') + ')' + '})()'; } }
...
* @return {string} js
* @private
*/
AccessorNode.prototype._compile = function (defs, args) {
defs.access = access;
defs.getSafeProperty = getSafeProperty;
var object = this.object._compile(defs, args);
var index = this.index._compile(defs, args);
if (this.index.isObjectProperty()) {
var prop = this.index.getObjectProperty();
return 'getSafeProperty(' + object + ', "' + prop + '")';
}
else if (this.index.needsSize()) {
...
_compileScope = function (defs, args) { var names = Object.keys(args); if (names.length === 0) { return 'scope'; } else { // merge arguments into scope defs.extend = extend; var jsArgs = names .map(function (arg) { return '"' + arg + '": ' + arg; }) .join(', '); return 'extend(extend({}, scope), {' + jsArgs + '})'; } }
...
*/
FunctionNode.prototype._compile = function (defs, args) {
// compile fn and arguments
var jsFn = this.fn._compile(defs, args);
var jsArgs = this.args.map(function (arg) {
return arg._compile(defs, args);
});
var jsScope = this._compileScope(defs, args);
var argsName;
if (this.fn.isSymbolNode) {
// we can statically determine whether the function has an rawArgs property
var name = this.fn.name;
var fn = defs.math[name];
var isRaw = (typeof fn === 'function') && (fn.rawArgs == true);
...
_getUniqueArgumentsName = function (defs) { var argsName; var i = 0; do { argsName = 'args' + i; i++; } while (argsName in defs); return argsName; }
...
// we can statically determine whether the function has an rawArgs property
var name = this.fn.name;
var fn = defs.math[name];
var isRaw = (typeof fn === 'function') && (fn.rawArgs == true);
if (isRaw) {
// pass unevaluated parameters (nodes) to the function
argsName = this._getUniqueArgumentsName(defs);
defs[argsName] = this.args;
return jsFn + '(' + argsName + ', math, ' + jsScope + ')';
}
else {
// "regular" evaluation
return jsFn + '(' + jsArgs.join(', ') + ')';
...
_toString = function (options) { var args = this.args.map(function (arg) { return arg.toString(options); }); // format the arguments like "add(2, 4.2)" return this.fn.toString(options) + '(' + args.join(', ') + ')'; }
...
}
}
if (typeof customString !== 'undefined') {
return customString;
}
return this._toString(options);
};
/**
* Internal function to generate the string output.
* This has to be implemented by every Node
*
* @throws {Error}
...
_toTex = function (options) { var args = this.args.map(function (arg) { //get LaTeX of the arguments return arg.toTex(options); }); var latexConverter; if (math[this.name] && ((typeof math[this.name].toTex === 'function') || (typeof math[this.name].toTex === 'object') || (typeof math[this.name].toTex === 'string'))) { //.toTex is a callback function latexConverter = math[this.name].toTex; } var customToTex; switch (typeof latexConverter) { case 'function': //a callback function customToTex = latexConverter(this, options); break; case 'string': //a template string customToTex = expandTemplate(latexConverter, this, options); break; case 'object': //an object with different "converters" for different numbers of arguments switch (typeof latexConverter[args.length]) { case 'function': customToTex = latexConverter[args.length](this, options); break; case 'string': customToTex = expandTemplate(latexConverter[args.length], this, options); break; } } if (typeof customToTex !== 'undefined') { return customToTex; } return expandTemplate(latex.defaultTemplate, this, options); }
...
}
}
if (typeof customTex !== 'undefined') {
return customTex;
}
return this._toTex(options);
};
/**
* Internal function to generate the LaTeX output.
* This has to be implemented by every Node
*
* @param {Object} [options]
...
clone = function () { return new FunctionNode(this.fn, this.args.slice(0)); }
...
return desc;
};
/**
* Export the help object to JSON
*/
Help.prototype.toJSON = function () {
var obj = object.clone(this.doc);
obj.mathjs = 'Help';
return obj;
};
/**
* Instantiate a Help object from a JSON object
* @param {Object} json
...
forEach = function (callback) { for (var i = 0; i < this.args.length; i++) { callback(this.args[i], 'args[' + i + ']', this); } }
...
if (def.indexOf(keyword) == 0) {
matches.push(def);
}
}
}
// commandline keywords
['exit', 'quit', 'clear'].forEach(function (cmd) {
if (cmd.indexOf(keyword) == 0) {
matches.push(cmd);
}
});
// math functions and constants
var ignore = ['expr', 'type'];
...
getIdentifier = function () { return this.type + ':' + this.name; }
...
*/
function getPrecedence (_node, parenthesis) {
var node = _node;
if (parenthesis !== 'keep') {
//ParenthesisNodes are only ignored when not in 'keep' mode
node = _node.getContent();
}
var identifier = node.getIdentifier();
for (var i = 0; i < properties.length; i++) {
if (identifier in properties[i]) {
return i;
}
}
return null;
}
...
map = function (callback) { var fn = this.fn.map(callback); var args = []; for (var i = 0; i < this.args.length; i++) { args[i] = this._ifNode(callback(this.args[i], 'args[' + i + ']', this)); } return new FunctionNode(fn, args); }
...
if (res && res.isResultSet) {
// we can have 0 or 1 results in the ResultSet, as the CLI
// does not allow multiple expressions separated by a return
res = res.entries[0];
node = node.blocks
.filter(function (entry) { return entry.visible; })
.map(function (entry) { return entry.node })[0];
}
if (node) {
if (node.isAssignmentNode) {
var name = findSymbolName(node);
if (name != null) {
scope.ans = scope[name];
...
toString = function (options) { var customString; var name = this.fn.toString(options); if (options && (typeof options.handler === 'object') && options.handler.hasOwnProperty(name)) { //callback is a map of callback functions customString = options.handler[name](this, options); } if (typeof customString !== 'undefined') { return customString; } //fall back to Node's toString return nodeToString.call(this, options); }
...
}
else {
scope.ans = res;
console.log(format(res));
}
}
else if (res instanceof math.type.Help) {
console.log(res.toString());
}
else {
scope.ans = res;
console.log(format(res));
}
}
}
...
toTex = function (options) { var customTex; if (options && (typeof options.handler === 'object') && options.handler.hasOwnProperty(this.name)) { //callback is a map of callback functions customTex = options.handler[this.name](this, options); } if (typeof customTex !== 'undefined') { return customTex; } //fall back to Node's toTex return nodeToTex.call(this, options); }
...
catch (err) {
console.log(err.toString());
}
break;
case 'tex':
try {
var tex = math.parse(expr).toTex({parenthesis: parenthesis});
console.log(tex);
}
catch (err) {
console.log(err.toString());
}
break;
}
...
_compile = function (defs, args) { // args can be mutated by IndexNode, when dimensions use `end` var childArgs = Object.create(args); // helper function to create a Range from start, step and end defs.range = function (start, end, step) { return new Range( (start && start.isBigNumber === true) ? start.toNumber() : start, (end && end.isBigNumber === true) ? end.toNumber() : end, (step && step.isBigNumber === true) ? step.toNumber() : step ); }; // TODO: implement support for bignumber (currently bignumbers are silently // reduced to numbers when changing the value to zero-based) // TODO: Optimization: when the range values are ConstantNodes, // we can beforehand resolve the zero-based value // optimization for a simple object property var dimensions = this.dimensions.map(function (range, i) { if (range && range.isRangeNode) { if (range.needsEnd()) { childArgs.end = true; // resolve end and create range return '(function () {' + 'var end = size[' + i + ']; ' + 'return range(' + range.start._compile(defs, childArgs) + ', ' + range.end._compile(defs, childArgs) + ', ' + (range.step ? range.step._compile(defs, childArgs) : '1') + '); ' + '})()'; } else { // create range return 'range(' + range.start._compile(defs, childArgs) + ', ' + range.end._compile(defs, childArgs) + ', ' + (range.step ? range.step._compile(defs, childArgs) : '1') + ')'; } } if (range.isSymbolNode && range.name === 'end') { childArgs.end = true; // resolve the parameter 'end' return '(function () {' + 'var end = size[' + i + ']; ' + 'return ' + range._compile(defs, childArgs) + '; ' + '})()' } else { // ConstantNode return range._compile(defs, childArgs); } }); return 'math.index(' + dimensions.join(', ') + ')'; }
...
* @return {string} js
* @private
*/
AccessorNode.prototype._compile = function (defs, args) {
defs.access = access;
defs.getSafeProperty = getSafeProperty;
var object = this.object._compile(defs, args);
var index = this.index._compile(defs, args);
if (this.index.isObjectProperty()) {
var prop = this.index.getObjectProperty();
return 'getSafeProperty(' + object + ', "' + prop + '")';
}
else if (this.index.needsSize()) {
...
_toString = function (options) { // format the parameters like "[1, 0:5]" return this.dotNotation ? ('.' + this.getObjectProperty()) : ('[' + this.dimensions.join(', ') + ']'); }
...
}
}
if (typeof customString !== 'undefined') {
return customString;
}
return this._toString(options);
};
/**
* Internal function to generate the string output.
* This has to be implemented by every Node
*
* @throws {Error}
...
_toTex = function (options) { var dimensions = this.dimensions.map(function (range) { return range.toTex(options); }); return this.dotNotation ? ('.' + this.getObjectProperty() + '') : ('_{' + dimensions.join(',') + '}'); }
...
}
}
if (typeof customTex !== 'undefined') {
return customTex;
}
return this._toTex(options);
};
/**
* Internal function to generate the LaTeX output.
* This has to be implemented by every Node
*
* @param {Object} [options]
...
clone = function () { return new IndexNode(this.dimensions.slice(0)); }
...
return desc;
};
/**
* Export the help object to JSON
*/
Help.prototype.toJSON = function () {
var obj = object.clone(this.doc);
obj.mathjs = 'Help';
return obj;
};
/**
* Instantiate a Help object from a JSON object
* @param {Object} json
...
forEach = function (callback) { for (var i = 0; i < this.dimensions.length; i++) { callback(this.dimensions[i], 'dimensions[' + i + ']', this); } }
...
if (def.indexOf(keyword) == 0) {
matches.push(def);
}
}
}
// commandline keywords
['exit', 'quit', 'clear'].forEach(function (cmd) {
if (cmd.indexOf(keyword) == 0) {
matches.push(cmd);
}
});
// math functions and constants
var ignore = ['expr', 'type'];
...
getObjectProperty = function () { return this.isObjectProperty() ? this.dimensions[0].value : null; }
...
this.index = index;
// readonly property name
Object.defineProperty(this, 'name', {
get: function () {
if (this.index) {
return (this.index.isObjectProperty())
? this.index.getObjectProperty()
: '';
}
else {
return this.object.name || '';
}
}.bind(this),
set: function () {
...
isObjectProperty = function () { return this.dimensions.length === 1 && this.dimensions[0].isConstantNode && this.dimensions[0].valueType === 'string'; }
...
this.object = object || null;
this.index = index;
// readonly property name
Object.defineProperty(this, 'name', {
get: function () {
if (this.index) {
return (this.index.isObjectProperty())
? this.index.getObjectProperty()
: '';
}
else {
return this.object.name || '';
}
}.bind(this),
...
map = function (callback) { var dimensions = []; for (var i = 0; i < this.dimensions.length; i++) { dimensions[i] = this._ifNode(callback(this.dimensions[i], 'dimensions[' + i + ']', this)); } return new IndexNode(dimensions); }
...
if (res && res.isResultSet) {
// we can have 0 or 1 results in the ResultSet, as the CLI
// does not allow multiple expressions separated by a return
res = res.entries[0];
node = node.blocks
.filter(function (entry) { return entry.visible; })
.map(function (entry) { return entry.node })[0];
}
if (node) {
if (node.isAssignmentNode) {
var name = findSymbolName(node);
if (name != null) {
scope.ans = scope[name];
...
needsSize = function () { return this.dimensions.some(function (range) { return (range.isRangeNode && range.needsEnd()) || (range.isSymbolNode && range.name === 'end'); }); }
...
var object = this.object._compile(defs, args);
var index = this.index._compile(defs, args);
if (this.index.isObjectProperty()) {
var prop = this.index.getObjectProperty();
return 'getSafeProperty(' + object + ', "' + prop + '")';
}
else if (this.index.needsSize()) {
// if some parameters use the 'end' parameter, we need to calculate the size
return '(function () {' +
' var object = ' + object + ';' +
' var size = math.size(object).valueOf();' +
' return access(object, ' + index + ');' +
'})()';
}
...
_compile = function (defs, args) { // must be implemented by each of the Node implementations throw new Error('Cannot compile a Node interface'); }
...
* @return {string} js
* @private
*/
AccessorNode.prototype._compile = function (defs, args) {
defs.access = access;
defs.getSafeProperty = getSafeProperty;
var object = this.object._compile(defs, args);
var index = this.index._compile(defs, args);
if (this.index.isObjectProperty()) {
var prop = this.index.getObjectProperty();
return 'getSafeProperty(' + object + ', "' + prop + '")';
}
else if (this.index.needsSize()) {
...
_ifNode = function (node) { if (!(node && node.isNode)) { throw new TypeError('Callback function must return a Node'); } return node; }
...
* Create a new AccessorNode having it's childs be the results of calling
* the provided callback function for each of the childs of the original node.
* @param {function(child: Node, path: string, parent: Node): Node} callback
* @returns {AccessorNode} Returns a transformed copy of the node
*/
AccessorNode.prototype.map = function (callback) {
return new AccessorNode(
this._ifNode(callback(this.object, 'object', this)),
this._ifNode(callback(this.index, 'index', this))
);
};
/**
* Create a clone of this node, a shallow copy
* @return {AccessorNode}
...
_toString = function () { //must be implemented by each of the Node implementations throw new Error('_toString not implemented for ' + this.type); }
...
}
}
if (typeof customString !== 'undefined') {
return customString;
}
return this._toString(options);
};
/**
* Internal function to generate the string output.
* This has to be implemented by every Node
*
* @throws {Error}
...
_toTex = function (options) { //must be implemented by each of the Node implementations throw new Error('_toTex not implemented for ' + this.type); }
...
}
}
if (typeof customTex !== 'undefined') {
return customTex;
}
return this._toTex(options);
};
/**
* Internal function to generate the LaTeX output.
* This has to be implemented by every Node
*
* @param {Object} [options]
...
clone = function () { // must be implemented by each of the Node implementations throw new Error('Cannot clone a Node interface'); }
...
return desc;
};
/**
* Export the help object to JSON
*/
Help.prototype.toJSON = function () {
var obj = object.clone(this.doc);
obj.mathjs = 'Help';
return obj;
};
/**
* Instantiate a Help object from a JSON object
* @param {Object} json
...
cloneDeep = function () { return this.map(function (node) { return node.cloneDeep(); }); }
...
/**
* Create a deep clone of this node
* @return {Node}
*/
Node.prototype.cloneDeep = function () {
return this.map(function (node) {
return node.cloneDeep();
});
};
/**
* Deep compare this node with another node.
* @param {Node} other
* @return {boolean} Returns true when both nodes are of the same type and
...
compile = function () { // TODO: calling compile(math) is deprecated since version 2.0.0. Remove this warning some day if (arguments.length > 0) { throw new Error('Calling compile(math) is deprecated. Call the function as compile() instead.'); } // definitions globally available inside the closure of the compiled expressions var defs = { math: math.expression.mathWithTransform, args: {}, // can be filled with names of FunctionAssignment arguments _validateScope: _validateScope }; // will be used to put local function arguments var args = {}; var code = this._compile(defs, args); var defsCode = Object.keys(defs).map(function (name) { return ' var ' + name + ' = defs["' + name + '"];'; }); var factoryCode = defsCode.join(' ') + 'return {' + ' "eval": function (scope) {' + ' if (scope) _validateScope(scope);' + ' scope = scope || {};' + ' return ' + code + ';' + ' }' + '};'; var factory = new Function('defs', factoryCode); return factory(defs); }
...
* parse(expr, options)
* parse([expr1, expr2, expr3, ...])
* parse([expr1, expr2, expr3, ...], options)
*
* Example:
*
* var node = parse('sqrt(3^2 + 4^2)');
* node.compile(math).eval(); // 5
*
* var scope = {a:3, b:4}
* var node = parse('a * b'); // 12
* var code = node.compile(math);
* code.eval(scope); // 12
* scope.a = 5;
* code.eval(scope); // 20
...
equals = function (other) { return other ? deepEqual(this, other) : false }
...
if (inv) {
root = root.neg();
}
if (root.isZero()) {
throw new Error('Root must be non-zero');
}
if (a.isNegative() && !root.abs().mod(2).equals(1)) {
throw new Error('Root must be odd when a is negative.');
}
// edge cases zero and infinity
if (a.isZero()) {
return inv ? new Big(Infinity) : 0;
}
...
eval = function (scope) { return this.compile().eval(scope); }
...
math.atan2(3, -3) / math.pi; // 0.75
math.log(1000, 10); // 3
math.sqrt(-4); // 2i
math.pow([[-1, 2], [3, 1]], 2); // [[7, 0], [0, 7]]
math.derivative('x^2 + x', 'x'); // 2 * x + 1
// expressions
math.eval('12 / (2.3 + 0.7)'); // 4
math.eval('5.08 cm to inch'); // 2 inch
math.eval('sin(45 deg) ^ 2'); // 0.5
math.eval('9 / 3 + 2i'); // 3 + 2i
math.eval('det([-1, 2; 3, 1])'); // -7
// chaining
math.chain(3)
...
filter = function (callback) { var nodes = []; this.traverse(function (node, path, parent) { if (callback(node, path, parent)) { nodes.push(node); } }); return nodes; }
...
}
}
}
}
}
// remove duplicates
matches = matches.filter(function(elem, pos, arr) {
return arr.indexOf(elem) == pos;
});
}
return [matches, keyword];
}
...
find = function () { throw new Error('Function Node.find is deprecated. Use Node.filter instead.'); }
...
var mf = multiplyScalar;
// process data types
if (adt && bdt && adt === bdt && typeof adt === 'string') {
// datatype
dt = adt;
// find signatures that matches (dt, dt)
af = typed.find(addScalar, [dt, dt]);
mf = typed.find(multiplyScalar, [dt, dt]);
}
// result (do not initialize it with zero)
var c = mf(adata[0], bdata[0]);
// loop data
for (var i = 1; i < n; i++) {
...
forEach = function (callback) { // must be implemented by each of the Node implementations throw new Error('Cannot run forEach on a Node interface'); }
...
if (def.indexOf(keyword) == 0) {
matches.push(def);
}
}
}
// commandline keywords
['exit', 'quit', 'clear'].forEach(function (cmd) {
if (cmd.indexOf(keyword) == 0) {
matches.push(cmd);
}
});
// math functions and constants
var ignore = ['expr', 'type'];
...
getContent = function () { return this; }
...
* @param {string} parenthesis
* @return {number|null}
*/
function getPrecedence (_node, parenthesis) {
var node = _node;
if (parenthesis !== 'keep') {
//ParenthesisNodes are only ignored when not in 'keep' mode
node = _node.getContent();
}
var identifier = node.getIdentifier();
for (var i = 0; i < properties.length; i++) {
if (identifier in properties[i]) {
return i;
}
}
...
getIdentifier = function () { return this.type; }
...
*/
function getPrecedence (_node, parenthesis) {
var node = _node;
if (parenthesis !== 'keep') {
//ParenthesisNodes are only ignored when not in 'keep' mode
node = _node.getContent();
}
var identifier = node.getIdentifier();
for (var i = 0; i < properties.length; i++) {
if (identifier in properties[i]) {
return i;
}
}
return null;
}
...
map = function (callback) { // must be implemented by each of the Node implementations throw new Error('Cannot run map on a Node interface'); }
...
if (res && res.isResultSet) {
// we can have 0 or 1 results in the ResultSet, as the CLI
// does not allow multiple expressions separated by a return
res = res.entries[0];
node = node.blocks
.filter(function (entry) { return entry.visible; })
.map(function (entry) { return entry.node })[0];
}
if (node) {
if (node.isAssignmentNode) {
var name = findSymbolName(node);
if (name != null) {
scope.ans = scope[name];
...
match = function () { throw new Error('Function Node.match is deprecated. See functions Node.filter, Node.transform, Node.traverse.'); }
...
* @param {function} fn A typed function
* @return {number} Returns the maximum number of expected arguments.
* Returns -1 when no signatures where found on the function.
*/
exports.maxArgumentCount = function (fn) {
return Object.keys(fn.signatures || {})
.reduce(function (args, signature) {
var count = (signature.match(/,/g) || []).length + 1;
return Math.max(args, count);
}, -1);
};
...
toString = function (options) { var customString; if (options && typeof options == "object") { switch (typeof options.handler) { case 'object': case 'undefined': break; case 'function': customString = options.handler(this, options); break; default: throw new TypeError('Object or function expected as callback'); } } if (typeof customString !== 'undefined') { return customString; } return this._toString(options); }
...
}
else {
scope.ans = res;
console.log(format(res));
}
}
else if (res instanceof math.type.Help) {
console.log(res.toString());
}
else {
scope.ans = res;
console.log(format(res));
}
}
}
...
toTex = function (options) { var customTex; if (options && typeof options == 'object') { switch (typeof options.handler) { case 'object': case 'undefined': break; case 'function': customTex = options.handler(this, options); break; default: throw new TypeError('Object or function expected as callback'); } } if (typeof customTex !== 'undefined') { return customTex; } return this._toTex(options); }
...
catch (err) {
console.log(err.toString());
}
break;
case 'tex':
try {
var tex = math.parse(expr).toTex({parenthesis: parenthesis});
console.log(tex);
}
catch (err) {
console.log(err.toString());
}
break;
}
...
transform = function (callback) { // traverse over all childs function _transform (node, callback) { return node.map(function(child, path, parent) { var replacement = callback(child, path, parent); return _transform(replacement, callback); }); } var replacement = callback(this, null, null); return _transform(replacement, callback); }
...
/**
* Recursively transform a node tree via a transform function.
*
* For example, to replace all nodes of type SymbolNode having name 'x' with a
* ConstantNode with value 2:
*
* var res = Node.transform(function (node, path, parent) {
* if (node && node.isSymbolNode) && (node.name == 'x')) {
* return new ConstantNode(2);
* }
* else {
* return node;
* }
* });
...
traverse = function (callback) { // execute callback for itself callback(this, null, null); // recursively traverse over all childs of a node function _traverse(node, callback) { node.forEach(function (child, path, parent) { callback(child, path, parent); _traverse(child, callback); }); } _traverse(this, callback); }
...
* otherwise. Function signature:
* callback(node: Node, index: string, parent: Node) : boolean
* @return {Node[]} nodes An array with nodes matching given filter criteria
*/
Node.prototype.filter = function (callback) {
var nodes = [];
this.traverse(function (node, path, parent) {
if (callback(node, path, parent)) {
nodes.push(node);
}
});
return nodes;
};
...
_compile = function (defs, args) { var entries = []; for (var key in this.properties) { if (this.properties.hasOwnProperty(key)) { entries.push('"' + key + '": ' + this.properties[key]._compile(defs, args)); } } return '{' + entries.join(', ') + '}'; }
...
* @return {string} js
* @private
*/
AccessorNode.prototype._compile = function (defs, args) {
defs.access = access;
defs.getSafeProperty = getSafeProperty;
var object = this.object._compile(defs, args);
var index = this.index._compile(defs, args);
if (this.index.isObjectProperty()) {
var prop = this.index.getObjectProperty();
return 'getSafeProperty(' + object + ', "' + prop + '")';
}
else if (this.index.needsSize()) {
...
_toString = function (options) { var entries = []; for (var key in this.properties) { if (this.properties.hasOwnProperty(key)) { entries.push('"' + key + '": ' + this.properties[key].toString(options)); } } return '{' + entries.join(', ') + '}'; }
...
}
}
if (typeof customString !== 'undefined') {
return customString;
}
return this._toString(options);
};
/**
* Internal function to generate the string output.
* This has to be implemented by every Node
*
* @throws {Error}
...
_toTex = function (options) { var entries = []; for (var key in this.properties) { if (this.properties.hasOwnProperty(key)) { entries.push("\\mathbf{" + key + ':} & ' + this.properties[key].toTex(options) + "\\\\"); } } return '\\left\\{\\begin{array}{ll}' + entries.join('\n') + '\\end{array}\\right\\}'; }
...
}
}
if (typeof customTex !== 'undefined') {
return customTex;
}
return this._toTex(options);
};
/**
* Internal function to generate the LaTeX output.
* This has to be implemented by every Node
*
* @param {Object} [options]
...
clone = function () { var properties = {}; for (var key in this.properties) { if (this.properties.hasOwnProperty(key)) { properties[key] = this.properties[key]; } } return new ObjectNode(properties); }
...
return desc;
};
/**
* Export the help object to JSON
*/
Help.prototype.toJSON = function () {
var obj = object.clone(this.doc);
obj.mathjs = 'Help';
return obj;
};
/**
* Instantiate a Help object from a JSON object
* @param {Object} json
...
forEach = function (callback) { for (var key in this.properties) { if (this.properties.hasOwnProperty(key)) { callback(this.properties[key], 'properties["' + key + '"]', this); } } }
...
if (def.indexOf(keyword) == 0) {
matches.push(def);
}
}
}
// commandline keywords
['exit', 'quit', 'clear'].forEach(function (cmd) {
if (cmd.indexOf(keyword) == 0) {
matches.push(cmd);
}
});
// math functions and constants
var ignore = ['expr', 'type'];
...
map = function (callback) { var properties = {}; for (var key in this.properties) { if (this.properties.hasOwnProperty(key)) { properties[key] = this._ifNode(callback(this.properties[key], 'properties["' + key + '"]', this)); } } return new ObjectNode(properties); }
...
if (res && res.isResultSet) {
// we can have 0 or 1 results in the ResultSet, as the CLI
// does not allow multiple expressions separated by a return
res = res.entries[0];
node = node.blocks
.filter(function (entry) { return entry.visible; })
.map(function (entry) { return entry.node })[0];
}
if (node) {
if (node.isAssignmentNode) {
var name = findSymbolName(node);
if (name != null) {
scope.ans = scope[name];
...
_compile = function (defs, args) { if (!defs.math[this.fn]) { throw new Error('Function ' + this.fn + ' missing in provided namespace "math"'); } var jsArgs = this.args.map(function (arg) { return arg._compile(defs, args); }); return 'math.' + this.fn + '(' + jsArgs.join(', ') + ')'; }
...
* @return {string} js
* @private
*/
AccessorNode.prototype._compile = function (defs, args) {
defs.access = access;
defs.getSafeProperty = getSafeProperty;
var object = this.object._compile(defs, args);
var index = this.index._compile(defs, args);
if (this.index.isObjectProperty()) {
var prop = this.index.getObjectProperty();
return 'getSafeProperty(' + object + ', "' + prop + '")';
}
else if (this.index.needsSize()) {
...
_toString = function (options) { var parenthesis = (options && options.parenthesis) ? options.parenthesis : 'keep'; var implicit = (options && options.implicit) ? options.implicit : 'hide'; var args = this.args; var parens = calculateNecessaryParentheses(this, parenthesis, args, false); if (args.length === 1) { //unary operators var assoc = operators.getAssociativity(this, parenthesis); var operand = args[0].toString(options); if (parens[0]) { operand = '(' + operand + ')'; } if (assoc === 'right') { //prefix operator return this.op + operand; } else if (assoc === 'left') { //postfix return operand + this.op; } //fall back to postfix return operand + this.op; } else if (args.length == 2) { var lhs = args[0].toString(options); //left hand side var rhs = args[1].toString(options); //right hand side if (parens[0]) { //left hand side in parenthesis? lhs = '(' + lhs + ')'; } if (parens[1]) { //right hand side in parenthesis? rhs = '(' + rhs + ')'; } if (this.implicit && (this.getIdentifier() === 'OperatorNode:multiply') && (implicit == 'hide')) { return lhs + ' ' + rhs; } return lhs + ' ' + this.op + ' ' + rhs; } else if ((args.length > 2) && ((this.getIdentifier() === 'OperatorNode:add') || (this.getIdentifier() === 'OperatorNode:multiply '))) { var stringifiedArgs = args.map(function (arg, index) { arg = arg.toString(options); if (parens[index]) { //put in parenthesis? arg = '(' + arg + ')'; } return arg; }); if (this.implicit && (this.getIdentifier() === 'OperatorNode:multiply') && (implicit === 'hide')) { return stringifiedArgs.join(' '); } return stringifiedArgs.join(' ' + this.op + ' '); } else { //fallback to formatting as a function call return this.fn + '(' + this.args.join(', ') + ')'; } }
...
}
}
if (typeof customString !== 'undefined') {
return customString;
}
return this._toString(options);
};
/**
* Internal function to generate the string output.
* This has to be implemented by every Node
*
* @throws {Error}
...
_toTex = function (options) { var parenthesis = (options && options.parenthesis) ? options.parenthesis : 'keep'; var implicit = (options && options.implicit) ? options.implicit : 'hide'; var args = this.args; var parens = calculateNecessaryParentheses(this, parenthesis, args, true); var op = latex.operators[this.fn]; op = typeof op === 'undefined' ? this.op : op; //fall back to using this.op if (args.length === 1) { //unary operators var assoc = operators.getAssociativity(this, parenthesis); var operand = args[0].toTex(options); if (parens[0]) { operand = '\\left(' + operand + '\\right)'; } if (assoc === 'right') { //prefix operator return op + operand; } else if (assoc === 'left') { //postfix operator return operand + op; } //fall back to postfix return operand + op; } else if (args.length === 2) { //binary operators var lhs = args[0]; //left hand side var lhsTex = lhs.toTex(options); if (parens[0]) { lhsTex = '\\left(' + lhsTex + '\\right)'; } var rhs = args[1]; //right hand side var rhsTex = rhs.toTex(options); if (parens[1]) { rhsTex = '\\left(' + rhsTex + '\\right)'; } //handle some exceptions (due to the way LaTeX works) var lhsIdentifier; if (parenthesis === 'keep') { lhsIdentifier = lhs.getIdentifier(); } else { //Ignore ParenthesisNodes if in 'keep' mode lhsIdentifier = lhs.getContent().getIdentifier(); } switch (this.getIdentifier()) { case 'OperatorNode:divide': //op contains '\\frac' at this point return op + '{' + lhsTex + '}' + '{' + rhsTex + '}'; case 'OperatorNode:pow': lhsTex = '{' + lhsTex + '}'; rhsTex = '{' + rhsTex + '}'; switch (lhsIdentifier) { case 'ConditionalNode': // case 'OperatorNode:divide': lhsTex = '\\left(' + lhsTex + '\\right)'; } case 'OperatorNode:multiply': if (this.implicit && (implicit === 'hide')) { return lhsTex + '~' + rhsTex; } } return lhsTex + op + rhsTex; } else if ((args.length > 2) && ((this.getIdentifier() === 'OperatorNode:add') || (this.getIdentifier() === 'OperatorNode:multiply '))) { var texifiedArgs = args.map(function (arg, index) { arg = arg.toTex(options); if (parens[index]) { arg = '\\left(' + arg + '\\right)'; } return arg; }); if ((this.getIdentifier() === 'OperatorNode:multiply') && this.implicit) { return texifiedArgs.join('~'); } return texifiedArgs.join(op) } else { //fall back to formatting as a function call //as this is a fallback, it doesn't use //fancy function names return '\\mathrm{' + this.fn + '}\\left(' + args.map(function (arg) { return arg.toTex(options); }).join(',') + '\\right)'; } }
...
}
}
if (typeof customTex !== 'undefined') {
return customTex;
}
return this._toTex(options);
};
/**
* Internal function to generate the LaTeX output.
* This has to be implemented by every Node
*
* @param {Object} [options]
...
clone = function () { return new OperatorNode(this.op, this.fn, this.args.slice(0), this.implicit); }
...
return desc;
};
/**
* Export the help object to JSON
*/
Help.prototype.toJSON = function () {
var obj = object.clone(this.doc);
obj.mathjs = 'Help';
return obj;
};
/**
* Instantiate a Help object from a JSON object
* @param {Object} json
...
forEach = function (callback) { for (var i = 0; i < this.args.length; i++) { callback(this.args[i], 'args[' + i + ']', this); } }
...
if (def.indexOf(keyword) == 0) {
matches.push(def);
}
}
}
// commandline keywords
['exit', 'quit', 'clear'].forEach(function (cmd) {
if (cmd.indexOf(keyword) == 0) {
matches.push(cmd);
}
});
// math functions and constants
var ignore = ['expr', 'type'];
...
getIdentifier = function () { return this.type + ':' + this.fn; }
...
*/
function getPrecedence (_node, parenthesis) {
var node = _node;
if (parenthesis !== 'keep') {
//ParenthesisNodes are only ignored when not in 'keep' mode
node = _node.getContent();
}
var identifier = node.getIdentifier();
for (var i = 0; i < properties.length; i++) {
if (identifier in properties[i]) {
return i;
}
}
return null;
}
...
map = function (callback) { var args = []; for (var i = 0; i < this.args.length; i++) { args[i] = this._ifNode(callback(this.args[i], 'args[' + i + ']', this)); } return new OperatorNode(this.op, this.fn, args); }
...
if (res && res.isResultSet) {
// we can have 0 or 1 results in the ResultSet, as the CLI
// does not allow multiple expressions separated by a return
res = res.entries[0];
node = node.blocks
.filter(function (entry) { return entry.visible; })
.map(function (entry) { return entry.node })[0];
}
if (node) {
if (node.isAssignmentNode) {
var name = findSymbolName(node);
if (name != null) {
scope.ans = scope[name];
...
_compile = function (defs, args) { return this.content._compile(defs, args); }
...
* @return {string} js
* @private
*/
AccessorNode.prototype._compile = function (defs, args) {
defs.access = access;
defs.getSafeProperty = getSafeProperty;
var object = this.object._compile(defs, args);
var index = this.index._compile(defs, args);
if (this.index.isObjectProperty()) {
var prop = this.index.getObjectProperty();
return 'getSafeProperty(' + object + ', "' + prop + '")';
}
else if (this.index.needsSize()) {
...
_toString = function (options) { if ((!options) || (options && !options.parenthesis) || (options && options.parenthesis === 'keep')) { return '(' + this.content.toString(options) + ')'; } return this.content.toString(options); }
...
}
}
if (typeof customString !== 'undefined') {
return customString;
}
return this._toString(options);
};
/**
* Internal function to generate the string output.
* This has to be implemented by every Node
*
* @throws {Error}
...
_toTex = function (options) { if ((!options) || (options && !options.parenthesis) || (options && options.parenthesis === 'keep')) { return '\\left(' + this.content.toTex(options) + '\\right)'; } return this.content.toTex(options); }
...
}
}
if (typeof customTex !== 'undefined') {
return customTex;
}
return this._toTex(options);
};
/**
* Internal function to generate the LaTeX output.
* This has to be implemented by every Node
*
* @param {Object} [options]
...
clone = function () { return new ParenthesisNode(this.content); }
...
return desc;
};
/**
* Export the help object to JSON
*/
Help.prototype.toJSON = function () {
var obj = object.clone(this.doc);
obj.mathjs = 'Help';
return obj;
};
/**
* Instantiate a Help object from a JSON object
* @param {Object} json
...
forEach = function (callback) { callback(this.content, 'content', this); }
...
if (def.indexOf(keyword) == 0) {
matches.push(def);
}
}
}
// commandline keywords
['exit', 'quit', 'clear'].forEach(function (cmd) {
if (cmd.indexOf(keyword) == 0) {
matches.push(cmd);
}
});
// math functions and constants
var ignore = ['expr', 'type'];
...
getContent = function () { return this.content.getContent(); }
...
* @param {string} parenthesis
* @return {number|null}
*/
function getPrecedence (_node, parenthesis) {
var node = _node;
if (parenthesis !== 'keep') {
//ParenthesisNodes are only ignored when not in 'keep' mode
node = _node.getContent();
}
var identifier = node.getIdentifier();
for (var i = 0; i < properties.length; i++) {
if (identifier in properties[i]) {
return i;
}
}
...
map = function (callback) { var content = callback(this.content, 'content', this); return new ParenthesisNode(content); }
...
if (res && res.isResultSet) {
// we can have 0 or 1 results in the ResultSet, as the CLI
// does not allow multiple expressions separated by a return
res = res.entries[0];
node = node.blocks
.filter(function (entry) { return entry.visible; })
.map(function (entry) { return entry.node })[0];
}
if (node) {
if (node.isAssignmentNode) {
var name = findSymbolName(node);
if (name != null) {
scope.ans = scope[name];
...
_compile = function (defs, args) { return 'math.range(' + this.start._compile(defs, args) + ', ' + this.end._compile(defs, args) + (this.step ? (', ' + this.step._compile(defs, args)) : '') + ')'; }
...
* @return {string} js
* @private
*/
AccessorNode.prototype._compile = function (defs, args) {
defs.access = access;
defs.getSafeProperty = getSafeProperty;
var object = this.object._compile(defs, args);
var index = this.index._compile(defs, args);
if (this.index.isObjectProperty()) {
var prop = this.index.getObjectProperty();
return 'getSafeProperty(' + object + ', "' + prop + '")';
}
else if (this.index.needsSize()) {
...
_toString = function (options) { var parenthesis = (options && options.parenthesis) ? options.parenthesis : 'keep'; var parens = calculateNecessaryParentheses(this, parenthesis); //format string as start:step:stop var str; var start = this.start.toString(options); if (parens.start) { start = '(' + start + ')'; } str = start; if (this.step) { var step = this.step.toString(options); if (parens.step) { step = '(' + step + ')'; } str += ':' + step; } var end = this.end.toString(options); if (parens.end) { end = '(' + end + ')'; } str += ':' + end; return str; }
...
}
}
if (typeof customString !== 'undefined') {
return customString;
}
return this._toString(options);
};
/**
* Internal function to generate the string output.
* This has to be implemented by every Node
*
* @throws {Error}
...
_toTex = function (options) { var parenthesis = (options && options.parenthesis) ? options.parenthesis : 'keep'; var parens = calculateNecessaryParentheses(this, parenthesis); var str = this.start.toTex(options); if (parens.start) { str = '\\left(' + str + '\\right)'; } if (this.step) { var step = this.step.toTex(options); if (parens.step) { step = '\\left(' + step + '\\right)'; } str += ':' + step; } var end = this.end.toTex(options); if (parens.end) { end = '\\left(' + end + '\\right)'; } str += ':' + end; return str; }
...
}
}
if (typeof customTex !== 'undefined') {
return customTex;
}
return this._toTex(options);
};
/**
* Internal function to generate the LaTeX output.
* This has to be implemented by every Node
*
* @param {Object} [options]
...
clone = function () { return new RangeNode(this.start, this.end, this.step && this.step); }
...
return desc;
};
/**
* Export the help object to JSON
*/
Help.prototype.toJSON = function () {
var obj = object.clone(this.doc);
obj.mathjs = 'Help';
return obj;
};
/**
* Instantiate a Help object from a JSON object
* @param {Object} json
...
forEach = function (callback) { callback(this.start, 'start', this); callback(this.end, 'end', this); if (this.step) { callback(this.step, 'step', this); } }
...
if (def.indexOf(keyword) == 0) {
matches.push(def);
}
}
}
// commandline keywords
['exit', 'quit', 'clear'].forEach(function (cmd) {
if (cmd.indexOf(keyword) == 0) {
matches.push(cmd);
}
});
// math functions and constants
var ignore = ['expr', 'type'];
...
map = function (callback) { return new RangeNode( this._ifNode(callback(this.start, 'start', this)), this._ifNode(callback(this.end, 'end', this)), this.step && this._ifNode(callback(this.step, 'step', this)) ); }
...
if (res && res.isResultSet) {
// we can have 0 or 1 results in the ResultSet, as the CLI
// does not allow multiple expressions separated by a return
res = res.entries[0];
node = node.blocks
.filter(function (entry) { return entry.visible; })
.map(function (entry) { return entry.node })[0];
}
if (node) {
if (node.isAssignmentNode) {
var name = findSymbolName(node);
if (name != null) {
scope.ans = scope[name];
...
needsEnd = function () { // find all `end` symbols in this RangeNode var endSymbols = this.filter(function (node) { return (node && node.isSymbolNode) && (node.name == 'end'); }); return endSymbols.length > 0; }
...
// TODO: Optimization: when the range values are ConstantNodes,
// we can beforehand resolve the zero-based value
// optimization for a simple object property
var dimensions = this.dimensions.map(function (range, i) {
if (range && range.isRangeNode) {
if (range.needsEnd()) {
childArgs.end = true;
// resolve end and create range
return '(function () {' +
'var end = size[' + i + ']; ' +
'return range(' +
range.start._compile(defs, childArgs) + ', ' +
...
_compile = function (defs, args) { // add a function to the definitions defs['undef'] = undef; defs['Unit'] = Unit; defs.getSafeProperty = getSafeProperty; if (args[this.name]) { // this is a FunctionAssignment argument // (like an x when inside the expression of a function assignment `f(x) = ...`) return this.name; } else if (this.name in defs.math) { return '("' + this.name + '" in scope ? getSafeProperty(scope, "' + this.name + '") : getSafeProperty(math, "' + this.name + '"))'; } else { return '(' + '"' + this.name + '" in scope ? getSafeProperty(scope, "' + this.name + '") : ' + (Unit.isValuelessUnit(this.name) ? 'new Unit(null, "' + this.name + '")' : 'undef("' + this.name + '")') + ')'; } }
...
* @return {string} js
* @private
*/
AccessorNode.prototype._compile = function (defs, args) {
defs.access = access;
defs.getSafeProperty = getSafeProperty;
var object = this.object._compile(defs, args);
var index = this.index._compile(defs, args);
if (this.index.isObjectProperty()) {
var prop = this.index.getObjectProperty();
return 'getSafeProperty(' + object + ', "' + prop + '")';
}
else if (this.index.needsSize()) {
...
_toString = function (options) { return this.name; }
...
}
}
if (typeof customString !== 'undefined') {
return customString;
}
return this._toString(options);
};
/**
* Internal function to generate the string output.
* This has to be implemented by every Node
*
* @throws {Error}
...
_toTex = function (options) { var isUnit = false; if ((typeof math[this.name] === 'undefined') && Unit.isValuelessUnit(this.name)) { isUnit = true; } var symbol = latex.toSymbol(this.name, isUnit); if (symbol[0] === '\\') { //no space needed if the symbol starts with '\' return symbol; } //the space prevents symbols from breaking stuff like '\cdot' if it's written right before the symbol return ' ' + symbol; }
...
}
}
if (typeof customTex !== 'undefined') {
return customTex;
}
return this._toTex(options);
};
/**
* Internal function to generate the LaTeX output.
* This has to be implemented by every Node
*
* @param {Object} [options]
...
clone = function () { return new SymbolNode(this.name); }
...
return desc;
};
/**
* Export the help object to JSON
*/
Help.prototype.toJSON = function () {
var obj = object.clone(this.doc);
obj.mathjs = 'Help';
return obj;
};
/**
* Instantiate a Help object from a JSON object
* @param {Object} json
...
forEach = function (callback) { // nothing to do, we don't have childs }
...
if (def.indexOf(keyword) == 0) {
matches.push(def);
}
}
}
// commandline keywords
['exit', 'quit', 'clear'].forEach(function (cmd) {
if (cmd.indexOf(keyword) == 0) {
matches.push(cmd);
}
});
// math functions and constants
var ignore = ['expr', 'type'];
...
map = function (callback) { return this.clone(); }
...
if (res && res.isResultSet) {
// we can have 0 or 1 results in the ResultSet, as the CLI
// does not allow multiple expressions separated by a return
res = res.entries[0];
node = node.blocks
.filter(function (entry) { return entry.visible; })
.map(function (entry) { return entry.node })[0];
}
if (node) {
if (node.isAssignmentNode) {
var name = findSymbolName(node);
if (name != null) {
scope.ans = scope[name];
...
function AccessorNode(object, index) { if (!(this instanceof AccessorNode)) { throw new SyntaxError('Constructor must be called with the new operator'); } if (!(object && object.isNode)) { throw new TypeError('Node expected for parameter "object"'); } if (!(index && index.isIndexNode)) { throw new TypeError('IndexNode expected for parameter "index"'); } this.object = object || null; this.index = index; // readonly property name Object.defineProperty(this, 'name', { get: function () { if (this.index) { return (this.index.isObjectProperty()) ? this.index.getObjectProperty() : ''; } else { return this.object.name || ''; } }.bind(this), set: function () { throw new Error('Cannot assign a new name, name is read-only'); } }); }
n/a
function ArrayNode(items) { if (!(this instanceof ArrayNode)) { throw new SyntaxError('Constructor must be called with the new operator'); } this.items = items || []; // validate input if (!Array.isArray(this.items) || !this.items.every(function (item) {return item && item.isNode;})) { throw new TypeError('Array containing Nodes expected'); } // TODO: deprecated since v3, remove some day var deprecated = function () { throw new Error('Property `ArrayNode.nodes` is deprecated, use `ArrayNode.items` instead'); }; Object.defineProperty(this, 'nodes', { get: deprecated, set: deprecated }); }
n/a
function AssignmentNode(object, index, value) { if (!(this instanceof AssignmentNode)) { throw new SyntaxError('Constructor must be called with the new operator'); } this.object = object; this.index = value ? index : null; this.value = value ? value : index; // validate input if (!object || !(object.isSymbolNode || object.isAccessorNode)) { throw new TypeError('SymbolNode or AccessorNode expected as "object"'); } if (object && object.isSymbolNode && object.name === 'end') { throw new Error('Cannot assign to symbol "end"'); } if (this.index && !this.index.isIndexNode) { throw new TypeError('IndexNode expected as "index"'); } if (!this.value || !this.value.isNode) { throw new TypeError('Node expected as "value"'); } // readonly property name Object.defineProperty(this, 'name', { get: function () { if (this.index) { return (this.index.isObjectProperty()) ? this.index.getObjectProperty() : ''; } else { return this.object.name || ''; } }.bind(this), set: function () { throw new Error('Cannot assign a new name, name is read-only'); } }); }
n/a
function BlockNode(blocks) { if (!(this instanceof BlockNode)) { throw new SyntaxError('Constructor must be called with the new operator'); } // validate input, copy blocks if (!Array.isArray(blocks)) throw new Error('Array expected'); this.blocks = blocks.map(function (block) { var node = block && block.node; var visible = block && block.visible !== undefined ? block.visible : true; if (!(node && node.isNode)) throw new TypeError('Property "node" must be a Node'); if (typeof visible !== 'boolean') throw new TypeError('Property "visible" must be a boolean'); return { node: node, visible: visible } }); }
n/a
function ConditionalNode(condition, trueExpr, falseExpr) { if (!(this instanceof ConditionalNode)) { throw new SyntaxError('Constructor must be called with the new operator'); } if (!(condition && condition.isNode)) throw new TypeError('Parameter condition must be a Node'); if (!(trueExpr && trueExpr.isNode)) throw new TypeError('Parameter trueExpr must be a Node'); if (!(falseExpr && falseExpr.isNode)) throw new TypeError('Parameter falseExpr must be a Node'); this.condition = condition; this.trueExpr = trueExpr; this.falseExpr = falseExpr; }
n/a
function ConstantNode(value, valueType) { if (!(this instanceof ConstantNode)) { throw new SyntaxError('Constructor must be called with the new operator'); } if (valueType) { if (typeof valueType !== 'string') { throw new TypeError('String expected for parameter "valueType"'); } if (typeof value !== 'string') { throw new TypeError('String expected for parameter "value"'); } this.value = value; this.valueType = valueType; } else { // stringify the value and determine the type this.value = value + ''; this.valueType = getType(value); } if (!SUPPORTED_TYPES[this.valueType]) { throw new TypeError('Unsupported type of value "' + this.valueType + '"'); } }
n/a
function FunctionAssignmentNode(name, params, expr) { if (!(this instanceof FunctionAssignmentNode)) { throw new SyntaxError('Constructor must be called with the new operator'); } // validate input if (typeof name !== 'string') throw new TypeError('String expected for parameter "name"'); if (!Array.isArray(params)) throw new TypeError('Array containing strings or objects expected for parameter "params"'); if (!(expr && expr.isNode)) throw new TypeError('Node expected for parameter "expr"'); if (name in keywords) throw new Error('Illegal function name, "' + name + '" is a reserved keyword'); this.name = name; this.params = params.map(function (param) { return param && param.name || param; }); this.types = params.map(function (param) { return param && param.type || 'any' }); this.expr = expr; }
n/a
function FunctionNode(fn, args) { if (!(this instanceof FunctionNode)) { throw new SyntaxError('Constructor must be called with the new operator'); } if (typeof fn === 'string') { fn = new SymbolNode(fn); } // validate input if (!fn || !fn.isNode) throw new TypeError('Node expected as parameter "fn"'); if (!Array.isArray(args) || !args.every(function (arg) {return arg && arg.isNode;})) { throw new TypeError('Array containing Nodes expected for parameter "args"'); } this.fn = fn; this.args = args || []; // readonly property name Object.defineProperty(this, 'name', { get: function () { return this.fn.name || ''; }.bind(this), set: function () { throw new Error('Cannot assign a new name, name is read-only'); } }); // TODO: deprecated since v3, remove some day var deprecated = function () { throw new Error('Property `FunctionNode.object` is deprecated, use `FunctionNode.fn` instead'); }; Object.defineProperty(this, 'object', { get: deprecated, set: deprecated }); }
n/a
function IndexNode(dimensions, dotNotation) { if (!(this instanceof IndexNode)) { throw new SyntaxError('Constructor must be called with the new operator'); } this.dimensions = dimensions; this.dotNotation = dotNotation || false; // validate input if (!isArray(dimensions) || !dimensions.every(function (range) {return range && range.isNode;})) { throw new TypeError('Array containing Nodes expected for parameter "dimensions"'); } if (this.dotNotation && !this.isObjectProperty()) { throw new Error('dotNotation only applicable for object properties'); } // TODO: deprecated since v3, remove some day var deprecated = function () { throw new Error('Property `IndexNode.object` is deprecated, use `IndexNode.fn` instead'); }; Object.defineProperty(this, 'object', { get: deprecated, set: deprecated }); }
n/a
function Node() { if (!(this instanceof Node)) { throw new SyntaxError('Constructor must be called with the new operator'); } }
n/a
function ObjectNode(properties) { if (!(this instanceof ObjectNode)) { throw new SyntaxError('Constructor must be called with the new operator'); } this.properties = properties || {}; // validate input if (properties) { if (!(typeof properties === 'object') || Object.keys(properties).some(function (key) { return !properties[key] || !properties[key].isNode; })) { throw new TypeError('Object containing Nodes expected'); } } }
n/a
function OperatorNode(op, fn, args, implicit) { if (!(this instanceof OperatorNode)) { throw new SyntaxError('Constructor must be called with the new operator'); } //validate input if (typeof op !== 'string') { throw new TypeError('string expected for parameter "op"'); } if (typeof fn !== 'string') { throw new TypeError('string expected for parameter "fn"'); } if (!Array.isArray(args) || !args.every(function (node) {return node && node.isNode;})) { throw new TypeError('Array containing Nodes expected for parameter "args"'); } this.implicit = (implicit === true); this.op = op; this.fn = fn; this.args = args || []; }
n/a
function ParenthesisNode(content) { if (!(this instanceof ParenthesisNode)) { throw new SyntaxError('Constructor must be called with the new operator'); } // validate input if (!(content && content.isNode)) { throw new TypeError('Node expected for parameter "content"'); } this.content = content; }
n/a
function RangeNode(start, end, step) { if (!(this instanceof RangeNode)) { throw new SyntaxError('Constructor must be called with the new operator'); } // validate inputs if (!(start && start.isNode)) throw new TypeError('Node expected'); if (!(end && end.isNode)) throw new TypeError('Node expected'); if (step && !(step && step.isNode)) throw new TypeError('Node expected'); if (arguments.length > 3) throw new Error('Too many arguments'); this.start = start; // included lower-bound this.end = end; // included upper-bound this.step = step || null; // optional step }
n/a
function SymbolNode(name) { if (!(this instanceof SymbolNode)) { throw new SyntaxError('Constructor must be called with the new operator'); } // validate input if (typeof name !== 'string') throw new TypeError('String expected for parameter "name"'); this.name = name; }
n/a
function UpdateNode() { // TODO: deprecated since v3. Cleanup some day throw new Error('UpdateNode is deprecated. Use AssignmentNode instead.'); }
n/a
function parse(expr, options) { if (arguments.length != 1 && arguments.length != 2) { throw new ArgumentsError('parse', arguments.length, 1, 2); } // pass extra nodes extra_nodes = (options && options.nodes) ? options.nodes : {}; if (typeof expr === 'string') { // parse a single expression expression = expr; return parseStart(); } else if (Array.isArray(expr) || expr instanceof type.Matrix) { // parse an array or matrix with expressions return deepMap(expr, function (elem) { if (typeof elem !== 'string') throw new TypeError('String expected'); expression = elem; return parseStart(); }); } else { // oops throw new TypeError('String or matrix expected'); } }
...
if (!expr) {
break;
}
switch (mode) {
case 'eval':
// evaluate expression
try {
var node = math.parse(expr);
var res = node.eval(scope);
if (res && res.isResultSet) {
// we can have 0 or 1 results in the ResultSet, as the CLI
// does not allow multiple expressions separated by a return
res = res.entries[0];
node = node.blocks
...
function isAlpha(c, cPrev, cNext) { return parse.isValidLatinOrGreek(c) || parse.isValidMathSymbol(c, cNext) || parse.isValidMathSymbol(cPrev, c); }
...
}
}
return;
}
// check for variables, functions, named operators
if (parse.isAlpha(c, prevPreview(), nextPreview())) {
while (parse.isAlpha(c, prevPreview(), nextPreview()) || parse.isDigit(c)) {
token += c;
next();
}
if (NAMED_DELIMITERS.hasOwnProperty(token)) {
token_type = TOKENTYPE.DELIMITER;
...
function isDecimalMark(c, cNext) { return c == '.' && cNext !== '/' && cNext !== '*' && cNext !== '^'; }
...
}
}
else {
while (parse.isDigit(c)) {
token += c;
next();
}
if (parse.isDecimalMark(c, nextPreview())) {
token += c;
next();
}
}
while (parse.isDigit(c)) {
token += c;
next();
...
function isDigit(c) { return (c >= '0' && c <= '9'); }
...
token_type = TOKENTYPE.NUMBER;
// get number, can have a single dot
if (c == '.') {
token += c;
next();
if (!parse.isDigit(c)) {
// this is no number, it is just a dot (can be dot notation)
token_type = TOKENTYPE.DELIMITER;
}
}
else {
while (parse.isDigit(c)) {
token += c;
...
function isDigitDot(c) { return ((c >= '0' && c <= '9') || c == '.'); }
...
token_type = TOKENTYPE.DELIMITER;
token = c;
next();
return;
}
// check for a number
if (parse.isDigitDot(c)) {
token_type = TOKENTYPE.NUMBER;
// get number, can have a single dot
if (c == '.') {
token += c;
next();
...
function isValidLatinOrGreek(c) { return /^[a-zA-Z_\u00C0-\u02AF\u0370-\u03FF\u2100-\u214F]$/.test(c); }
...
*
* @param {string} c Current character in the expression
* @param {string} cPrev Previous character
* @param {string} cNext Next character
* @return {boolean}
*/
parse.isAlpha = function isAlpha (c, cPrev, cNext) {
return parse.isValidLatinOrGreek(c)
|| parse.isValidMathSymbol(c, cNext)
|| parse.isValidMathSymbol(cPrev, c);
};
/**
* Test whether a character is a valid latin, greek, or letter-like character
* @param {string} c
...
function isValidMathSymbol(high, low) { return /^[\uD835]$/.test(high) && /^[\uDC00-\uDFFF]$/.test(low) && /^[^\uDC55\uDC9D\uDCA0\uDCA1\uDCA3\uDCA4\uDCA7\uDCA8\uDCAD\uDCBA\uDCBC\uDCC4\uDD06\uDD0B\uDD0C\uDD15\uDD1D\uDD3A\uDD3F\uDD45\uDD47-\uDD49\uDD51\uDEA6\uDEA7\uDFCC\uDFCD]$/.test(low); }
...
* @param {string} c Current character in the expression
* @param {string} cPrev Previous character
* @param {string} cNext Next character
* @return {boolean}
*/
parse.isAlpha = function isAlpha (c, cPrev, cNext) {
return parse.isValidLatinOrGreek(c)
|| parse.isValidMathSymbol(c, cNext)
|| parse.isValidMathSymbol(cPrev, c);
};
/**
* Test whether a character is a valid latin, greek, or letter-like character
* @param {string} c
* @return {boolean}
...
function isWhitespace(c, nestingLevel) { // TODO: also take '\r' carriage return as newline? Or does that give problems on mac? return c == ' ' || c == '\t' || (c == '\n' && nestingLevel > 0); }
...
function getToken() {
token_type = TOKENTYPE.NULL;
token = '';
comment = '';
// skip over whitespaces
// space, tab, and newline when inside parameters
while (parse.isWhitespace(c, nesting_level)) {
next();
}
// skip comment
if (c == '#') {
while (c != '\n' && c != '') {
comment += c;
...
function concat(arg0) { "use strict"; var name = 'concat'; if (arguments.length > 0) { var varArgs = []; for (var i = 0; i < arguments.length; i++) { varArgs.push(arguments[i]); } return signature0(varArgs); // signature: ...any } throw createError(name, arguments.length, 0, arguments[0], 'any'); }
...
// figure out what number of arguments the callback function expects
var args = maxArgumentCount(callback);
var recurse = function (value, index) {
if (Array.isArray(value)) {
value.forEach(function (child, i) {
// we create a copy of the index array and append the new index value
recurse(child, index.concat(i + 1)); // one based index, hence i+1
});
}
else {
// invoke the callback function with the right number of arguments
if (args === 1) {
callback(value);
}
...
function filterTransform(args, math, scope) { var x, test; if (args[0]) { x = args[0].compile().eval(scope); } if (args[1]) { if (args[1] && args[1].isSymbolNode) { // a function pointer, like filter([3, -2, 5], myTestFunction); test = args[1].compile().eval(scope); } else { // an equation like filter([3, -2, 5], x > 0) // find an undefined symbol var _scope = scope || {}; var symbol = args[1] .filter(function (node) { return (node && node.isSymbolNode) && !(node.name in math) && !(node.name in _scope); })[0]; // create a test function for this equation var sub = Object.create(_scope); var eq = args[1].compile(); if (symbol) { var name = symbol.name; test = function (x) { sub[name] = x; return eq.eval(sub); } } else { throw new Error('No undefined variable found in filter equation'); } } } return filter(x, test); }
...
}
}
}
}
}
// remove duplicates
matches = matches.filter(function(elem, pos, arr) {
return arr.indexOf(elem) == pos;
});
}
return [matches, keyword];
}
...
function forEach(arg0, arg1) { "use strict"; var name = 'forEach'; if (test0(arg0)) { // type: Array if (test1(arg1)) { // type: function if (arguments.length === 2) { return signature0(arg0, arg1); // signature: Array, function } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'function'); } if (test2(arg0)) { // type: Matrix if (test1(arg1)) { // type: function if (arguments.length === 2) { return signature0(arg0, arg1); // signature: Matrix, function } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'function'); } throw createError(name, arguments.length, 0, arguments[0], 'Array,Matrix'); }
...
if (def.indexOf(keyword) == 0) {
matches.push(def);
}
}
}
// commandline keywords
['exit', 'quit', 'clear'].forEach(function (cmd) {
if (cmd.indexOf(keyword) == 0) {
matches.push(cmd);
}
});
// math functions and constants
var ignore = ['expr', 'type'];
...
function indexTransform() { var args = []; for (var i = 0, ii = arguments.length; i < ii; i++) { var arg = arguments[i]; // change from one-based to zero based, and convert BigNumber to number if (arg && arg.isRange === true) { arg.start--; arg.end -= (arg.step > 0 ? 0 : 2); } else if (arg && arg.isSet === true) { arg = arg.map(function (v) { return v - 1; }); } else if (arg && (arg.isArray === true || arg.isMatrix)) { arg = arg.map(function (v) { return v - 1; }); } else if (typeof arg === 'number') { arg--; } else if (arg && arg.isBigNumber === true) { arg = arg.toNumber() - 1; } else if (typeof arg === 'string') { // leave as is } else { throw new TypeError('Dimension must be an Array, Matrix, number, string, or Range'); } args[i] = arg; } var res = new type.Index(); type.Index.apply(res, args); return res; }
...
'})()'
}
else { // ConstantNode
return range._compile(defs, childArgs);
}
});
return 'math.index(' + dimensions.join(', ') + ')';
};
/**
* Execute a callback for each of the child nodes of this node
* @param {function(child: Node, path: string, parent: Node)} callback
*/
IndexNode.prototype.forEach = function (callback) {
...
function max(arg0, arg1) { "use strict"; var name = 'max'; if (test0(arg0)) { // type: Array if (test1(arg1)) { // type: function if (arguments.length === 2) { return signature0(arg0, arg1); // signature: Array, function } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'function'); } if (test2(arg0)) { // type: Matrix if (test1(arg1)) { // type: function if (arguments.length === 2) { return signature1(arg0, arg1); // signature: Matrix, function } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'function'); } throw createError(name, arguments.length, 0, arguments[0], 'Array,Matrix'); }
...
if (res && res.isResultSet) {
// we can have 0 or 1 results in the ResultSet, as the CLI
// does not allow multiple expressions separated by a return
res = res.entries[0];
node = node.blocks
.filter(function (entry) { return entry.visible; })
.map(function (entry) { return entry.node })[0];
}
if (node) {
if (node.isAssignmentNode) {
var name = findSymbolName(node);
if (name != null) {
scope.ans = scope[name];
...
function max(arg0) { "use strict"; var name = 'max'; if (arguments.length > 0) { var varArgs = []; for (var i = 0; i < arguments.length; i++) { varArgs.push(arguments[i]); } return signature0(varArgs); // signature: ...any } throw createError(name, arguments.length, 0, arguments[0], 'any'); }
...
* @return {number} Returns the maximum number of expected arguments.
* Returns -1 when no signatures where found on the function.
*/
exports.maxArgumentCount = function (fn) {
return Object.keys(fn.signatures || {})
.reduce(function (args, signature) {
var count = (signature.match(/,/g) || []).length + 1;
return Math.max(args, count);
}, -1);
};
...
function mean(arg0) { "use strict"; var name = 'mean'; if (arguments.length > 0) { var varArgs = []; for (var i = 0; i < arguments.length; i++) { varArgs.push(arguments[i]); } return signature0(varArgs); // signature: ...any } throw createError(name, arguments.length, 0, arguments[0], 'any'); }
...
* Compute the mean value of matrix or a list with values.
* In case of a multi dimensional array, the mean of the flattened array
* will be calculated. When `dim` is provided, the maximum over the selected
* dimension will be calculated. Parameter `dim` is zero-based.
*
* Syntax:
*
* math.mean(a, b, c, ...)
* math.mean(A)
* math.mean(A, dim)
*
* Examples:
*
* math.mean(2, 1, 4, 3); // returns 2.5
* math.mean([1, 2.7, 3.2, 4]); // returns 2.725
...
function min(arg0) { "use strict"; var name = 'min'; if (arguments.length > 0) { var varArgs = []; for (var i = 0; i < arguments.length; i++) { varArgs.push(arguments[i]); } return signature0(varArgs); // signature: ...any } throw createError(name, arguments.length, 0, arguments[0], 'any'); }
...
* @private
*/
function _resize (array, size, dim, defaultValue) {
var i;
var elem;
var oldLen = array.length;
var newLen = size[dim];
var minLen = Math.min(oldLen, newLen);
// apply new length
array.length = newLen;
if (dim < size.length - 1) {
// non-last dimension
var dimNext = dim + 1;
...
function range(arg0) { "use strict"; var name = 'range'; if (arguments.length > 0) { var varArgs = []; for (var i = 0; i < arguments.length; i++) { varArgs.push(arguments[i]); } return signature0(varArgs); // signature: ...any } throw createError(name, arguments.length, 0, arguments[0], 'any'); }
...
* the name of the argument, and the value is `true`.
* The object may not be mutated, but must be
* extended instead.
* @return {string} js
* @private
*/
RangeNode.prototype._compile = function (defs, args) {
return 'math.range(' +
this.start._compile(defs, args) + ', ' +
this.end._compile(defs, args) +
(this.step ? (', ' + this.step._compile(defs, args)) : '') +
')';
};
/**
...
function subset(arg0) { "use strict"; var name = 'subset'; if (arguments.length > 0) { var varArgs = []; for (var i = 0; i < arguments.length; i++) { varArgs.push(arguments[i]); } return signature0(varArgs); // signature: ...any } throw createError(name, arguments.length, 0, arguments[0], 'any'); }
...
function factory (type, config, load, typed) {
var matrix = load(require('../../type/matrix/function/matrix'));
/**
* Get or set a subset of a matrix or string.
*
* Syntax:
* math.subset(value, index) // retrieve a subset
* math.subset(value, index, replacement [, defaultValue]) // replace a subset
*
* Examples:
*
* // get a subset
* var d = [[1, 2], [3, 4]];
* math.subset(d, math.index(1, 0)); // returns 3
...
function factory(type, config, load, typed) {
var matrix = load(require('../../type/matrix/function/matrix'));
/**
* Create a 2-dimensional identity matrix with size m x n or n x n.
* The matrix has ones on the diagonal and zeros elsewhere.
*
* Syntax:
*
* math.eye(n)
* math.eye(n, format)
* math.eye(m, n)
* math.eye(m, n, format)
* math.eye([m, n])
* math.eye([m, n], format)
*
* Examples:
*
* math.eye(3); // returns [[1, 0, 0], [0, 1, 0], [0, 0, 1]]
* math.eye(3, 2); // returns [[1, 0], [0, 1], [0, 0]]
*
* var A = [[1, 2, 3], [4, 5, 6]];
* math.eye(math.size(A)); // returns [[1, 0, 0], [0, 1, 0]]
*
* See also:
*
* diag, ones, zeros, size, range
*
* @param {...number | Matrix | Array} size The size for the matrix
* @param {string} [format] The Matrix storage format
*
* @return {Matrix | Array | number} A matrix with ones on the diagonal.
*/
var eye = typed('eye', {
'': function () {
return (config.matrix === 'Matrix') ? matrix([]) : [];
},
'string': function (format) {
return matrix(format);
},
'number | BigNumber': function (rows) {
return _eye(rows, rows, config.matrix === 'Matrix' ? 'default' : undefined);
},
'number | BigNumber, string': function (rows, format) {
return _eye(rows, rows, format);
},
'number | BigNumber, number | BigNumber': function (rows, cols) {
return _eye(rows, cols, config.matrix === 'Matrix' ? 'default' : undefined);
},
'number | BigNumber, number | BigNumber, string': function (rows, cols, format) {
return _eye(rows, cols, format);
},
'Array': function (size) {
return _eyeVector(size);
},
'Array, string': function (size, format) {
return _eyeVector(size, format);
},
'Matrix': function (size) {
return _eyeVector(size.valueOf(), size.storage());
},
'Matrix, string': function (size, format) {
return _eyeVector(size.valueOf(), format);
}
});
eye.toTex = undefined; // use default template
return eye;
function _eyeVector (size, format) {
switch (size.length) {
case 0: return format ? matrix(format) : [];
case 1: return _eye(size[0], size[0], format);
case 2: return _eye(size[0], size[1], format);
default: throw new Error('Vector containing two values expected');
}
}
/**
* Create an identity matrix
* @param {number | BigNumber} rows
* @param {number | BigNumber} cols
* @param {string} [format]
* @returns {Matrix}
* @private
*/
function _eye (rows, cols, format) {
// BigNumber constructor with the right precision
var Big = (rows && rows.isBigNumber === true)
? type.BigNumber
: (cols && cols.isBigNumber === true)
? type.BigNumber
: null;
if (rows && rows.isBigNumber === true) rows = rows.toNumber();
if (cols && cols.isBigNumber === true) cols = cols.toNumber();
if (!isInteger(rows) || rows < 1) {
throw new Error('Parameters in function eye must be positive integers');
}
if (!isInteger(cols) || cols < 1) {
throw new Error('Parameters in function eye must be positive integers');
}
var one = Big ? new type.BigNumber(1) : 1;
var defaultValue = Big ? new Big(0) : 0;
var size = [rows, cols];
// check we need to return a matrix
if (format) {
// get matrix storage constructor
var F = type.Matrix.storage(format);
// create diagonal matrix (use optimized implementation for storage format)
return F.diagonal(size, one, 0, defaultValue);
}
// create and resize array
var res = array.resize([], size, defaultValue);
// fill in ones on the diagonal
var minimum = rows < cols ? rows : cols;
// fill diagonal
for (var d = 0; d < minimum; d++) {
res[d][d] = one;
}
return res;
}
}
n/a
function factory(type, config, load, typed) {
var gamma = load(require('./gamma'));
var latex = require('../../utils/latex');
/**
* Compute the factorial of a value
*
* Factorial only supports an integer value as argument.
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.factorial(n)
*
* Examples:
*
* math.factorial(5); // returns 120
* math.factorial(3); // returns 6
*
* See also:
*
* combinations, gamma, permutations
*
* @param {number | BigNumber | Array | Matrix} n An integer number
* @return {number | BigNumber | Array | Matrix} The factorial of `n`
*/
var factorial = typed('factorial', {
'number': function (n) {
if (n < 0) {
throw new Error('Value must be non-negative');
}
return gamma(n + 1);
},
'BigNumber': function (n) {
if (n.isNegative()) {
throw new Error('Value must be non-negative');
}
return gamma(n.plus(1));
},
'Array | Matrix': function (n) {
return deepMap(n, factorial);
}
});
factorial.toTex = {
1: '\\left(${args[0]}\\right)' + latex.operators['factorial']
};
return factorial;
}
n/a
function factory(type, config, load, typed) {
var matrix = load(require('../../type/matrix/function/matrix'));
/**
* Filter the items in an array or one dimensional matrix.
*
* Syntax:
*
* math.filter(x, test)
*
* Examples:
*
* function isPositive (x) {
* return x > 0;
* }
* math.filter([6, -2, -1, 4, 3], isPositive); // returns [6, 4, 3]
*
* math.filter(["23", "foo", "100", "55", "bar"], /[0-9]+/); // returns ["23", "100", "55"]
*
* See also:
*
* forEach, map, sort
*
* @param {Matrix | Array} x A one dimensional matrix or array to filter
* @param {Function | RegExp} test
* A function or regular expression to test items.
* All entries for which `test` returns true are returned.
* When `test` is a function, it is invoked with three parameters:
* the value of the element, the index of the element, and the
* matrix/array being traversed. The function must return a boolean.
* @return {Matrix | Array} Returns the filtered matrix.
*/
var filter = typed('filter', {
'Array, function': _filterCallback,
'Array, RegExp': _filterRegExp,
'Matrix, function': function (x, test) {
return matrix(_filterCallback(x.toArray(), test));
},
'Matrix, RegExp': function (x, test) {
return matrix(_filterRegExp(x.toArray(), test));
}
});
filter.toTex = undefined; // use default template
return filter;
}
n/a
function factory(type, config, load, typed) { var filter = load(require('../../function/matrix/filter')); var SymbolNode = load(require('../node/SymbolNode')); function filterTransform(args, math, scope) { var x, test; if (args[0]) { x = args[0].compile().eval(scope); } if (args[1]) { if (args[1] && args[1].isSymbolNode) { // a function pointer, like filter([3, -2, 5], myTestFunction); test = args[1].compile().eval(scope); } else { // an equation like filter([3, -2, 5], x > 0) // find an undefined symbol var _scope = scope || {}; var symbol = args[1] .filter(function (node) { return (node && node.isSymbolNode) && !(node.name in math) && !(node.name in _scope); })[0]; // create a test function for this equation var sub = Object.create(_scope); var eq = args[1].compile(); if (symbol) { var name = symbol.name; test = function (x) { sub[name] = x; return eq.eval(sub); } } else { throw new Error('No undefined variable found in filter equation'); } } } return filter(x, test); } filterTransform.rawArgs = true; return filterTransform; }
n/a
function factory(type, config, load, typed) {
/**
* Round a value towards zero.
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.fix(x)
*
* Examples:
*
* math.fix(3.2); // returns number 3
* math.fix(3.8); // returns number 3
* math.fix(-4.2); // returns number -4
* math.fix(-4.7); // returns number -4
*
* var c = math.complex(3.2, -2.7);
* math.fix(c); // returns Complex 3 - 2i
*
* math.fix([3.2, 3.8, -4.7]); // returns Array [3, 3, -4]
*
* See also:
*
* ceil, floor, round
*
* @param {number | BigNumber | Fraction | Complex | Array | Matrix} x Number to be rounded
* @return {number | BigNumber | Fraction | Complex | Array | Matrix} Rounded value
*/
var fix = typed('fix', {
'number': function (x) {
return (x > 0) ? Math.floor(x) : Math.ceil(x);
},
'Complex': function (x) {
return new type.Complex(
(x.re > 0) ? Math.floor(x.re) : Math.ceil(x.re),
(x.im > 0) ? Math.floor(x.im) : Math.ceil(x.im)
);
},
'BigNumber': function (x) {
return x.isNegative() ? x.ceil() : x.floor();
},
'Fraction': function (x) {
return x.s < 0 ? x.ceil() : x.floor();
},
'Array | Matrix': function (x) {
// deep map collection, skip zeros since fix(0) = 0
return deepMap(x, fix, true);
}
});
fix.toTex = {1: '\\mathrm{${name}}\\left(${args[0]}\\right)'};
return fix;
}
n/a
function factory(type, config, load, typed) {
var matrix = load(require('../../type/matrix/function/matrix'));
/**
* Flatten a multi dimensional matrix into a single dimensional matrix.
*
* Syntax:
*
* math.flatten(x)
*
* Examples:
*
* math.flatten([[1,2], [3,4]]); // returns [1, 2, 3, 4]
*
* See also:
*
* concat, resize, size, squeeze
*
* @param {Matrix | Array} x Matrix to be flattened
* @return {Matrix | Array} Returns the flattened matrix
*/
var flatten = typed('flatten', {
'Array': function (x) {
return _flatten(clone(x));
},
'Matrix': function (x) {
var flat = _flatten(clone(x.toArray()));
// TODO: return the same matrix type as x
return matrix(flat);
}
});
flatten.toTex = undefined; // use default template
return flatten;
}
n/a
function factory(type, config, load, typed) {
/**
* Round a value towards minus infinity.
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.floor(x)
*
* Examples:
*
* math.floor(3.2); // returns number 3
* math.floor(3.8); // returns number 3
* math.floor(-4.2); // returns number -5
* math.floor(-4.7); // returns number -5
*
* var c = math.complex(3.2, -2.7);
* math.floor(c); // returns Complex 3 - 3i
*
* math.floor([3.2, 3.8, -4.7]); // returns Array [3, 3, -5]
*
* See also:
*
* ceil, fix, round
*
* @param {number | BigNumber | Fraction | Complex | Array | Matrix} x Number to be rounded
* @return {number | BigNumber | Fraction | Complex | Array | Matrix} Rounded value
*/
var floor = typed('floor', {
'number': Math.floor,
'Complex': function (x) {
return x.floor();
},
'BigNumber': function (x) {
return x.floor();
},
'Fraction': function (x) {
return x.floor();
},
'Array | Matrix': function (x) {
// deep map collection, skip zeros since floor(0) = 0
return deepMap(x, floor, true);
}
});
floor.toTex = {1: '\\left\\lfloor${args[0]}\\right\\rfloor'};
return floor;
}
n/a
function factory(type, config, load, typed) {
/**
* Iterate over all elements of a matrix/array, and executes the given callback function.
*
* Syntax:
*
* math.forEach(x, callback)
*
* Examples:
*
* math.forEach([1, 2, 3], function(value) {
* console.log(value);
* });
* // outputs 1, 2, 3
*
* See also:
*
* filter, map, sort
*
* @param {Matrix | Array} x The matrix to iterate on.
* @param {Function} callback The callback function is invoked with three
* parameters: the value of the element, the index
* of the element, and the Matrix/array being traversed.
*/
var forEach = typed('forEach', {
'Array, function': _forEach,
'Matrix, function': function (x, callback) {
return x.forEach(callback);
}
});
forEach.toTex = undefined; // use default template
return forEach;
}
n/a
function factory(type, config, load, typed) { var forEach = load(require('../../function/matrix/forEach')); return typed('forEach', { 'Array | Matrix, function': function (array, callback) { // figure out what number of arguments the callback function expects var args = maxArgumentCount(callback); var recurse = function (value, index) { if (Array.isArray(value)) { value.forEach(function (child, i) { // we create a copy of the index array and append the new index value recurse(child, index.concat(i + 1)); // one based index, hence i+1 }); } else { // invoke the callback function with the right number of arguments if (args === 1) { callback(value); } else if (args === 2) { callback(value, index); } else { // 3 or -1 callback(value, index, array); } } }; recurse(array.valueOf(), []); // pass Array } }); }
n/a
function factory(type, config, load, typed) { /** * Format a value of any type into a string. * * Syntax: * * math.format(value) * math.format(value, options) * math.format(value, precision) * math.format(value, callback) * * Where: * * - `value: *` * The value to be formatted * - `options: Object` * An object with formatting options. Available options: * - `notation: string` * Number notation. Choose from: * - 'fixed' * Always use regular number notation. * For example '123.40' and '14000000' * - 'exponential' * Always use exponential notation. * For example '1.234e+2' and '1.4e+7' * - 'engineering' * Always use engineering notation. * For example '123.4e+0' and '14.0e+6' * - 'auto' (default) * Regular number notation for numbers having an absolute value between * `lower` and `upper` bounds, and uses exponential notation elsewhere. * Lower bound is included, upper bound is excluded. * For example '123.4' and '1.4e7'. * - `precision: number` * A number between 0 and 16 to round the digits of the number. In case * of notations 'exponential' and 'auto', `precision` defines the total * number of significant digits returned and is undefined by default. * In case of notation 'fixed', `precision` defines the number of * significant digits after the decimal point, and is 0 by default. * - `exponential: Object` * An object containing two parameters, {number} lower and {number} upper, * used by notation 'auto' to determine when to return exponential * notation. Default values are `lower=1e-3` and `upper=1e5`. Only * applicable for notation `auto`. * - `fraction: string`. Available values: 'ratio' (default) or 'decimal'. * For example `format(fraction(1, 3))` will output '1/3' when 'ratio' is * configured, and will output `0.(3)` when 'decimal' is configured. * - `callback: function` * A custom formatting function, invoked for all numeric elements in `value`, * for example all elements of a matrix, or the real and imaginary * parts of a complex number. This callback can be used to override the * built-in numeric notation with any type of formatting. Function `callback` * is called with `value` as parameter and must return a string. * * When `value` is an Object: * * - When the object contains a property `format` being a function, this function * is invoked as `value.format(options)` and the result is returned. * - When the object has its own `toString` method, this method is invoked * and the result is returned. * - In other cases the function will loop over all object properties and * return JSON object notation like '{"a": 2, "b": 3}'. * * When value is a function: * * - When the function has a property `syntax`, it returns this * syntax description. * - In other cases, a string `'function'` is returned. * * Examples: * * math.format(6.4); // returns '6.4' * math.format(1240000); // returns '1.24e6' * math.format(1/3); // returns '0.3333333333333333' * math.format(1/3, 3); // returns '0.333' * math.format(21385, 2); // returns '21000' * math.format(12.071, {notation: 'fixed'}); // returns '12' * math.format(2.3, {notation: 'fixed', precision: 2}); // returns '2.30' * math.format(52.8, {notation: 'exponential'}); // returns '5.28e+1' * math.format(12400, {notation: 'engineering'}); // returns '12.400e+3' * * function formatCurrency(value) { * // return currency notation with two digits: * return '$' + value.toFixed(2); * * ...
n/a
format = function (value, options) { if (typeof options === 'function') { // handle format(value, fn) return options(value); } // handle special cases if (!value.isFinite()) { return value.isNaN() ? 'NaN' : (value.gt(0) ? 'Infinity' : '-Infinity'); } // default values for options var notation = 'auto'; var precision = undefined; if (options !== undefined) { // determine notation from options if (options.notation) { notation = options.notation; } // determine precision from options if (typeof options === 'number') { precision = options; } else if (options.precision) { precision = options.precision; } } // handle the various notations switch (notation) { case 'fixed': return exports.toFixed(value, precision); case 'exponential': return exports.toExponential(value, precision); case 'auto': // determine lower and upper bound for exponential notation. // TODO: implement support for upper and lower to be BigNumbers themselves var lower = 1e-3; var upper = 1e5; if (options && options.exponential) { if (options.exponential.lower !== undefined) { lower = options.exponential.lower; } if (options.exponential.upper !== undefined) { upper = options.exponential.upper; } } // adjust the configuration of the BigNumber constructor (yeah, this is quite tricky...) var oldConfig = { toExpNeg: value.constructor.toExpNeg, toExpPos: value.constructor.toExpPos }; value.constructor.config({ toExpNeg: Math.round(Math.log(lower) / Math.LN10), toExpPos: Math.round(Math.log(upper) / Math.LN10) }); // handle special case zero if (value.isZero()) return '0'; // determine whether or not to output exponential notation var str; var abs = value.abs(); if (abs.gte(lower) && abs.lt(upper)) { // normal number notation str = value.toSignificantDigits(precision).toFixed(); } else { // exponential notation str = exports.toExponential(value, precision); } // remove trailing zeros after the decimal point return str.replace(/((\.\d*?)(0+))($|e)/, function () { var digits = arguments[2]; var e = arguments[4]; return (digits !== '.') ? digits + e : e; }); default: throw new Error('Unknown notation "' + notation + '". ' + 'Choose "auto", "exponential", or "fixed".'); } }
...
* Helper function to format a value. Regular numbers will be rounded
* to 14 digits to prevent round-off errors from showing up.
* @param {*} value
*/
function format(value) {
var math = getMath();
return math.format(value, {
fn: function (value) {
if (typeof value === 'number') {
// round numbers
return math.format(value, PRECISION);
}
else {
return math.format(value);
...
toExponential = function (value, precision) { if (precision !== undefined) { return value.toExponential(precision - 1); // Note the offset of one } else { return value.toExponential(); } }
...
// handle the various notations
switch (notation) {
case 'fixed':
return exports.toFixed(value, precision);
case 'exponential':
return exports.toExponential(value, precision);
case 'auto':
// determine lower and upper bound for exponential notation.
// TODO: implement support for upper and lower to be BigNumbers themselves
var lower = 1e-3;
var upper = 1e5;
if (options && options.exponential) {
...
toFixed = function (value, precision) { return value.toFixed(precision || 0); // Note: the (precision || 0) is needed as the toFixed of BigNumber has an // undefined default precision instead of 0. }
...
* math.format(12.071, {notation: 'fixed'}); // returns '12'
* math.format(2.3, {notation: 'fixed', precision: 2}); // returns '2.30'
* math.format(52.8, {notation: 'exponential'}); // returns '5.28e+1'
* math.format(12400, {notation: 'engineering'}); // returns '12.400e+3'
*
* function formatCurrency(value) {
* // return currency notation with two digits:
* return '$' + value.toFixed(2);
*
* // you could also use math.format inside the callback:
* // return '$' + math.format(value, {notation: 'fixed', precision: 2});
* }
* math.format([2.1, 3, 0.016], formatCurrency}; // returns '[$2.10, $3.00, $0.02]'
*
* See also:
...
maxArgumentCount = function (fn) { return Object.keys(fn.signatures || {}) .reduce(function (args, signature) { var count = (signature.match(/,/g) || []).length + 1; return Math.max(args, count); }, -1); }
n/a
memoize = function (fn, hasher) { return function memoize() { if (typeof memoize.cache !== 'object') { memoize.cache = {}; } var args = []; for (var i = 0; i < arguments.length; i++) { args[i] = arguments[i]; } var hash = hasher ? hasher(args) : JSON.stringify(args); if (!(hash in memoize.cache)) { return memoize.cache[hash] = fn.apply(fn, args); } return memoize.cache[hash]; }; }
n/a
function factory(type, config, load, typed) {
var multiply = load(require('../arithmetic/multiply'));
var pow = load(require('../arithmetic/pow'));
/**
* Compute the gamma function of a value using Lanczos approximation for
* small values, and an extended Stirling approximation for large values.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.gamma(n)
*
* Examples:
*
* math.gamma(5); // returns 24
* math.gamma(-0.5); // returns -3.5449077018110335
* math.gamma(math.i); // returns -0.15494982830180973 - 0.49801566811835596i
*
* See also:
*
* combinations, factorial, permutations
*
* @param {number | Array | Matrix} n A real or complex number
* @return {number | Array | Matrix} The gamma of `n`
*/
var gamma = typed('gamma', {
'number': function (n) {
var t, x;
if (isInteger(n)) {
if (n <= 0) {
return isFinite(n) ? Infinity : NaN;
}
if (n > 171) {
return Infinity; // Will overflow
}
var value = n - 2;
var res = n - 1;
while (value > 1) {
res *= value;
value--;
}
if (res == 0) {
res = 1; // 0! is per definition 1
}
return res;
}
if (n < 0.5) {
return Math.PI / (Math.sin(Math.PI * n) * gamma(1-n));
}
if (n >= 171.35) {
return Infinity; // will overflow
}
if (n > 85.0) { // Extended Stirling Approx
var twoN = n*n;
var threeN = twoN*n;
var fourN = threeN*n;
var fiveN = fourN*n;
return Math.sqrt(2*Math.PI/n) * Math.pow((n/Math.E), n) *
(1 + 1/(12*n) + 1/(288*twoN) - 139/(51840*threeN) -
571/(2488320*fourN) + 163879/(209018880*fiveN) +
5246819/(75246796800*fiveN*n));
}
--n;
x = p[0];
for (var i = 1; i < p.length; ++i) {
x += p[i] / (n+i);
}
t = n + g + 0.5;
return Math.sqrt(2*Math.PI) * Math.pow(t, n+0.5) * Math.exp(-t) * x;
},
'Complex': function (n) {
var t, x;
if (n.im == 0) {
return gamma(n.re);
}
n = new type.Complex(n.re - 1, n.im);
x = new type.Complex(p[0], 0);
for (var i = 1; i < p.length; ++i) {
var real = n.re + i; // x += p[i]/(n+i)
var den = real*real + n.im*n.im;
if (den != 0) {
x.re += p[i] * real / den;
x.im += -(p[i] * n.im) / den;
} else {
x.re = p[i] < 0
? -Infinity
: Infinity;
}
}
t = new type.Complex(n.re + g + 0.5, n.im);
var twoPiSqrt = Math.sqrt(2*Math.PI);
n.re += 0.5;
var result = pow(t, n);
if (result.im == 0) { // sqrt(2*PI)*result
result.re *= twoPiSqrt;
} else if (result.re == 0) {
result.im *= twoPiSqrt;
} else {
result.re *= twoPiSqrt;
result.im *= twoPiSqrt;
}
var r = Math.exp(-t.re); // exp(-t)
t.re = r * Math.cos(-t.im);
t.im = r * Math.sin(-t.im);
return multiply(multiply(result, t), x);
},
'BigNumber': function (n) {
if (n.isInteger()) {
return (n.isNegative() || n.isZero())
? new type.BigNumber(Infinity)
: bigFactorial(n.minus(1));
}
if (!n.isFinite()) {
return new type.BigNumber(n.isNegative() ? NaN : Infinity);
}
throw new Error('Integer BigNumber expected');
},
'Array | Matrix': function (n) {
return deepMap(n, gamma);
}
});
/**
* Calculate factorial for a BigNumber
* @param {BigNumber} n
* @returns {BigNumber} Returns the factorial of n
*/
function bigFactorial(n) {
if (n.isZero()) {
return new type.BigNumber(1); // 0! is per definition 1
}
var precision = config.precision + (Math.log(n.toNumber() ...
n/a
function factory(type, config, load, typed) {
var matrix = load(require('../../type/matrix/function/matrix'));
var algorithm01 = load(require('../../type/matrix/utils/algorithm01'));
var algorithm04 = load(require('../../type/matrix/utils/algorithm04'));
var algorithm10 = load(require('../../type/matrix/utils/algorithm10'));
var algorithm13 = load(require('../../type/matrix/utils/algorithm13'));
var algorithm14 = load(require('../../type/matrix/utils/algorithm14'));
/**
* Calculate the greatest common divisor for two or more values or arrays.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.gcd(a, b)
* math.gcd(a, b, c, ...)
*
* Examples:
*
* math.gcd(8, 12); // returns 4
* math.gcd(-4, 6); // returns 2
* math.gcd(25, 15, -10); // returns 5
*
* math.gcd([8, -4], [12, 6]); // returns [4, 2]
*
* See also:
*
* lcm, xgcd
*
* @param {... number | BigNumber | Fraction | Array | Matrix} args Two or more integer numbers
* @return {number | BigNumber | Fraction | Array | Matrix} The greatest common divisor
*/
var gcd = typed('gcd', {
'number, number': _gcd,
'BigNumber, BigNumber': _gcdBigNumber,
'Fraction, Fraction': function (x, y) {
return x.gcd(y);
},
'Matrix, Matrix': function (x, y) {
// result
var c;
// process matrix storage
switch (x.storage()) {
case 'sparse':
switch (y.storage()) {
case 'sparse':
// sparse + sparse
c = algorithm04(x, y, gcd);
break;
default:
// sparse + dense
c = algorithm01(y, x, gcd, true);
break;
}
break;
default:
switch (y.storage()) {
case 'sparse':
// dense + sparse
c = algorithm01(x, y, gcd, false);
break;
default:
// dense + dense
c = algorithm13(x, y, gcd);
break;
}
break;
}
return c;
},
'Array, Array': function (x, y) {
// use matrix implementation
return gcd(matrix(x), matrix(y)).valueOf();
},
'Array, Matrix': function (x, y) {
// use matrix implementation
return gcd(matrix(x), y);
},
'Matrix, Array': function (x, y) {
// use matrix implementation
return gcd(x, matrix(y));
},
'Matrix, number | BigNumber': function (x, y) {
// result
var c;
// check storage format
switch (x.storage()) {
case 'sparse':
c = algorithm10(x, y, gcd, false);
break;
default:
c = algorithm14(x, y, gcd, false);
break;
}
return c;
},
'number | BigNumber, Matrix': function (x, y) {
// result
var c;
// check storage format
switch (y.storage()) {
case 'sparse':
c = algorithm10(y, x, gcd, true);
break;
default:
c = algorithm14(y, x, gcd, true);
break;
}
return c;
},
'Array, number | BigNumber': function (x, y) {
// use matrix implementation
return algorithm14(matrix(x), y, gcd, false).valueOf();
},
'number | BigNumber, Array': function (x, y) {
// use matrix implementation
return algorithm14(matrix(y), x, gcd, true).valueOf();
},
// TODO: need a smarter notation here
'Array | Matrix | number | BigNumber, Array | Matrix | number | BigNumber, ...Array | Matrix | number | BigNumber': function
(a, b, args) {
var res = gcd(a, b);
for (var i = 0; i < args.length; i++) {
res = gcd(res, args[i]);
}
return res;
}
});
gcd.toTex = '\\gcd\\left(${args}\\right)';
return gcd;
/**
* Calculate gcd for BigNumbers
* @param {BigNumber} a
* @param {BigNumber} b
* @returns {BigNumber} Returns greatest common denomin ...
n/a
function factory(type, config, load, typed) {
var abs = load(require('./abs'));
var add = load(require('./addScalar'));
var divide = load(require('./divideScalar'));
var multiply = load(require('./multiplyScalar'));
var sqrt = load(require('./sqrt'));
var smaller = load(require('../relational/smaller'));
var isPositive = load(require('../utils/isPositive'));
/**
* Calculate the hypotenusa of a list with values. The hypotenusa is defined as:
*
* hypot(a, b, c, ...) = sqrt(a^2 + b^2 + c^2 + ...)
*
* For matrix input, the hypotenusa is calculated for all values in the matrix.
*
* Syntax:
*
* math.hypot(a, b, ...)
* math.hypot([a, b, c, ...])
*
* Examples:
*
* math.hypot(3, 4); // 5
* math.hypot(3, 4, 5); // 7.0710678118654755
* math.hypot([3, 4, 5]); // 7.0710678118654755
* math.hypot(-2); // 2
*
* See also:
*
* abs, norm
*
* @param {... number | BigNumber} args
* @return {number | BigNumber} Returns the hypothenusa of the input values.
*/
var hypot = typed('hypot', {
'... number | BigNumber': _hypot,
'Array': function (x) {
return hypot.apply(hypot, flatten(x));
},
'Matrix': function (x) {
return hypot.apply(hypot, flatten(x.toArray()));
}
});
/**
* Calculate the hypotenusa for an Array with values
* @param {Array.<number | BigNumber>} args
* @return {number | BigNumber} Returns the result
* @private
*/
function _hypot (args) {
// code based on `hypot` from es6-shim:
// https://github.com/paulmillr/es6-shim/blob/master/es6-shim.js#L1619-L1633
var result = 0;
var largest = 0;
for (var i = 0; i < args.length; i++) {
var value = abs(args[i]);
if (smaller(largest, value)) {
result = multiply(result, multiply(divide(largest, value), divide(largest, value)));
result = add(result, 1);
largest = value;
} else {
result = add(result, isPositive(value) ? multiply(divide(value, largest), divide(value, largest)) : value);
}
}
return multiply(largest, sqrt(result));
}
hypot.toTex = '\\hypot\\left(${args}\\right)';
return hypot;
}
n/a
function factory(type, config, load, typed) {
/**
* Get the imaginary part of a complex number.
* For a complex number `a + bi`, the function returns `b`.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.im(x)
*
* Examples:
*
* var a = math.complex(2, 3);
* math.re(a); // returns number 2
* math.im(a); // returns number 3
*
* math.re(math.complex('-5.2i')); // returns number -5.2
* math.re(math.complex(2.4)); // returns number 0
*
* See also:
*
* re, conj, abs, arg
*
* @param {number | BigNumber | Complex | Array | Matrix} x
* A complex number or array with complex numbers
* @return {number | BigNumber | Array | Matrix} The imaginary part of x
*/
var im = typed('im', {
'number': function (x) {
return 0;
},
'BigNumber': function (x) {
return new type.BigNumber(0);
},
'Complex': function (x) {
return x.im;
},
'Array | Matrix': function (x) {
return deepMap(x, im);
}
});
im.toTex = {1: '\\Im\\left\\lbrace${args[0]}\\right\\rbrace'};
return im;
}
n/a
function factory(type, config, load, typed, math) {
/**
* Import functions from an object or a module
*
* Syntax:
*
* math.import(object)
* math.import(object, options)
*
* Where:
*
* - `object: Object`
* An object with functions to be imported.
* - `options: Object` An object with import options. Available options:
* - `override: boolean`
* If true, existing functions will be overwritten. False by default.
* - `silent: boolean`
* If true, the function will not throw errors on duplicates or invalid
* types. False by default.
* - `wrap: boolean`
* If true, the functions will be wrapped in a wrapper function
* which converts data types like Matrix to primitive data types like Array.
* The wrapper is needed when extending math.js with libraries which do not
* support these data type. False by default.
*
* Examples:
*
* // define new functions and variables
* math.import({
* myvalue: 42,
* hello: function (name) {
* return 'hello, ' + name + '!';
* }
* });
*
* // use the imported function and variable
* math.myvalue * 2; // 84
* math.hello('user'); // 'hello, user!'
*
* // import the npm module 'numbers'
* // (must be installed first with `npm install numbers`)
* math.import(require('numbers'), {wrap: true});
*
* math.fibonacci(7); // returns 13
*
* @param {Object | Array} object Object with functions to be imported.
* @param {Object} [options] Import options.
*/
function math_import(object, options) {
var num = arguments.length;
if (num !== 1 && num !== 2) {
throw new ArgumentsError('import', num, 1, 2);
}
if (!options) {
options = {};
}
if (isFactory(object)) {
_importFactory(object, options);
}
// TODO: allow a typed-function with name too
else if (Array.isArray(object)) {
object.forEach(function (entry) {
math_import(entry, options);
});
}
else if (typeof object === 'object') {
// a map with functions
for (var name in object) {
if (object.hasOwnProperty(name)) {
var value = object[name];
if (isSupportedType(value)) {
_import(name, value, options);
}
else if (isFactory(object)) {
_importFactory(object, options);
}
else {
math_import(value, options);
}
}
}
}
else {
if (!options.silent) {
throw new TypeError('Factory, Object, or Array expected');
}
}
}
/**
* Add a property to the math namespace and create a chain proxy for it.
* @param {string} name
* @param {*} value
* @param {Object} options See import for a description of the options
* @private
*/
function _import(name, value, options) {
// TODO: refactor this function, it's to complicated and contains duplicate code
if (options.wrap && typeof value === 'function') {
// create a wrapper around the function
value = _wrap(value);
}
if (isTypedFunction(math[name]) && isTypedFunction(value)) {
if (options.override) {
// give the typed function the right name
value = typed(name, value.signatures);
}
else {
// merge the existing and typed function
value = typed(math[name], value);
}
math[name] = value;
_importTransform(name, value);
math.emit('import', name, function resolver() {
return value;
});
return;
}
if (math[name] === undefined || options.override) {
math[name] = value;
_importTransform(name, value);
math.emit('import', name, function resolver() {
return value;
});
return;
}
if (!options.silent) {
throw new Error('Cannot import "' + name + '": already exists');
}
}
function _importTransform (name, value) {
if (value && typeof value ...
n/a
function factory(type, config, load) { return function indexTransform() { var args = []; for (var i = 0, ii = arguments.length; i < ii; i++) { var arg = arguments[i]; // change from one-based to zero based, and convert BigNumber to number if (arg && arg.isRange === true) { arg.start--; arg.end -= (arg.step > 0 ? 0 : 2); } else if (arg && arg.isSet === true) { arg = arg.map(function (v) { return v - 1; }); } else if (arg && (arg.isArray === true || arg.isMatrix)) { arg = arg.map(function (v) { return v - 1; }); } else if (typeof arg === 'number') { arg--; } else if (arg && arg.isBigNumber === true) { arg = arg.toNumber() - 1; } else if (typeof arg === 'string') { // leave as is } else { throw new TypeError('Dimension must be an Array, Matrix, number, string, or Range'); } args[i] = arg; } var res = new type.Index(); type.Index.apply(res, args); return res; }; }
n/a
function factory(type, config, load, typed) {
var abs = load(require('../arithmetic/abs'));
var add = load(require('../arithmetic/add'));
var matrix = load(require('../../type/matrix/function/matrix'));
var multiply = load(require('../arithmetic/multiply'));
var subtract = load(require('../arithmetic/subtract'));
/**
* Calculates the point of intersection of two lines in two or three dimensions
* and of a line and a plane in three dimensions. The inputs are in the form of
* arrays or 1 dimensional matrices. The line intersection functions return null
* if the lines do not meet.
*
* Note: Fill the plane coefficients as `x + y + z = c` and not as `x + y + z + c = 0`.
*
* Syntax:
*
* math.intersect(endPoint1Line1, endPoint2Line1, endPoint1Line2, endPoint2Line2)
* math.intersect(endPoint1, endPoint2, planeCoefficients)
*
* Examples:
*
* math.intersect([0, 0], [10, 10], [10, 0], [0, 10]); // Returns [5, 5]
* math.intersect([0, 0, 0], [10, 10, 0], [10, 0, 0], [0, 10, 0]); // Returns [5, 5, 0]
* math.intersect([1, 0, 1], [4, -2, 2], [1, 1, 1, 6]); // Returns [7, -4, 3]
*
* @param {Array | Matrix} w Co-ordinates of first end-point of first line
* @param {Array | Matrix} x Co-ordinates of second end-point of first line
* @param {Array | Matrix} y Co-ordinates of first end-point of second line
* OR Co-efficients of the plane's equation
* @param {Array | Matrix} z Co-ordinates of second end-point of second line
* OR null if the calculation is for line and plane
* @return {Array} Returns the point of intersection of lines/lines-planes
*/
var intersect = typed('intersect', {
'Array, Array, Array': function (x, y, plane) {
if (!_3d(x)) { throw new TypeError('Array with 3 numbers expected for first argument'); }
if (!_3d(y)) { throw new TypeError('Array with 3 numbers expected for second argument'); }
if (!_4d(plane)) { throw new TypeError('Array with 4 numbers expected as third argument'); }
return _intersectLinePlane(x[0], x[1], x[2], y[0], y[1], y[2], plane[0], plane[1], plane[2], plane[3]);
},
'Array, Array, Array, Array': function (w, x, y, z) {
if (w.length === 2) {
if (!_2d(w)) { throw new TypeError('Array with 2 numbers expected for first argument'); }
if (!_2d(x)) { throw new TypeError('Array with 2 numbers expected for second argument'); }
if (!_2d(y)) { throw new TypeError('Array with 2 numbers expected for third argument'); }
if (!_2d(z)) { throw new TypeError('Array with 2 numbers expected for fourth argument'); }
return _intersect2d(w, x, y, z);
}
else if (w.length === 3) {
if (!_3d(w)) { throw new TypeError('Array with 3 numbers expected for first argument'); }
if (!_3d(x)) { throw new TypeError('Array with 3 numbers expected for second argument'); }
if (!_3d(y)) { throw new TypeError('Array with 3 numbers expected for third argument'); }
if (!_3d(z)) { throw new TypeError('Array with 3 numbers expected for fourth argument'); }
return _intersect3d(w[0], w[1], w[2], x[0], x[1], x[2], y[0], y[1], y[2], z[0], z[1], z[2]);
}
else {
throw new TypeError('Arrays with two or thee dimensional points expected');
}
},
'Matrix, Matrix, Matrix': function (x, y, plane) {
return matrix(intersect(x.valueOf(), y.valueOf(), plane.valueOf()));
},
'Matrix, Matrix, Matrix, Matrix': function (w, x, y, z) {
// TODO: output matrix type should match input matrix type
return matrix(intersect(w.valueOf(), x.valueOf(), y.valueOf(), z.valueOf()));
}
});
function _2d(x) {
return x.length === 2 && typeof x[0] === 'number' && typeof x[1] === 'number';
}
function _3d(x) {
return x.length === 3 && typeof x[0] === 'number' && typeof x[1] === 'number' && typeof x[2] === 'number';
}
function _4d(x) {
return x.length ...
n/a
function factory(type, config, load, typed) {
var matrix = load(require('../../type/matrix/function/matrix'));
var divideScalar = load(require('../arithmetic/divideScalar'));
var addScalar = load(require('../arithmetic/addScalar'));
var multiply = load(require('../arithmetic/multiply'));
var unaryMinus = load(require('../arithmetic/unaryMinus'));
var det = load(require('../matrix/det'));
var eye = load(require('./eye'));
/**
* Calculate the inverse of a square matrix.
*
* Syntax:
*
* math.inv(x)
*
* Examples:
*
* math.inv([[1, 2], [3, 4]]); // returns [[-2, 1], [1.5, -0.5]]
* math.inv(4); // returns 0.25
* 1 / 4; // returns 0.25
*
* See also:
*
* det, transpose
*
* @param {number | Complex | Array | Matrix} x Matrix to be inversed
* @return {number | Complex | Array | Matrix} The inverse of `x`.
*/
var inv = typed('inv', {
'Array | Matrix': function (x) {
var size = (x.isMatrix === true) ? x.size() : util.array.size(x);
switch (size.length) {
case 1:
// vector
if (size[0] == 1) {
if (x.isMatrix === true) {
return matrix([
divideScalar(1, x.valueOf()[0])
]);
}
else {
return [
divideScalar(1, x[0])
];
}
}
else {
throw new RangeError('Matrix must be square ' +
'(size: ' + util.string.format(size) + ')');
}
case 2:
// two dimensional array
var rows = size[0];
var cols = size[1];
if (rows == cols) {
if (x.isMatrix === true) {
return matrix(
_inv(x.valueOf(), rows, cols),
x.storage()
);
}
else {
// return an Array
return _inv(x, rows, cols);
}
}
else {
throw new RangeError('Matrix must be square ' +
'(size: ' + util.string.format(size) + ')');
}
default:
// multi dimensional array
throw new RangeError('Matrix must be two dimensional ' +
'(size: ' + util.string.format(size) + ')');
}
},
'any': function (x) {
// scalar
return divideScalar(1, x); // FIXME: create a BigNumber one when configured for bignumbers
}
});
/**
* Calculate the inverse of a square matrix
* @param {Array[]} mat A square matrix
* @param {number} rows Number of rows
* @param {number} cols Number of columns, must equal rows
* @return {Array[]} inv Inverse matrix
* @private
*/
function _inv (mat, rows, cols){
var r, s, f, value, temp;
if (rows == 1) {
// this is a 1 x 1 matrix
value = mat[0][0];
if (value == 0) {
throw Error('Cannot calculate inverse, determinant is zero');
}
return [[
divideScalar(1, value)
]];
}
else if (rows == 2) {
// this is a 2 x 2 matrix
var d = det(mat);
if (d == 0) {
throw Error('Cannot calculate inverse, determinant is zero');
}
return [
[
divideScalar(mat[1][1], d),
divideScalar(unaryMinus(mat[0][1]), d)
],
[
divideScalar(unaryMinus(mat[1][0]), d),
divideScalar(mat[0][0], d)
]
];
}
else {
// this is a matrix of 3 x 3 or larger
// calculate inverse using gauss-jordan elimination
// http://en.wikipedia.org/wiki/Gaussian_elimination
// http://mathworld.wolfram.com/MatrixInverse.html
// http://math.uww.edu/~mcfarlat/inverse.htm
// make a copy of the matrix (only the arrays, not of the elements)
var A = mat.concat();
for (r = 0; r < rows; r++) {
A[r] = A[r].concat();
}
// create an identity matrix which in the end will ...
n/a
function factory(type, config, load, typed) {
/**
* Test whether a value is an integer number.
* The function supports `number`, `BigNumber`, and `Fraction`.
*
* The function is evaluated element-wise in case of Array or Matrix input.
*
* Syntax:
*
* math.isInteger(x)
*
* Examples:
*
* math.isInteger(2); // returns true
* math.isInteger(0); // returns true
* math.isInteger(0.5); // returns false
* math.isInteger(math.bignumber(500)); // returns true
* math.isInteger(math.fraction(4)); // returns true
* math.isInteger('3'); // returns true
* math.isInteger([3, 0.5, -2]); // returns [true, false, true]
* math.isInteger(math.complex('2-4i'); // throws an error
*
* See also:
*
* isNumeric, isPositive, isNegative, isZero
*
* @param {number | BigNumber | Fraction | Array | Matrix} x Value to be tested
* @return {boolean} Returns true when `x` contains a numeric, integer value.
* Throws an error in case of an unknown data type.
*/
var isInteger = typed('isInteger', {
'number': number.isInteger, // TODO: what to do with isInteger(add(0.1, 0.2)) ?
'BigNumber': function (x) {
return x.isInt();
},
'Fraction': function (x) {
return x.d === 1 && isFinite(x.n);
},
'Array | Matrix': function (x) {
return deepMap(x, isInteger);
}
});
return isInteger;
}
n/a
function factory(type, config, load, typed) {
/**
* Test whether a value is NaN (not a number).
* The function supports types `number`, `BigNumber`, `Fraction`, `Unit` and `Complex`.
*
* The function is evaluated element-wise in case of Array or Matrix input.
*
* Syntax:
*
* math.isNaN(x)
*
* Examples:
*
* math.isNaN(3); // returns false
* math.isNaN(NaN); // returns true
* math.isNaN(0); // returns false
* math.isNaN(math.bignumber(NaN)); // returns true
* math.isNaN(math.bignumber(0)); // returns false
* math.isNaN(math.fraction(-2, 5)); // returns false
* math.isNaN('-2'); // returns false
* math.isNaN([2, 0, -3, NaN]'); // returns [false, false, false, true]
*
* See also:
*
* isNumeric, isNegative, isPositive, isZero, isInteger
*
* @param {number | BigNumber | Fraction | Unit | Array | Matrix} x Value to be tested
* @return {boolean} Returns true when `x` is NaN.
* Throws an error in case of an unknown data type.
*/
var isNaN = typed('isNaN', {
'number': function (x) {
return Number.isNaN(x);
},
'BigNumber': function (x) {
return x.isNaN();
},
'Fraction': function (x) {
return false;
},
'Complex': function (x) {
return Number.isNaN(x.re) && Number.isNaN(x.im);
},
'Unit': function (x) {
return Number.isNaN(x.value);
},
'Array | Matrix': function (x) {
return deepMap(x, Number.isNaN);
}
});
return isNaN;
}
n/a
function factory(type, config, load, typed) {
/**
* Test whether a value is negative: smaller than zero.
* The function supports types `number`, `BigNumber`, `Fraction`, and `Unit`.
*
* The function is evaluated element-wise in case of Array or Matrix input.
*
* Syntax:
*
* math.isNegative(x)
*
* Examples:
*
* math.isNegative(3); // returns false
* math.isNegative(-2); // returns true
* math.isNegative(0); // returns false
* math.isNegative(-0); // returns false
* math.isNegative(math.bignumber(2)); // returns false
* math.isNegative(math.fraction(-2, 5)); // returns true
* math.isNegative('-2'); // returns true
* math.isNegative([2, 0, -3]'); // returns [false, false, true]
*
* See also:
*
* isNumeric, isPositive, isZero, isInteger
*
* @param {number | BigNumber | Fraction | Unit | Array | Matrix} x Value to be tested
* @return {boolean} Returns true when `x` is larger than zero.
* Throws an error in case of an unknown data type.
*/
var isNegative = typed('isNegative', {
'number': function (x) {
return x < 0;
},
'BigNumber': function (x) {
return x.isNeg() && !x.isZero() && !x.isNaN();
},
'Fraction': function (x) {
return x.s < 0; // It's enough to decide on the sign
},
'Unit': function (x) {
return isNegative(x.value);
},
'Array | Matrix': function (x) {
return deepMap(x, isNegative);
}
});
return isNegative;
}
n/a
function factory(type, config, load, typed) {
/**
* Test whether a value is an numeric value.
*
* The function is evaluated element-wise in case of Array or Matrix input.
*
* Syntax:
*
* math.isNumeric(x)
*
* Examples:
*
* math.isNumeric(2); // returns true
* math.isNumeric(0); // returns true
* math.isNumeric(math.bignumber(500)); // returns true
* math.isNumeric(math.fraction(4)); // returns true
* math.isNumeric(math.complex('2-4i'); // returns false
* math.isNumeric('3'); // returns false
* math.isNumeric([2.3, 'foo', false]); // returns [true, false, true]
*
* See also:
*
* isZero, isPositive, isNegative, isInteger
*
* @param {*} x Value to be tested
* @return {boolean} Returns true when `x` is a `number`, `BigNumber`,
* `Fraction`, or `boolean`. Returns false for other types.
* Throws an error in case of unknown types.
*/
var isNumeric = typed('isNumeric', {
'number | BigNumber | Fraction | boolean': function () {
return true;
},
'Complex | Unit | string': function () {
return false;
},
'Array | Matrix': function (x) {
return deepMap(x, isNumeric);
}
});
return isNumeric;
}
n/a
function factory(type, config, load, typed) {
/**
* Test whether a value is positive: larger than zero.
* The function supports types `number`, `BigNumber`, `Fraction`, and `Unit`.
*
* The function is evaluated element-wise in case of Array or Matrix input.
*
* Syntax:
*
* math.isPositive(x)
*
* Examples:
*
* math.isPositive(3); // returns true
* math.isPositive(-2); // returns false
* math.isPositive(0); // returns false
* math.isPositive(-0); // returns false
* math.isPositive(0.5); // returns true
* math.isPositive(math.bignumber(2)); // returns true
* math.isPositive(math.fraction(-2, 5)); // returns false
* math.isPositive(math.fraction(1,3)); // returns false
* math.isPositive('2'); // returns true
* math.isPositive([2, 0, -3]'); // returns [true, false, false]
*
* See also:
*
* isNumeric, isZero, isNegative, isInteger
*
* @param {number | BigNumber | Fraction | Unit | Array | Matrix} x Value to be tested
* @return {boolean} Returns true when `x` is larger than zero.
* Throws an error in case of an unknown data type.
*/
var isPositive = typed('isPositive', {
'number': function (x) {
return x > 0;
},
'BigNumber': function (x) {
return !x.isNeg() && !x.isZero() && !x.isNaN();
},
'Fraction': function (x) {
return x.s > 0 && x.n > 0;
},
'Unit': function (x) {
return isPositive(x.value);
},
'Array | Matrix': function (x) {
return deepMap(x, isPositive);
}
});
return isPositive;
}
n/a
function factory(type, config, load, typed) {
/**
* Test whether a value is prime: has no divisors other than itself and one.
* The function supports type `number`, `bignumber`.
*
* The function is evaluated element-wise in case of Array or Matrix input.
*
* Syntax:
*
* math.isPrime(x)
*
* Examples:
*
* math.isPrime(3); // returns true
* math.isPrime(-2); // returns false
* math.isPrime(0); // returns false
* math.isPrime(-0); // returns false
* math.isPrime(0.5); // returns false
* math.isPrime('2'); // returns true
* math.isPrime([2, 17, 100]'); // returns [true, true, false]
*
* See also:
*
* isNumeric, isZero, isNegative, isInteger
*
* @param {number | BigNumber | Array | Matrix} x Value to be tested
* @return {boolean} Returns true when `x` is larger than zero.
* Throws an error in case of an unknown data type.
*/
var isPrime = typed('isPrime', {
'number': function (x) {
if (x < 2){
return false;
}
if (x == 2){
return true;
}
if (x % 2 == 0){
return false;
}
for (var i = 3; i * i <= x; i += 2){
if (x % i == 0){
return false;
}
}
return true;
},
'BigNumber': function (x) {
if (x.lt(2)){
return false;
}
if (x.equals(2)){
return true;
}
if (x.mod(2).isZero()){
return false;
}
for(var i = type.BigNumber(3); i.times(i).lte(x); i = i.plus(1)){
if (x.mod(i).isZero()){
return false;
}
}
return true;
},
'Array | Matrix': function (x) {
return deepMap(x, isPrime);
}
});
return isPrime;
}
n/a
function factory(type, config, load, typed) {
/**
* Test whether a value is zero.
* The function can check for zero for types `number`, `BigNumber`, `Fraction`,
* `Complex`, and `Unit`.
*
* The function is evaluated element-wise in case of Array or Matrix input.
*
* Syntax:
*
* math.isZero(x)
*
* Examples:
*
* math.isZero(0); // returns true
* math.isZero(2); // returns false
* math.isZero(0.5); // returns false
* math.isZero(math.bignumber(0)); // returns true
* math.isZero(math.fraction(0)); // returns true
* math.isZero(math.fraction(1,3)); // returns false
* math.isZero(math.complex('2 - 4i'); // returns false
* math.isZero(math.complex('0i'); // returns true
* math.isZero('0'); // returns true
* math.isZero('2'); // returns false
* math.isZero([2, 0, -3]'); // returns [false, true, false]
*
* See also:
*
* isNumeric, isPositive, isNegative, isInteger
*
* @param {number | BigNumber | Complex | Fraction | Unit | Array | Matrix} x Value to be tested
* @return {boolean} Returns true when `x` is zero.
* Throws an error in case of an unknown data type.
*/
var isZero = typed('isZero', {
'number': function (x) {
return x === 0;
},
'BigNumber': function (x) {
return x.isZero();
},
'Complex': function (x) {
return x.re === 0 && x.im === 0;
},
'Fraction': function (x) {
return x.d === 1 && x.n === 0;
},
'Unit': function (x) {
return isZero(x.value);
},
'Array | Matrix': function (x) {
return deepMap(x, isZero);
}
});
return isZero;
}
n/a
function reviver(key, value) { var constructor = type[value && value.mathjs]; if (constructor && typeof constructor.fromJSON === 'function') { return constructor.fromJSON(value); } return value; }
n/a
function factory(type, config, load, typed) {
var matrix = load(require('../../type/matrix/function/matrix'));
var divide = load(require('../arithmetic/divide'));
var sum = load(require('../statistics/sum'));
var multiply = load(require('../arithmetic/multiply'));
var dotDivide = load(require('../arithmetic/dotDivide'));
var log = load(require('../arithmetic/log'));
var isNumeric = load(require('../utils/isNumeric'));
/**
* Calculate the Kullback-Leibler (KL) divergence between two distributions
*
* Syntax:
*
* math.kldivergence(x, y)
*
* Examples:
*
* math.kldivergence([0.7,0.5,0.4], [0.2,0.9,0.5]); //returns 0.24376698773121153
*
*
* @param {Array | Matrix} q First vector
* @param {Array | Matrix} p Second vector
* @return {number} Returns distance between q and p
*/
var kldivergence = typed('kldivergence', {
'Array, Array': function(q, p) {
return _kldiv(matrix(q), matrix(p));
},
'Matrix, Array': function(q, p) {
return _kldiv(q, matrix(p));
},
'Array, Matrix': function(q, p){
return _kldiv(matrix(q), p);
},
'Matrix, Matrix': function(q, p){
return _kldiv(q, p);
}
});
function _kldiv(q, p) {
var plength = p.size().length;
var qlength = q.size().length;
if (plength > 1) {
throw new Error('first object must be one dimensional');
}
if (qlength > 1) {
throw new Error('second object must be one dimensional');
}
if(plength !== qlength){
throw new Error("Length of two vectors must be equal");
}
//Before calculation, apply normalization
var sumq = sum(q);
if (sumq === 0) {
throw new Error("Sum of elements in first object must be non zero");
}
var sump = sum(p);
if (sump === 0) {
throw new Error("Sum of elements in second object must be non zero");
}
var qnorm = divide(q, sum(q));
var pnorm = divide(p, sum(p));
var result = sum(multiply(qnorm, log(dotDivide(qnorm, pnorm))));
if (isNumeric(result)) {
return result;
}
else {
return Number.NaN;
}
}
return kldivergence;
}
n/a
function factory(type, config, load, typed) {
var matrix = load(require('../../type/matrix/function/matrix'));
var multiplyScalar = load(require('../arithmetic/multiplyScalar'))
/**
* Calculates the kronecker product of 2 matrices or vectors.
*
* NOTE: If a one dimensional vector / matrix is given, it will be
* wrapped so its two dimensions.
* See the examples.
*
* Syntax:
*
* math.kron(x, y)
*
* Examples:
*
* math.kron([[1, 0], [0, 1]], [[1, 2], [3, 4]]);
* // returns [ [ 1, 2, 0, 0 ], [ 3, 4, 0, 0 ], [ 0, 0, 1, 2 ], [ 0, 0, 3, 4 ] ]
*
* math.kron([1,1], [2,3,4]);
* // returns [ [ 2, 3, 4, 2, 3, 4 ] ]
*
* See also:
*
* multiply, dot, cross
*
* @param {Array | Matrix} x First vector
* @param {Array | Matrix} y Second vector
* @return {Array | Matrix} Returns the kronecker product of `x` and `y`
*/
var kron = typed('kron', {
'Matrix, Matrix': function(x, y) {
return matrix(_kron(x.toArray(), y.toArray()));
},
'Matrix, Array': function(x, y) {
return matrix(_kron(x.toArray(), y));
},
'Array, Matrix': function(x, y) {
return matrix(_kron(x, y.toArray()));
},
'Array, Array': _kron
});
return kron;
/**
* Calculate the kronecker product of two matrices / vectors
* @param {Array} a First vector
* @param {Array} b Second vector
* @returns {Array} Returns the kronecker product of x and y
* @private
*/
function _kron(a, b) {
// Deal with the dimensions of the matricies.
if (size(a).length === 1) {
// Wrap it in a 2D Matrix
a = [a];
}
if (size(b).length === 1) {
// Wrap it in a 2D Matrix
b = [b]
}
if (size(a).length > 2 || size(b).length > 2) {
throw new RangeError('Vectors with dimensions greater then 2 are not supported expected ' +
'(Size x = ' + JSON.stringify(a.length) + ', y = ' + JSON.stringify(b.length) + ')');
}
var t = [];
var r = [];
return a.map(function(a) {
return b.map(function(b) {
return a.map(function(y) {
return b.map(function(x) {
return r.push(multiplyScalar(y, x));
});
}, t.push(r = []));
});
}, t = []) && t;
}
}
n/a
function factory(type, config, load, typed) {
var matrix = load(require('../../type/matrix/function/matrix'));
var algorithm03 = load(require('../../type/matrix/utils/algorithm03'));
var algorithm07 = load(require('../../type/matrix/utils/algorithm07'));
var algorithm12 = load(require('../../type/matrix/utils/algorithm12'));
var algorithm13 = load(require('../../type/matrix/utils/algorithm13'));
var algorithm14 = load(require('../../type/matrix/utils/algorithm14'));
var latex = require('../../utils/latex');
/**
* Test whether value x is larger than y.
*
* The function returns true when x is larger than y and the relative
* difference between x and y is larger than the configured epsilon. The
* function cannot be used to compare values smaller than approximately 2.22e-16.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.larger(x, y)
*
* Examples:
*
* math.larger(2, 3); // returns false
* math.larger(5, 2 + 2); // returns true
*
* var a = math.unit('5 cm');
* var b = math.unit('2 inch');
* math.larger(a, b); // returns false
*
* See also:
*
* equal, unequal, smaller, smallerEq, largerEq, compare
*
* @param {number | BigNumber | Fraction | boolean | Unit | string | Array | Matrix} x First value to compare
* @param {number | BigNumber | Fraction | boolean | Unit | string | Array | Matrix} y Second value to compare
* @return {boolean | Array | Matrix} Returns true when the x is larger than y, else returns false
*/
var larger = typed('larger', {
'boolean, boolean': function (x, y) {
return x > y;
},
'number, number': function (x, y) {
return x > y && !nearlyEqual(x, y, config.epsilon);
},
'BigNumber, BigNumber': function (x, y) {
return x.gt(y) && !bigNearlyEqual(x, y, config.epsilon);
},
'Fraction, Fraction': function (x, y) {
return x.compare(y) === 1;
},
'Complex, Complex': function () {
throw new TypeError('No ordering relation is defined for complex numbers');
},
'Unit, Unit': function (x, y) {
if (!x.equalBase(y)) {
throw new Error('Cannot compare units with different base');
}
return larger(x.value, y.value);
},
'string, string': function (x, y) {
return x > y;
},
'Matrix, Matrix': function (x, y) {
// result
var c;
// process matrix storage
switch (x.storage()) {
case 'sparse':
switch (y.storage()) {
case 'sparse':
// sparse + sparse
c = algorithm07(x, y, larger);
break;
default:
// sparse + dense
c = algorithm03(y, x, larger, true);
break;
}
break;
default:
switch (y.storage()) {
case 'sparse':
// dense + sparse
c = algorithm03(x, y, larger, false);
break;
default:
// dense + dense
c = algorithm13(x, y, larger);
break;
}
break;
}
return c;
},
'Array, Array': function (x, y) {
// use matrix implementation
return larger(matrix(x), matrix(y)).valueOf();
},
'Array, Matrix': function (x, y) {
// use matrix implementation
return larger(matrix(x), y);
},
'Matrix, Array': function (x, y) {
// use matrix implementation
return larger(x, matrix(y));
},
'Matrix, any': function (x, y) {
// result
var c;
// check storage format
switch (x.storage()) {
case 'sparse':
c = algorithm12(x, y, larger, false);
break;
default:
c = algorithm14(x, y, larger, false);
break;
}
return c;
},
'any, Matrix': function (x, y) {
// result
var c;
// check storage format
switch (y.storage()) {
case 'sparse': ...
n/a
function factory(type, config, load, typed) {
var matrix = load(require('../../type/matrix/function/matrix'));
var algorithm03 = load(require('../../type/matrix/utils/algorithm03'));
var algorithm07 = load(require('../../type/matrix/utils/algorithm07'));
var algorithm12 = load(require('../../type/matrix/utils/algorithm12'));
var algorithm13 = load(require('../../type/matrix/utils/algorithm13'));
var algorithm14 = load(require('../../type/matrix/utils/algorithm14'));
var latex = require('../../utils/latex');
/**
* Test whether value x is larger or equal to y.
*
* The function returns true when x is larger than y or the relative
* difference between x and y is smaller than the configured epsilon. The
* function cannot be used to compare values smaller than approximately 2.22e-16.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.largerEq(x, y)
*
* Examples:
*
* math.larger(2, 1 + 1); // returns false
* math.largerEq(2, 1 + 1); // returns true
*
* See also:
*
* equal, unequal, smaller, smallerEq, larger, compare
*
* @param {number | BigNumber | Fraction | boolean | Unit | string | Array | Matrix} x First value to compare
* @param {number | BigNumber | Fraction | boolean | Unit | string | Array | Matrix} y Second value to compare
* @return {boolean | Array | Matrix} Returns true when the x is larger or equal to y, else returns false
*/
var largerEq = typed('largerEq', {
'boolean, boolean': function (x, y) {
return x >= y;
},
'number, number': function (x, y) {
return x >= y || nearlyEqual(x, y, config.epsilon);
},
'BigNumber, BigNumber': function (x, y) {
return x.gte(y) || bigNearlyEqual(x, y, config.epsilon);
},
'Fraction, Fraction': function (x, y) {
return x.compare(y) !== -1;
},
'Complex, Complex': function () {
throw new TypeError('No ordering relation is defined for complex numbers');
},
'Unit, Unit': function (x, y) {
if (!x.equalBase(y)) {
throw new Error('Cannot compare units with different base');
}
return largerEq(x.value, y.value);
},
'string, string': function (x, y) {
return x >= y;
},
'Matrix, Matrix': function (x, y) {
// result
var c;
// process matrix storage
switch (x.storage()) {
case 'sparse':
switch (y.storage()) {
case 'sparse':
// sparse + sparse
c = algorithm07(x, y, largerEq);
break;
default:
// sparse + dense
c = algorithm03(y, x, largerEq, true);
break;
}
break;
default:
switch (y.storage()) {
case 'sparse':
// dense + sparse
c = algorithm03(x, y, largerEq, false);
break;
default:
// dense + dense
c = algorithm13(x, y, largerEq);
break;
}
break;
}
return c;
},
'Array, Array': function (x, y) {
// use matrix implementation
return largerEq(matrix(x), matrix(y)).valueOf();
},
'Array, Matrix': function (x, y) {
// use matrix implementation
return largerEq(matrix(x), y);
},
'Matrix, Array': function (x, y) {
// use matrix implementation
return largerEq(x, matrix(y));
},
'Matrix, any': function (x, y) {
// result
var c;
// check storage format
switch (x.storage()) {
case 'sparse':
c = algorithm12(x, y, largerEq, false);
break;
default:
c = algorithm14(x, y, largerEq, false);
break;
}
return c;
},
'any, Matrix': function (x, y) {
// result
var c;
// check storage format
switch (y.storage()) {
case 'sparse':
c = algorithm12(y, x, largerEq, true);
break;
default: ...
n/a
toSymbol = function (name, isUnit) { isUnit = typeof isUnit === 'undefined' ? false : isUnit; if (isUnit) { if (units.hasOwnProperty(name)) { return units[name]; } return '\\mathrm{' + name + '}'; } if (exports.symbols.hasOwnProperty(name)) { return exports.symbols[name]; } else if (name.indexOf('_') !== -1) { //symbol with index (eg. alpha_1) var index = name.indexOf('_'); return exports.toSymbol(name.substring(0, index)) + '_{' + exports.toSymbol(name.substring(index + 1)) + '}'; } return name; }
...
if (exports.symbols.hasOwnProperty(name)) {
return exports.symbols[name];
}
else if (name.indexOf('_') !== -1) {
//symbol with index (eg. alpha_1)
var index = name.indexOf('_');
return exports.toSymbol(name.substring(0, index)) + '_{'
+ exports.toSymbol(name.substring(index + 1)) + '}';
}
return name;
};
...
function factory(type, config, load, typed) {
var matrix = load(require('../../type/matrix/function/matrix'));
var algorithm02 = load(require('../../type/matrix/utils/algorithm02'));
var algorithm06 = load(require('../../type/matrix/utils/algorithm06'));
var algorithm11 = load(require('../../type/matrix/utils/algorithm11'));
var algorithm13 = load(require('../../type/matrix/utils/algorithm13'));
var algorithm14 = load(require('../../type/matrix/utils/algorithm14'));
/**
* Calculate the least common multiple for two or more values or arrays.
*
* lcm is defined as:
*
* lcm(a, b) = abs(a * b) / gcd(a, b)
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.lcm(a, b)
* math.lcm(a, b, c, ...)
*
* Examples:
*
* math.lcm(4, 6); // returns 12
* math.lcm(6, 21); // returns 42
* math.lcm(6, 21, 5); // returns 210
*
* math.lcm([4, 6], [6, 21]); // returns [12, 42]
*
* See also:
*
* gcd, xgcd
*
* @param {... number | BigNumber | Array | Matrix} args Two or more integer numbers
* @return {number | BigNumber | Array | Matrix} The least common multiple
*/
var lcm = typed('lcm', {
'number, number': _lcm,
'BigNumber, BigNumber': _lcmBigNumber,
'Fraction, Fraction': function (x, y) {
return x.lcm(y);
},
'Matrix, Matrix': function (x, y) {
// result
var c;
// process matrix storage
switch (x.storage()) {
case 'sparse':
switch (y.storage()) {
case 'sparse':
// sparse + sparse
c = algorithm06(x, y, lcm);
break;
default:
// sparse + dense
c = algorithm02(y, x, lcm, true);
break;
}
break;
default:
switch (y.storage()) {
case 'sparse':
// dense + sparse
c = algorithm02(x, y, lcm, false);
break;
default:
// dense + dense
c = algorithm13(x, y, lcm);
break;
}
break;
}
return c;
},
'Array, Array': function (x, y) {
// use matrix implementation
return lcm(matrix(x), matrix(y)).valueOf();
},
'Array, Matrix': function (x, y) {
// use matrix implementation
return lcm(matrix(x), y);
},
'Matrix, Array': function (x, y) {
// use matrix implementation
return lcm(x, matrix(y));
},
'Matrix, number | BigNumber': function (x, y) {
// result
var c;
// check storage format
switch (x.storage()) {
case 'sparse':
c = algorithm11(x, y, lcm, false);
break;
default:
c = algorithm14(x, y, lcm, false);
break;
}
return c;
},
'number | BigNumber, Matrix': function (x, y) {
// result
var c;
// check storage format
switch (y.storage()) {
case 'sparse':
c = algorithm11(y, x, lcm, true);
break;
default:
c = algorithm14(y, x, lcm, true);
break;
}
return c;
},
'Array, number | BigNumber': function (x, y) {
// use matrix implementation
return algorithm14(matrix(x), y, lcm, false).valueOf();
},
'number | BigNumber, Array': function (x, y) {
// use matrix implementation
return algorithm14(matrix(y), x, lcm, true).valueOf();
},
// TODO: need a smarter notation here
'Array | Matrix | number | BigNumber, Array | Matrix | number | BigNumber, ...Array | Matrix | number | BigNumber': function
(a, b, args) {
var res = lcm(a, b);
for (var i = 0; i < args.length; i++) {
res = lcm(res, args[i]);
}
return res;
}
});
lcm.toTex = undefined; // use default template
return lcm;
/**
* Calculate lcm for two BigNumbers
* @param {BigNumber} a
* @param {BigNu ...
n/a
function factory(type, config, load, typed) {
var latex = require('../../utils/latex');
var matrix = load(require('../../type/matrix/function/matrix'));
var equalScalar = load(require('../relational/equalScalar'));
var zeros = load(require('../matrix/zeros'));
var algorithm01 = load(require('../../type/matrix/utils/algorithm01'));
var algorithm02 = load(require('../../type/matrix/utils/algorithm02'));
var algorithm08 = load(require('../../type/matrix/utils/algorithm08'));
var algorithm10 = load(require('../../type/matrix/utils/algorithm10'));
var algorithm11 = load(require('../../type/matrix/utils/algorithm11'));
var algorithm13 = load(require('../../type/matrix/utils/algorithm13'));
var algorithm14 = load(require('../../type/matrix/utils/algorithm14'));
/**
* Bitwise left logical shift of a value x by y number of bits, `x << y`.
* For matrices, the function is evaluated element wise.
* For units, the function is evaluated on the best prefix base.
*
* Syntax:
*
* math.leftShift(x, y)
*
* Examples:
*
* math.leftShift(1, 2); // returns number 4
*
* math.leftShift([1, 2, 3], 4); // returns Array [16, 32, 64]
*
* See also:
*
* leftShift, bitNot, bitOr, bitXor, rightArithShift, rightLogShift
*
* @param {number | BigNumber | Array | Matrix} x Value to be shifted
* @param {number | BigNumber} y Amount of shifts
* @return {number | BigNumber | Array | Matrix} `x` shifted left `y` times
*/
var leftShift = typed('leftShift', {
'number, number': function (x, y) {
if (!isInteger(x) || !isInteger(y)) {
throw new Error('Integers expected in function leftShift');
}
return x << y;
},
'BigNumber, BigNumber': bigLeftShift,
'Matrix, Matrix': function (x, y) {
// result
var c;
// process matrix storage
switch (x.storage()) {
case 'sparse':
switch (y.storage()) {
case 'sparse':
// sparse & sparse
c = algorithm08(x, y, leftShift, false);
break;
default:
// sparse & dense
c = algorithm02(y, x, leftShift, true);
break;
}
break;
default:
switch (y.storage()) {
case 'sparse':
// dense & sparse
c = algorithm01(x, y, leftShift, false);
break;
default:
// dense & dense
c = algorithm13(x, y, leftShift);
break;
}
break;
}
return c;
},
'Array, Array': function (x, y) {
// use matrix implementation
return leftShift(matrix(x), matrix(y)).valueOf();
},
'Array, Matrix': function (x, y) {
// use matrix implementation
return leftShift(matrix(x), y);
},
'Matrix, Array': function (x, y) {
// use matrix implementation
return leftShift(x, matrix(y));
},
'Matrix, number | BigNumber': function (x, y) {
// check scalar
if (!equalScalar(y, 0)) {
// result
var c;
// check storage format
switch (x.storage()) {
case 'sparse':
c = algorithm11(x, y, leftShift, false);
break;
default:
c = algorithm14(x, y, leftShift, false);
break;
}
return c;
}
return x.clone();
},
'number | BigNumber, Matrix': function (x, y) {
// check scalar
if (!equalScalar(x, 0)) {
// result
var c;
// check storage format
switch (y.storage()) {
case 'sparse':
c = algorithm10(y, x, leftShift, true);
break;
default:
c = algorithm14(y, x, leftShift, true);
break;
}
return c;
}
return zeros(y.size(), y.storage());
},
'Array, number | BigNumber': function (x, y) {
// use matrix implementation
return leftShift(matrix(x), y).valueOf( ...
n/a
function factory(type, config, load, typed) {
/**
* Calculate the 10-base logarithm of a value. This is the same as calculating `log(x, 10)`.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.log10(x)
*
* Examples:
*
* math.log10(0.00001); // returns -5
* math.log10(10000); // returns 4
* math.log(10000) / math.log(10); // returns 4
* math.pow(10, 4); // returns 10000
*
* See also:
*
* exp, log
*
* @param {number | BigNumber | Complex | Array | Matrix} x
* Value for which to calculate the logarithm.
* @return {number | BigNumber | Complex | Array | Matrix}
* Returns the 10-base logarithm of `x`
*/
var log10 = typed('log10', {
'number': function (x) {
if (x >= 0 || config.predictable) {
return _log10(x);
}
else {
// negative value -> complex value computation
return new type.Complex(x, 0).log().div(Math.LN10);
}
},
'Complex': function (x) {
return new type.Complex(x).log().div(Math.LN10);
},
'BigNumber': function (x) {
if (!x.isNegative() || config.predictable) {
return x.log();
}
else {
// downgrade to number, return Complex valued result
return new type.Complex(x.toNumber(), 0).log().div(Math.LN10);
}
},
'Array | Matrix': function (x) {
return deepMap(x, log10);
}
});
log10.toTex = {1: '\\log_{10}\\left(${args[0]}\\right)'};
return log10;
}
n/a
function factory(type, config, load, typed) {
var abs = load(require('../arithmetic/abs'));
var map = load(require('../matrix/map'));
var median = load(require('../statistics/median'));
var subtract = load(require('../arithmetic/subtract'));
/**
* Compute the median absolute deviation of a matrix or a list with values.
* The median absolute deviation is defined as the median of the absolute
* deviations from the median.
*
* Syntax:
*
* math.mad(a, b, c, ...)
* math.mad(A)
*
* Examples:
*
* math.mad(10, 20, 30); // returns 10
* math.mad([1, 2, 3]); // returns 1
* math.mad([[1, 2, 3], [4, 5, 6]]); // returns 1.5
*
* See also:
*
* median, mean, std, abs
*
* @param {Array | Matrix} array
* A single matrix or multiple scalar values.
* @return {*} The median absolute deviation.
*/
var mad = typed('mad', {
// mad([a, b, c, d, ...])
'Array | Matrix': _mad,
// mad(a, b, c, d, ...)
'...': function (args) {
return _mad(args);
}
});
mad.toTex = undefined; // use default template
return mad;
function _mad(array) {
array = flatten(array.valueOf());
if (array.length === 0) {
throw new Error('Cannot calculate median absolute deviation of an empty array');
}
var med = median(array);
return median(map(array, function (value) {
return abs(subtract(value, med));
}));
}
}
n/a
function factory(type, config, load, typed) {
/**
* Create a new matrix or array with the results of the callback function executed on
* each entry of the matrix/array.
*
* Syntax:
*
* math.map(x, callback)
*
* Examples:
*
* math.map([1, 2, 3], function(value) {
* return value * value;
* }); // returns [1, 4, 9]
*
* See also:
*
* filter, forEach, sort
*
* @param {Matrix | Array} x The matrix to iterate on.
* @param {Function} callback The callback method is invoked with three
* parameters: the value of the element, the index
* of the element, and the matrix being traversed.
* @return {Matrix | array} Transformed map of x
*/
var map = typed('map', {
'Array, function': _map,
'Matrix, function': function (x, callback) {
return x.map(callback);
}
});
map.toTex = undefined; // use default template
return map;
}
n/a
function factory(type, config, load, typed) { var map = load(require('../../function/matrix/map')); var matrix = load(require('../../type/matrix/function/matrix')); return typed('max', { 'Array, function': function (x, callback) { return _map(x, callback, x); }, 'Matrix, function': function (x, callback) { return matrix(_map(x.valueOf(), callback, x)); } }); }
n/a
function factory(type, config, load, typed) {
var larger = load(require('../relational/larger'));
/**
* Compute the maximum value of a matrix or a list with values.
* In case of a multi dimensional array, the maximum of the flattened array
* will be calculated. When `dim` is provided, the maximum over the selected
* dimension will be calculated. Parameter `dim` is zero-based.
*
* Syntax:
*
* math.max(a, b, c, ...)
* math.max(A)
* math.max(A, dim)
*
* Examples:
*
* math.max(2, 1, 4, 3); // returns 4
* math.max([2, 1, 4, 3]); // returns 4
*
* // maximum over a specified dimension (zero-based)
* math.max([[2, 5], [4, 3], [1, 7]], 0); // returns [4, 7]
* math.max([[2, 5], [4, 3]], [1, 7], 1); // returns [5, 4, 7]
*
* math.max(2.7, 7.1, -4.5, 2.0, 4.1); // returns 7.1
* math.min(2.7, 7.1, -4.5, 2.0, 4.1); // returns -4.5
*
* See also:
*
* mean, median, min, prod, std, sum, var
*
* @param {... *} args A single matrix or or multiple scalar values
* @return {*} The maximum value
*/
var max = typed('max', {
// max([a, b, c, d, ...])
'Array | Matrix': _max,
// max([a, b, c, d, ...], dim)
'Array | Matrix, number | BigNumber': function (array, dim) {
return reduce(array, dim.valueOf(), _largest);
},
// max(a, b, c, d, ...)
'...': function (args) {
if (containsCollections(args)) {
throw new TypeError('Scalar values expected in function max');
}
return _max(args);
}
});
max.toTex = '\\max\\left(${args}\\right)';
return max;
/**
* Return the largest of two values
* @param {*} x
* @param {*} y
* @returns {*} Returns x when x is largest, or y when y is largest
* @private
*/
function _largest(x, y){
return larger(x, y) ? x : y;
}
/**
* Recursively calculate the maximum value in an n-dimensional array
* @param {Array} array
* @return {number} max
* @private
*/
function _max(array) {
var max = undefined;
deepForEach(array, function (value) {
if (max === undefined || larger(value, max)) {
max = value;
}
});
if (max === undefined) {
throw new Error('Cannot calculate max of an empty array');
}
return max;
}
}
n/a
function factory(type, config, load, typed) { var max = load(require('../../function/statistics/max')); return typed('max', { '...any': function (args) { // change last argument dim from one-based to zero-based if (args.length == 2 && isCollection(args[0])) { var dim = args[1]; if (typeof dim === 'number') { args[1] = dim - 1; } else if (dim && dim.isBigNumber === true) { args[1] = dim.minus(1); } } try { return max.apply(null, args); } catch (err) { throw errorTransform(err); } } }); }
n/a
function factory(type, config, load, typed) {
var add = load(require('../arithmetic/add'));
var divide = load(require('../arithmetic/divide'));
/**
* Compute the mean value of matrix or a list with values.
* In case of a multi dimensional array, the mean of the flattened array
* will be calculated. When `dim` is provided, the maximum over the selected
* dimension will be calculated. Parameter `dim` is zero-based.
*
* Syntax:
*
* math.mean(a, b, c, ...)
* math.mean(A)
* math.mean(A, dim)
*
* Examples:
*
* math.mean(2, 1, 4, 3); // returns 2.5
* math.mean([1, 2.7, 3.2, 4]); // returns 2.725
*
* math.mean([[2, 5], [6, 3], [1, 7]], 0); // returns [3, 5]
* math.mean([[2, 5], [6, 3], [1, 7]], 1); // returns [3.5, 4.5, 4]
*
* See also:
*
* median, min, max, sum, prod, std, var
*
* @param {... *} args A single matrix or or multiple scalar values
* @return {*} The mean of all values
*/
var mean = typed('mean', {
// mean([a, b, c, d, ...])
'Array | Matrix': _mean,
// mean([a, b, c, d, ...], dim)
'Array | Matrix, number | BigNumber': _nmean,
// mean(a, b, c, d, ...)
'...': function (args) {
if (containsCollections(args)) {
throw new TypeError('Scalar values expected in function mean');
}
return _mean(args);
}
});
mean.toTex = undefined; // use default template
return mean;
/**
* Calculate the mean value in an n-dimensional array, returning a
* n-1 dimensional array
* @param {Array} array
* @param {number} dim
* @return {number} mean
* @private
*/
function _nmean(array, dim){
var sum = reduce(array, dim, add);
var s = Array.isArray(array) ? size(array) : array.size();
return divide(sum, s[dim]);
}
/**
* Recursively calculate the mean value in an n-dimensional array
* @param {Array} array
* @return {number} mean
* @private
*/
function _mean(array) {
var sum = 0;
var num = 0;
deepForEach(array, function (value) {
sum = add(sum, value);
num++;
});
if (num === 0) {
throw new Error('Cannot calculate mean of an empty array');
}
return divide(sum, num);
}
}
n/a
function factory(type, config, load, typed) { var mean = load(require('../../function/statistics/mean')); return typed('mean', { '...any': function (args) { // change last argument dim from one-based to zero-based if (args.length == 2 && isCollection(args[0])) { var dim = args[1]; if (typeof dim === 'number') { args[1] = dim - 1; } else if (dim && dim.isBigNumber === true) { args[1] = dim.minus(1); } } try { return mean.apply(null, args); } catch (err) { throw errorTransform(err); } } }); }
n/a
function factory(type, config, load, typed) {
var add = load(require('../arithmetic/addScalar'));
var divide = load(require('../arithmetic/divideScalar'));
var compare = load(require('../relational/compare'));
var partitionSelect = load(require('../matrix/partitionSelect'));
/**
* Compute the median of a matrix or a list with values. The values are
* sorted and the middle value is returned. In case of an even number of
* values, the average of the two middle values is returned.
* Supported types of values are: Number, BigNumber, Unit
*
* In case of a (multi dimensional) array or matrix, the median of all
* elements will be calculated.
*
* Syntax:
*
* math.median(a, b, c, ...)
* math.median(A)
*
* Examples:
*
* math.median(5, 2, 7); // returns 5
* math.median([3, -1, 5, 7]); // returns 4
*
* See also:
*
* mean, min, max, sum, prod, std, var, quantileSeq
*
* @param {... *} args A single matrix or or multiple scalar values
* @return {*} The median
*/
var median = typed('median', {
// median([a, b, c, d, ...])
'Array | Matrix': _median,
// median([a, b, c, d, ...], dim)
'Array | Matrix, number | BigNumber': function (array, dim) {
// TODO: implement median(A, dim)
throw new Error('median(A, dim) is not yet supported');
//return reduce(arguments[0], arguments[1], ...);
},
// median(a, b, c, d, ...)
'...': function (args) {
if (containsCollections(args)) {
throw new TypeError('Scalar values expected in function median');
}
return _median(args);
}
});
/**
* Recursively calculate the median of an n-dimensional array
* @param {Array} array
* @return {Number} median
* @private
*/
function _median(array) {
array = flatten(array.valueOf());
var num = array.length;
if (num == 0) {
throw new Error('Cannot calculate median of an empty array');
}
if (num % 2 == 0) {
// even: return the average of the two middle values
var mid = num / 2 - 1;
var right = partitionSelect(array, mid + 1);
// array now partitioned at mid + 1, take max of left part
var left = array[mid];
for (var i = 0; i < mid; ++i) {
if (compare(array[i], left) > 0) {
left = array[i];
}
}
return middle2(left, right);
}
else {
// odd: return the middle value
var m = partitionSelect(array, (num - 1) / 2);
return middle(m);
}
}
// helper function to type check the middle value of the array
var middle = typed({
'number | BigNumber | Unit': function (value) {
return value;
}
});
// helper function to type check the two middle value of the array
var middle2 = typed({
'number | BigNumber | Unit, number | BigNumber | Unit': function (left, right) {
return divide(add(left, right), 2);
}
});
median.toTex = undefined; // use default template
return median;
}
n/a
function factory(type, config, load, typed) {
var matrix = load(require('../../type/matrix/function/matrix'));
var latex = require('../../utils/latex');
var algorithm02 = load(require('../../type/matrix/utils/algorithm02'));
var algorithm03 = load(require('../../type/matrix/utils/algorithm03'));
var algorithm05 = load(require('../../type/matrix/utils/algorithm05'));
var algorithm11 = load(require('../../type/matrix/utils/algorithm11'));
var algorithm12 = load(require('../../type/matrix/utils/algorithm12'));
var algorithm13 = load(require('../../type/matrix/utils/algorithm13'));
var algorithm14 = load(require('../../type/matrix/utils/algorithm14'));
/**
* Calculates the modulus, the remainder of an integer division.
*
* For matrices, the function is evaluated element wise.
*
* The modulus is defined as:
*
* x - y * floor(x / y)
*
* See http://en.wikipedia.org/wiki/Modulo_operation.
*
* Syntax:
*
* math.mod(x, y)
*
* Examples:
*
* math.mod(8, 3); // returns 2
* math.mod(11, 2); // returns 1
*
* function isOdd(x) {
* return math.mod(x, 2) != 0;
* }
*
* isOdd(2); // returns false
* isOdd(3); // returns true
*
* See also:
*
* divide
*
* @param {number | BigNumber | Fraction | Array | Matrix} x Dividend
* @param {number | BigNumber | Fraction | Array | Matrix} y Divisor
* @return {number | BigNumber | Fraction | Array | Matrix} Returns the remainder of `x` divided by `y`.
*/
var mod = typed('mod', {
'number, number': _mod,
'BigNumber, BigNumber': function (x, y) {
return y.isZero() ? x : x.mod(y);
},
'Fraction, Fraction': function (x, y) {
return x.mod(y);
},
'Matrix, Matrix': function (x, y) {
// result
var c;
// process matrix storage
switch (x.storage()) {
case 'sparse':
switch (y.storage()) {
case 'sparse':
// mod(sparse, sparse)
c = algorithm05(x, y, mod, false);
break;
default:
// mod(sparse, dense)
c = algorithm02(y, x, mod, true);
break;
}
break;
default:
switch (y.storage()) {
case 'sparse':
// mod(dense, sparse)
c = algorithm03(x, y, mod, false);
break;
default:
// mod(dense, dense)
c = algorithm13(x, y, mod);
break;
}
break;
}
return c;
},
'Array, Array': function (x, y) {
// use matrix implementation
return mod(matrix(x), matrix(y)).valueOf();
},
'Array, Matrix': function (x, y) {
// use matrix implementation
return mod(matrix(x), y);
},
'Matrix, Array': function (x, y) {
// use matrix implementation
return mod(x, matrix(y));
},
'Matrix, any': function (x, y) {
// result
var c;
// check storage format
switch (x.storage()) {
case 'sparse':
c = algorithm11(x, y, mod, false);
break;
default:
c = algorithm14(x, y, mod, false);
break;
}
return c;
},
'any, Matrix': function (x, y) {
// result
var c;
// check storage format
switch (y.storage()) {
case 'sparse':
c = algorithm12(y, x, mod, true);
break;
default:
c = algorithm14(y, x, mod, true);
break;
}
return c;
},
'Array, any': function (x, y) {
// use matrix implementation
return algorithm14(matrix(x), y, mod, false).valueOf();
},
'any, Array': function (x, y) {
// use matrix implementation
return algorithm14(matrix(y), x, mod, true).valueOf();
}
});
mod.toTex = {
2: '\\left(${args[0]}' + latex.operators['mod'] + '${args[1]}\\right)'
};
return mod;
/** ...
n/a
function factory(type, config, load, typed) {
/**
* Computes the mode of a set of numbers or a list with values(numbers or characters).
* If there are more than one modes, it returns a list of those values.
*
* Syntax:
*
* math.mode(a, b, c, ...)
* math.mode(A)
*
* Examples:
*
* math.mode(2, 1, 4, 3, 1); // returns [1]
* math.mode([1, 2.7, 3.2, 4, 2.7]); // returns [2.7]
* math.mode(1, 4, 6, 1, 6) // returns [1, 6]
* math.mode('a','a','b','c') // returns ["a"]
* math.mode(1, 1.5, 'abc') // returns [1, 1.5, "abc"]
*
* See also:
*
* median,
* mean
*
* @param {... *} args A single matrix
* @return {*} The mode of all values
*/
var mode = typed('mode', {
'Array | Matrix' : _mode,
'...': function (args) {
return _mode(args);
}
});
return mode;
/**
* Calculates the mode in an 1-dimensional array
* @param {Array} values
* @return {number} mode
* @private
*/
function _mode(values) {
values = flatten(values.valueOf());
var num = values.length;
if (num == 0) {
throw new Error('Cannot calculate mode of an empty array');
}
var count = {},
mode = [],
max = 0;
for (var i in values) {
if (!(values[i] in count)){
count[values[i]] = 0;
}
count[values[i]]++;
if (count[values[i]] == max){
mode.push(values[i]);
}
else if (count[values[i]] > max) {
max = count[values[i]];
mode = [values[i]];
}
}
return mode;
};
}
n/a
function factory(type, config, load, typed) {
var add = load(require('../arithmetic/add'));
var multiply = load(require('../arithmetic/multiply'));
var divide = load(require('../arithmetic/divide'));
var factorial = load(require('../probability/factorial'));
var isInteger = load(require('../utils/isInteger'));
var isPositive = load(require('../utils/isPositive'));
/**
* Multinomial Coefficients compute the number of ways of picking a1, a2, ..., ai unordered outcomes from `n` possibilities.
*
* multinomial takes one array of integers as an argument.
* The following condition must be enforced: every ai <= 0
*
* Syntax:
*
* math.multinomial(a) // a is an array type
*
* Examples:
*
* math.multinomial([1,2,1]); // returns 12
*
* See also:
*
* combinations, factorial
*
* @param {number[] | BigNumber[]} a Integer numbers of objects in the subset
* @return {Number | BigNumber} Multinomial coefficient.
*/
return typed('multinomial', {
'Array | Matrix': function (a) {
var sum = 0;
var denom = 1;
deepForEach(a, function(ai) {
if(!isInteger(ai) || !isPositive(ai)) {
throw new TypeError('Positive integer value expected in function multinomial');
}
sum = add(sum, ai);
denom = multiply(denom, factorial(ai));
});
return divide(factorial(sum), denom);
}
});
}
n/a
function factory(type, config, load, typed) {
var latex = require('../../utils/latex');
var matrix = load(require('../../type/matrix/function/matrix'));
var addScalar = load(require('./addScalar'));
var multiplyScalar = load(require('./multiplyScalar'));
var equalScalar = load(require('../relational/equalScalar'));
var algorithm11 = load(require('../../type/matrix/utils/algorithm11'));
var algorithm14 = load(require('../../type/matrix/utils/algorithm14'));
var DenseMatrix = type.DenseMatrix;
var SparseMatrix = type.SparseMatrix;
/**
* Multiply two or more values, `x * y`.
* For matrices, the matrix product is calculated.
*
* Syntax:
*
* math.multiply(x, y)
* math.multiply(x, y, z, ...)
*
* Examples:
*
* math.multiply(4, 5.2); // returns number 20.8
* math.multiply(2, 3, 4); // returns number 24
*
* var a = math.complex(2, 3);
* var b = math.complex(4, 1);
* math.multiply(a, b); // returns Complex 5 + 14i
*
* var c = [[1, 2], [4, 3]];
* var d = [[1, 2, 3], [3, -4, 7]];
* math.multiply(c, d); // returns Array [[7, -6, 17], [13, -4, 33]]
*
* var e = math.unit('2.1 km');
* math.multiply(3, e); // returns Unit 6.3 km
*
* See also:
*
* divide, prod, cross, dot
*
* @param {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} x First value to multiply
* @param {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} y Second value to multiply
* @return {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} Multiplication of `x` and `y`
*/
var multiply = typed('multiply', extend({
// we extend the signatures of multiplyScalar with signatures dealing with matrices
'Array, Array': function (x, y) {
// check dimensions
_validateMatrixDimensions(array.size(x), array.size(y));
// use dense matrix implementation
var m = multiply(matrix(x), matrix(y));
// return array or scalar
return (m && m.isMatrix === true) ? m.valueOf() : m;
},
'Matrix, Matrix': function (x, y) {
// dimensions
var xsize = x.size();
var ysize = y.size();
// check dimensions
_validateMatrixDimensions(xsize, ysize);
// process dimensions
if (xsize.length === 1) {
// process y dimensions
if (ysize.length === 1) {
// Vector * Vector
return _multiplyVectorVector(x, y, xsize[0]);
}
// Vector * Matrix
return _multiplyVectorMatrix(x, y);
}
// process y dimensions
if (ysize.length === 1) {
// Matrix * Vector
return _multiplyMatrixVector(x, y);
}
// Matrix * Matrix
return _multiplyMatrixMatrix(x, y);
},
'Matrix, Array': function (x, y) {
// use Matrix * Matrix implementation
return multiply(x, matrix(y));
},
'Array, Matrix': function (x, y) {
// use Matrix * Matrix implementation
return multiply(matrix(x, y.storage()), y);
},
'Matrix, any': function (x, y) {
// result
var c;
// process storage format
switch (x.storage()) {
case 'sparse':
c = algorithm11(x, y, multiplyScalar, false);
break;
case 'dense':
c = algorithm14(x, y, multiplyScalar, false);
break;
}
return c;
},
'any, Matrix': function (x, y) {
// result
var c;
// check storage format
switch (y.storage()) {
case 'sparse':
c = algorithm11(y, x, multiplyScalar, true);
break;
case 'dense':
c = algorithm14(y, x, multiplyScalar, true);
break;
}
return c;
},
'Array, any': function (x, y) {
// use matrix implementation
return algorithm14(matrix(x), y, multiplyScalar, false).valueOf();
},
'any, Array': function (x, y) {
// use matrix implementation
return algorithm14(matrix(y), x, multiplyScalar, tr ...
n/a
function factory(type, config, load, typed) {
/**
* Multiply two scalar values, `x * y`.
* This function is meant for internal use: it is used by the public function
* `multiply`
*
* This function does not support collections (Array or Matrix), and does
* not validate the number of of inputs.
*
* @param {number | BigNumber | Fraction | Complex | Unit} x First value to multiply
* @param {number | BigNumber | Fraction | Complex} y Second value to multiply
* @return {number | BigNumber | Fraction | Complex | Unit} Multiplication of `x` and `y`
* @private
*/
var multiplyScalar = typed('multiplyScalar', {
'number, number': function (x, y) {
return x * y;
},
'Complex, Complex': function (x, y) {
return x.mul(y);
},
'BigNumber, BigNumber': function (x, y) {
return x.times(y);
},
'Fraction, Fraction': function (x, y) {
return x.mul(y);
},
'number | Fraction | BigNumber | Complex, Unit': function (x, y) {
var res = y.clone();
res.value = (res.value === null) ? res._normalize(x) : multiplyScalar(res.value, x);
return res;
},
'Unit, number | Fraction | BigNumber | Complex': function (x, y) {
var res = x.clone();
res.value = (res.value === null) ? res._normalize(y) : multiplyScalar(res.value, y);
return res;
},
'Unit, Unit': function (x, y) {
return x.multiply(y);
}
});
return multiplyScalar;
}
n/a
function factory(type, config, load, typed) {
var abs = load(require('../arithmetic/abs'));
var add = load(require('../arithmetic/add'));
var pow = load(require('../arithmetic/pow'));
var sqrt = load(require('../arithmetic/sqrt'));
var multiply = load(require('../arithmetic/multiply'));
var equalScalar = load(require('../relational/equalScalar'));
var larger = load(require('../relational/larger'));
var smaller = load(require('../relational/smaller'));
var matrix = load(require('../../type/matrix/function/matrix'));
var trace = load(require('../matrix/trace'));
var transpose = load(require('../matrix/transpose'));
/**
* Calculate the norm of a number, vector or matrix.
*
* The second parameter p is optional. If not provided, it defaults to 2.
*
* Syntax:
*
* math.norm(x)
* math.norm(x, p)
*
* Examples:
*
* math.abs(-3.5); // returns 3.5
* math.norm(-3.5); // returns 3.5
*
* math.norm(math.complex(3, -4)); // returns 5
*
* math.norm([1, 2, -3], Infinity); // returns 3
* math.norm([1, 2, -3], -Infinity); // returns 1
*
* math.norm([3, 4], 2); // returns 5
*
* math.norm([[1, 2], [3, 4]], 1) // returns 6
* math.norm([[1, 2], [3, 4]], 'inf'); // returns 7
* math.norm([[1, 2], [3, 4]], 'fro'); // returns 5.477225575051661
*
* See also:
*
* abs, hypot
*
* @param {number | BigNumber | Complex | Array | Matrix} x
* Value for which to calculate the norm
* @param {number | BigNumber | string} [p=2]
* Vector space.
* Supported numbers include Infinity and -Infinity.
* Supported strings are: 'inf', '-inf', and 'fro' (The Frobenius norm)
* @return {number | BigNumber} the p-norm
*/
var norm = typed('norm', {
'number': Math.abs,
'Complex': function (x) {
return x.abs();
},
'BigNumber': function (x) {
// norm(x) = abs(x)
return x.abs();
},
'boolean | null' : function (x) {
// norm(x) = abs(x)
return Math.abs(x);
},
'Array': function (x) {
return _norm(matrix(x), 2);
},
'Matrix': function (x) {
return _norm(x, 2);
},
'number | Complex | BigNumber | boolean | null, number | BigNumber | string': function (x) {
// ignore second parameter, TODO: remove the option of second parameter for these types
return norm(x);
},
'Array, number | BigNumber | string': function (x, p) {
return _norm(matrix(x), p);
},
'Matrix, number | BigNumber | string': function (x, p) {
return _norm(x, p);
}
});
/**
* Calculate the norm for an array
* @param {Array} x
* @param {number | string} p
* @returns {number} Returns the norm
* @private
*/
function _norm (x, p) {
// size
var sizeX = x.size();
// check if it is a vector
if (sizeX.length == 1) {
// check p
if (p === Number.POSITIVE_INFINITY || p === 'inf') {
// norm(x, Infinity) = max(abs(x))
var pinf = 0;
// skip zeros since abs(0) == 0
x.forEach(
function (value) {
var v = abs(value);
if (larger(v, pinf))
pinf = v;
},
true);
return pinf;
}
if (p === Number.NEGATIVE_INFINITY || p === '-inf') {
// norm(x, -Infinity) = min(abs(x))
var ninf;
// skip zeros since abs(0) == 0
x.forEach(
function (value) {
var v = abs(value);
if (!ninf || smaller(v, ninf))
ninf = v;
},
true);
return ninf || 0;
}
if (p === 'fro') {
return _norm(x, 2);
}
if (typeof p === 'number' && !isNaN(p)) {
// check p != 0
if (!equalScalar(p, 0)) {
// norm(x, p) = sum(abs(xi) ^ p) ^ 1/p ...
n/a
function factory(type, config, load, typed) {
var latex = require('../../utils/latex');
/**
* Logical `not`. Flips boolean value of a given parameter.
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.not(x)
*
* Examples:
*
* math.not(2); // returns false
* math.not(0); // returns true
* math.not(true); // returns false
*
* a = [2, -7, 0];
* math.not(a); // returns [false, false, true]
*
* See also:
*
* and, or, xor
*
* @param {number | BigNumber | Complex | Unit | Array | Matrix} x First value to check
* @return {boolean | Array | Matrix}
* Returns true when input is a zero or empty value.
*/
var not = typed('not', {
'number': function (x) {
return !x;
},
'Complex': function (x) {
return x.re === 0 && x.im === 0;
},
'BigNumber': function (x) {
return x.isZero() || x.isNaN();
},
'Unit': function (x) {
return not(x.value);
},
'Array | Matrix': function (x) {
return deepMap(x, not);
}
});
not.toTex = {
1: latex.operators['not'] + '\\left(${args[0]}\\right)'
};
return not;
}
n/a
function factory(type, config, load, typed) {
var matrix = load(require('../../type/matrix/function/matrix'));
var algorithm01 = load(require('../../type/matrix/utils/algorithm01'));
var algorithm02 = load(require('../../type/matrix/utils/algorithm02'));
var algorithm06 = load(require('../../type/matrix/utils/algorithm06'));
var algorithm11 = load(require('../../type/matrix/utils/algorithm11'));
var algorithm13 = load(require('../../type/matrix/utils/algorithm13'));
var algorithm14 = load(require('../../type/matrix/utils/algorithm14'));
/**
* Calculate the nth root of a value.
* The principal nth root of a positive real number A, is the positive real
* solution of the equation
*
* x^root = A
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.nthRoot(a)
* math.nthRoot(a, root)
*
* Examples:
*
* math.nthRoot(9, 2); // returns 3, as 3^2 == 9
* math.sqrt(9); // returns 3, as 3^2 == 9
* math.nthRoot(64, 3); // returns 4, as 4^3 == 64
*
* See also:
*
* sqrt, pow
*
* @param {number | BigNumber | Array | Matrix | Complex} a
* Value for which to calculate the nth root
* @param {number | BigNumber} [root=2] The root.
* @return {number | Complex | Array | Matrix} Returns the nth root of `a`
*/
var nthRoot = typed('nthRoot', {
'number': function (x) {
return _nthRoot(x, 2);
},
'number, number': _nthRoot,
'BigNumber': function (x) {
return _bigNthRoot(x, new type.BigNumber(2));
},
'Complex' : function(x) {
return _nthComplexRoot(x, 2);
},
'Complex, number' : _nthComplexRoot,
'BigNumber, BigNumber': _bigNthRoot,
'Array | Matrix': function (x) {
return nthRoot(x, 2);
},
'Matrix, Matrix': function (x, y) {
// result
var c;
// process matrix storage
switch (x.storage()) {
case 'sparse':
switch (y.storage()) {
case 'sparse':
// density must be one (no zeros in matrix)
if (y.density() === 1) {
// sparse + sparse
c = algorithm06(x, y, nthRoot);
}
else {
// throw exception
throw new Error('Root must be non-zero');
}
break;
default:
// sparse + dense
c = algorithm02(y, x, nthRoot, true);
break;
}
break;
default:
switch (y.storage()) {
case 'sparse':
// density must be one (no zeros in matrix)
if (y.density() === 1) {
// dense + sparse
c = algorithm01(x, y, nthRoot, false);
}
else {
// throw exception
throw new Error('Root must be non-zero');
}
break;
default:
// dense + dense
c = algorithm13(x, y, nthRoot);
break;
}
break;
}
return c;
},
'Array, Array': function (x, y) {
// use matrix implementation
return nthRoot(matrix(x), matrix(y)).valueOf();
},
'Array, Matrix': function (x, y) {
// use matrix implementation
return nthRoot(matrix(x), y);
},
'Matrix, Array': function (x, y) {
// use matrix implementation
return nthRoot(x, matrix(y));
},
'Matrix, number | BigNumber': function (x, y) {
// result
var c;
// check storage format
switch (x.storage()) {
case 'sparse':
c = algorithm11(x, y, nthRoot, false);
break;
default:
c = algorithm14(x, y, nthRoot, false);
break;
}
return c;
},
'number | BigNumber, Matrix': function (x, y) {
// result
var c;
// check storage format
switch (y.storage()) {
case 'sparse':
// density must be one ( ...
n/a
function factory(type, config, load, typed) {
/**
* Create a number or convert a string, boolean, or unit to a number.
* When value is a matrix, all elements will be converted to number.
*
* Syntax:
*
* math.number(value)
* math.number(unit, valuelessUnit)
*
* Examples:
*
* math.number(2); // returns number 2
* math.number('7.2'); // returns number 7.2
* math.number(true); // returns number 1
* math.number([true, false, true, true]); // returns [1, 0, 1, 1]
* math.number(math.unit('52cm'), 'm'); // returns 0.52
*
* See also:
*
* bignumber, boolean, complex, index, matrix, string, unit
*
* @param {string | number | BigNumber | Fraction | boolean | Array | Matrix | Unit | null} [value] Value to be converted
* @param {Unit | string} [valuelessUnit] A valueless unit, used to convert a unit to a number
* @return {number | Array | Matrix} The created number
*/
var number = typed('number', {
'': function () {
return 0;
},
'number': function (x) {
return x;
},
'string': function (x) {
var num = Number(x);
if (isNaN(num)) {
throw new SyntaxError('String "' + x + '" is no valid number');
}
return num;
},
'BigNumber': function (x) {
return x.toNumber();
},
'Fraction': function (x) {
return x.valueOf();
},
'Unit': function (x) {
throw new Error('Second argument with valueless unit expected');
},
'Unit, string | Unit': function (unit, valuelessUnit) {
return unit.toNumber(valuelessUnit);
},
'Array | Matrix': function (x) {
return deepMap(x, number);
}
});
number.toTex = {
0: '0',
1: '\\left(${args[0]}\\right)',
2: '\\left(\\left(${args[0]}\\right)${args[1]}\\right)'
};
return number;
}
n/a
canDefineProperty = function () { // test needed for broken IE8 implementation try { if (Object.defineProperty) { Object.defineProperty({}, 'x', { get: function () {} }); return true; } } catch (e) {} return false; }
...
* of the properties value.
* @param {Object} object Object where to add the property
* @param {string} prop Property name
* @param {Function} fn Function returning the property value. Called
* without arguments.
*/
exports.lazy = function (object, prop, fn) {
if (exports.canDefineProperty()) {
var _uninitialized = true;
var _value;
Object.defineProperty(object, prop, {
get: function () {
if (_uninitialized) {
_value = fn();
_uninitialized = false;
...
function clone(x) { var type = typeof x; // immutable primitive types if (type === 'number' || type === 'string' || type === 'boolean' || x === null || x === undefined) { return x; } // use clone function of the object when available if (typeof x.clone === 'function') { return x.clone(); } // array if (Array.isArray(x)) { return x.map(function (value) { return clone(value); }); } if (x instanceof Number) return new Number(x.valueOf()); if (x instanceof String) return new String(x.valueOf()); if (x instanceof Boolean) return new Boolean(x.valueOf()); if (x instanceof Date) return new Date(x.valueOf()); if (x && x.isBigNumber === true) return x; // bignumbers are immutable if (x instanceof RegExp) throw new TypeError('Cannot clone ' + x); // TODO: clone a RegExp // object var m = {}; for (var key in x) { if (x.hasOwnProperty(key)) { m[key] = clone(x[key]); } } return m; }
...
return desc;
};
/**
* Export the help object to JSON
*/
Help.prototype.toJSON = function () {
var obj = object.clone(this.doc);
obj.mathjs = 'Help';
return obj;
};
/**
* Instantiate a Help object from a JSON object
* @param {Object} json
...
function deepEqual(a, b) { var prop, i, len; if (Array.isArray(a)) { if (!Array.isArray(b)) { return false; } if (a.length != b.length) { return false; } for (i = 0, len = a.length; i < len; i++) { if (!exports.deepEqual(a[i], b[i])) { return false; } } return true; } else if (a instanceof Object) { if (Array.isArray(b) || !(b instanceof Object)) { return false; } for (prop in a) { //noinspection JSUnfilteredForInLoop if (!exports.deepEqual(a[prop], b[prop])) { return false; } } for (prop in b) { //noinspection JSUnfilteredForInLoop if (!exports.deepEqual(a[prop], b[prop])) { return false; } } return true; } else { return (typeof a === typeof b) && (a == b); } }
...
}
if (a.length != b.length) {
return false;
}
for (i = 0, len = a.length; i < len; i++) {
if (!exports.deepEqual(a[i], b[i])) {
return false;
}
}
return true;
}
else if (a instanceof Object) {
if (Array.isArray(b) || !(b instanceof Object)) {
...
function deepExtend(a, b) { // TODO: add support for Arrays to deepExtend if (Array.isArray(b)) { throw new TypeError('Arrays are not supported by deepExtend'); } for (var prop in b) { if (b.hasOwnProperty(prop)) { if (b[prop] && b[prop].constructor === Object) { if (a[prop] === undefined) { a[prop] = {}; } if (a[prop].constructor === Object) { deepExtend(a[prop], b[prop]); } else { a[prop] = b[prop]; } } else if (Array.isArray(b[prop])) { throw new TypeError('Arrays are not supported by deepExtend'); } else { a[prop] = b[prop]; } } } return a; }
...
var prev = object.clone(config);
// validate some of the options
validateOption(options, 'matrix', MATRIX);
validateOption(options, 'number', NUMBER);
// merge options
object.deepExtend(config, options);
var curr = object.clone(config);
var changes = object.clone(options);
// emit 'config' event
math.emit('config', curr, prev, changes);
...
extend = function (a, b) { for (var prop in b) { if (b.hasOwnProperty(prop)) { a[prop] = b[prop]; } } return a; }
n/a
isFactory = function (object) { return object && typeof object.factory === 'function'; }
n/a
lazy = function (object, prop, fn) { if (exports.canDefineProperty()) { var _uninitialized = true; var _value; Object.defineProperty(object, prop, { get: function () { if (_uninitialized) { _value = fn(); _uninitialized = false; } return _value; }, set: function (value) { _value = value; _uninitialized = false; }, configurable: true, enumerable: true }); } else { // fall back to immediate evaluation object[prop] = fn(); } }
...
function setConstant(math, name, value) {
math[name] = value;
math.expression.mathWithTransform[name] = value;
}
// create a lazy constant in both math and mathWithTransform
function setLazyConstant (math, name, resolver) {
object.lazy(math, name, resolver);
object.lazy(math.expression.mathWithTransform, name, resolver);
}
exports.factory = factory;
exports.lazy = false; // no lazy loading of constants, the constants themselves are lazy when needed
exports.math = true; // request access to the math namespace
...
traverse = function (object, path) { var obj = object; if (path) { var names = path.split('.'); for (var i = 0; i < names.length; i++) { var name = names[i]; if (!(name in obj)) { obj[name] = {}; } obj = obj[name]; } } return obj; }
...
* otherwise. Function signature:
* callback(node: Node, index: string, parent: Node) : boolean
* @return {Node[]} nodes An array with nodes matching given filter criteria
*/
Node.prototype.filter = function (callback) {
var nodes = [];
this.traverse(function (node, path, parent) {
if (callback(node, path, parent)) {
nodes.push(node);
}
});
return nodes;
};
...
function factory(type, config, load, typed) {
var matrix = load(require('../../type/matrix/function/matrix'));
/**
* Create a matrix filled with ones. The created matrix can have one or
* multiple dimensions.
*
* Syntax:
*
* math.ones(m)
* math.ones(m, format)
* math.ones(m, n)
* math.ones(m, n, format)
* math.ones([m, n])
* math.ones([m, n], format)
* math.ones([m, n, p, ...])
* math.ones([m, n, p, ...], format)
*
* Examples:
*
* math.ones(3); // returns [1, 1, 1]
* math.ones(3, 2); // returns [[1, 1], [1, 1], [1, 1]]
* math.ones(3, 2, 'dense'); // returns Dense Matrix [[1, 1], [1, 1], [1, 1]]
*
* var A = [[1, 2, 3], [4, 5, 6]];
* math.ones(math.size(A)); // returns [[1, 1, 1], [1, 1, 1]]
*
* See also:
*
* zeros, eye, size, range
*
* @param {...number | Array} size The size of each dimension of the matrix
* @param {string} [format] The Matrix storage format
*
* @return {Array | Matrix | number} A matrix filled with ones
*/
var ones = typed('ones', {
'': function () {
return (config.matrix === 'Array')
? _ones([])
: _ones([], 'default');
},
// math.ones(m, n, p, ..., format)
// TODO: more accurate signature '...number | BigNumber, string' as soon as typed-function supports this
'...number | BigNumber | string': function (size) {
var last = size[size.length - 1];
if (typeof last === 'string') {
var format = size.pop();
return _ones(size, format);
}
else if (config.matrix === 'Array') {
return _ones(size);
}
else {
return _ones(size, 'default');
}
},
'Array': _ones,
'Matrix': function (size) {
var format = size.storage();
return _ones(size.valueOf(), format);
},
'Array | Matrix, string': function (size, format) {
return _ones (size.valueOf(), format);
}
});
ones.toTex = undefined; // use default template
return ones;
/**
* Create an Array or Matrix with ones
* @param {Array} size
* @param {string} [format='default']
* @return {Array | Matrix}
* @private
*/
function _ones(size, format) {
var hasBigNumbers = _normalize(size);
var defaultValue = hasBigNumbers ? new type.BigNumber(1) : 1;
_validate(size);
if (format) {
// return a matrix
var m = matrix(format);
if (size.length > 0) {
return m.resize(size, defaultValue);
}
return m;
}
else {
// return an Array
var arr = [];
if (size.length > 0) {
return resize(arr, size, defaultValue);
}
return arr;
}
}
// replace BigNumbers with numbers, returns true if size contained BigNumbers
function _normalize(size) {
var hasBigNumbers = false;
size.forEach(function (value, index, arr) {
if (value && value.isBigNumber === true) {
hasBigNumbers = true;
arr[index] = value.toNumber();
}
});
return hasBigNumbers;
}
// validate arguments
function _validate (size) {
size.forEach(function (value) {
if (typeof value !== 'number' || !isInteger(value) || value < 0) {
throw new Error('Parameters in function ones must be positive integers');
}
});
}
}
n/a
function getAssociativity(_node, parenthesis) { var node = _node; if (parenthesis !== 'keep') { //ParenthesisNodes are only ignored when not in 'keep' mode node = _node.getContent(); } var identifier = node.getIdentifier(); var index = getPrecedence(node, parenthesis); if (index === null) { //node isn't in the list return null; } var property = properties[index][identifier]; if (property.hasOwnProperty('associativity')) { if (property.associativity === 'left') { return 'left'; } if (property.associativity === 'right') { return 'right'; } //associativity is invalid throw Error('\'' + identifier + '\' has the invalid associativity \'' + property.associativity + '\'.'); } //associativity is undefined return null; }
...
* @param {boolean} latex
* @return {boolean[]}
* @private
*/
function calculateNecessaryParentheses(root, parenthesis, args, latex) {
//precedence of the root OperatorNode
var precedence = operators.getPrecedence(root, parenthesis);
var associativity = operators.getAssociativity(root, parenthesis);
if ((parenthesis === 'all') || ((args.length > 2) && (root.getIdentifier() !== 'OperatorNode:add
x27;) && (root.getIdentifier() !== 'OperatorNode:multiply'))) {
var parens = args.map(function (arg) {
switch (arg.getContent().type) { //Nodes that don't need extra parentheses
case 'ArrayNode':
case 'ConstantNode':
case 'SymbolNode':
...
function getPrecedence(_node, parenthesis) { var node = _node; if (parenthesis !== 'keep') { //ParenthesisNodes are only ignored when not in 'keep' mode node = _node.getContent(); } var identifier = node.getIdentifier(); for (var i = 0; i < properties.length; i++) { if (identifier in properties[i]) { return i; } } return null; }
...
* @private
*/
function needParenthesis(node, parenthesis) {
if (!parenthesis) {
parenthesis = 'keep';
}
var precedence = operators.getPrecedence(node, parenthesis);
var exprPrecedence = operators.getPrecedence(node.value, parenthesis);
return (parenthesis === 'all')
|| ((exprPrecedence !== null) && (exprPrecedence <= precedence));
}
/**
* Get string representation
...
function isAssociativeWith(nodeA, nodeB, parenthesis) { var a = nodeA; var b = nodeB; if (parenthesis !== 'keep') { //ParenthesisNodes are only ignored when not in 'keep' mode var a = nodeA.getContent(); var b = nodeB.getContent(); } var identifierA = a.getIdentifier(); var identifierB = b.getIdentifier(); var index = getPrecedence(a, parenthesis); if (index === null) { //node isn't in the list return null; } var property = properties[index][identifierA]; if (property.hasOwnProperty('associativeWith') && (property.associativeWith instanceof Array)) { for (var i = 0; i < property.associativeWith.length; i++) { if (property.associativeWith[i] === identifierB) { return true; } } return false; } //associativeWith is not defined return null; }
...
//otherwise, no parens needed
return [false];
} else if (args.length === 2) { //binary operators
var lhsParens; //left hand side needs parenthesis?
//precedence of the left hand side
var lhsPrecedence = operators.getPrecedence(args[0], parenthesis);
//is the root node associative with the left hand side
var assocWithLhs = operators.isAssociativeWith(root, args[0], parenthesis);
if (lhsPrecedence === null) {
//if the left hand side has no defined precedence, no parens are needed
//FunctionNode for example
lhsParens = false;
}
else if ((lhsPrecedence === precedence) && (associativity === 'right') && !assocWithLhs) {
...
function factory(type, config, load, typed) {
var latex = require('../../utils/latex');
var matrix = load(require('../../type/matrix/function/matrix'));
var algorithm03 = load(require('../../type/matrix/utils/algorithm03'));
var algorithm05 = load(require('../../type/matrix/utils/algorithm05'));
var algorithm12 = load(require('../../type/matrix/utils/algorithm12'));
var algorithm13 = load(require('../../type/matrix/utils/algorithm13'));
var algorithm14 = load(require('../../type/matrix/utils/algorithm14'));
/**
* Logical `or`. Test if at least one value is defined with a nonzero/nonempty value.
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.or(x, y)
*
* Examples:
*
* math.or(2, 4); // returns true
*
* a = [2, 5, 0];
* b = [0, 22, 0];
* c = 0;
*
* math.or(a, b); // returns [true, true, false]
* math.or(b, c); // returns [false, true, false]
*
* See also:
*
* and, not, xor
*
* @param {number | BigNumber | Complex | Unit | Array | Matrix} x First value to check
* @param {number | BigNumber | Complex | Unit | Array | Matrix} y Second value to check
* @return {boolean | Array | Matrix}
* Returns true when one of the inputs is defined with a nonzero/nonempty value.
*/
var or = typed('or', {
'number, number': function (x, y) {
return !!(x || y);
},
'Complex, Complex': function (x, y) {
return (x.re !== 0 || x.im !== 0) || (y.re !== 0 || y.im !== 0);
},
'BigNumber, BigNumber': function (x, y) {
return (!x.isZero() && !x.isNaN()) || (!y.isZero() && !y.isNaN());
},
'Unit, Unit': function (x, y) {
return or(x.value, y.value);
},
'Matrix, Matrix': function (x, y) {
// result
var c;
// process matrix storage
switch (x.storage()) {
case 'sparse':
switch (y.storage()) {
case 'sparse':
// sparse + sparse
c = algorithm05(x, y, or);
break;
default:
// sparse + dense
c = algorithm03(y, x, or, true);
break;
}
break;
default:
switch (y.storage()) {
case 'sparse':
// dense + sparse
c = algorithm03(x, y, or, false);
break;
default:
// dense + dense
c = algorithm13(x, y, or);
break;
}
break;
}
return c;
},
'Array, Array': function (x, y) {
// use matrix implementation
return or(matrix(x), matrix(y)).valueOf();
},
'Array, Matrix': function (x, y) {
// use matrix implementation
return or(matrix(x), y);
},
'Matrix, Array': function (x, y) {
// use matrix implementation
return or(x, matrix(y));
},
'Matrix, any': function (x, y) {
// result
var c;
// check storage format
switch (x.storage()) {
case 'sparse':
c = algorithm12(x, y, or, false);
break;
default:
c = algorithm14(x, y, or, false);
break;
}
return c;
},
'any, Matrix': function (x, y) {
// result
var c;
// check storage format
switch (y.storage()) {
case 'sparse':
c = algorithm12(y, x, or, true);
break;
default:
c = algorithm14(y, x, or, true);
break;
}
return c;
},
'Array, any': function (x, y) {
// use matrix implementation
return algorithm14(matrix(x), y, or, false).valueOf();
},
'any, Array': function (x, y) {
// use matrix implementation
return algorithm14(matrix(y), x, or, true).valueOf();
}
});
or.toTex = {
2: '\\left(${args[0]}' + latex.operators['or'] + '${args[1]}\\right)'
};
return or;
}
n/a
function factory(type, config, load, typed) {
var AccessorNode = load(require('./node/AccessorNode'));
var ArrayNode = load(require('./node/ArrayNode'));
var AssignmentNode = load(require('./node/AssignmentNode'));
var BlockNode = load(require('./node/BlockNode'));
var ConditionalNode = load(require('./node/ConditionalNode'));
var ConstantNode = load(require('./node/ConstantNode'));
var FunctionAssignmentNode = load(require('./node/FunctionAssignmentNode'));
var IndexNode = load(require('./node/IndexNode'));
var ObjectNode = load(require('./node/ObjectNode'));
var OperatorNode = load(require('./node/OperatorNode'));
var ParenthesisNode = load(require('./node/ParenthesisNode'));
var FunctionNode = load(require('./node/FunctionNode'));
var RangeNode = load(require('./node/RangeNode'));
var SymbolNode = load(require('./node/SymbolNode'));
/**
* Parse an expression. Returns a node tree, which can be evaluated by
* invoking node.eval();
*
* Syntax:
*
* parse(expr)
* parse(expr, options)
* parse([expr1, expr2, expr3, ...])
* parse([expr1, expr2, expr3, ...], options)
*
* Example:
*
* var node = parse('sqrt(3^2 + 4^2)');
* node.compile(math).eval(); // 5
*
* var scope = {a:3, b:4}
* var node = parse('a * b'); // 12
* var code = node.compile(math);
* code.eval(scope); // 12
* scope.a = 5;
* code.eval(scope); // 20
*
* var nodes = math.parse(['a = 3', 'b = 4', 'a * b']);
* nodes[2].compile(math).eval(); // 12
*
* @param {string | string[] | Matrix} expr
* @param {{nodes: Object<string, Node>}} [options] Available options:
* - `nodes` a set of custom nodes
* @return {Node | Node[]} node
* @throws {Error}
*/
function parse (expr, options) {
if (arguments.length != 1 && arguments.length != 2) {
throw new ArgumentsError('parse', arguments.length, 1, 2);
}
// pass extra nodes
extra_nodes = (options && options.nodes) ? options.nodes : {};
if (typeof expr === 'string') {
// parse a single expression
expression = expr;
return parseStart();
}
else if (Array.isArray(expr) || expr instanceof type.Matrix) {
// parse an array or matrix with expressions
return deepMap(expr, function (elem) {
if (typeof elem !== 'string') throw new TypeError('String expected');
expression = elem;
return parseStart();
});
}
else {
// oops
throw new TypeError('String or matrix expected');
}
}
// token types enumeration
var TOKENTYPE = {
NULL : 0,
DELIMITER : 1,
NUMBER : 2,
SYMBOL : 3,
UNKNOWN : 4
};
// map with all delimiters
var DELIMITERS = {
',': true,
'(': true,
')': true,
'[': true,
']': true,
'{': true,
'}': true,
'\"': true,
';': true,
'+': true,
'-': true,
'*': true,
'.*': true,
'/': true,
'./': true,
'%': true,
'^': true,
'.^': true,
'~': true,
'!': true,
'&': true,
'|': true,
'^|': true,
'\'': true,
'=': true,
':': true,
'?': true,
'==': true,
'!=': true,
'<': true,
'>': true,
'<=': true,
'>=': true,
'<<': true,
'>>': true,
'>>>': true
};
// map with all named delimiters
var NAMED_DELIMITERS = {
'mod': true,
'to': true,
'in': true,
'and': true,
'xor': true,
'or': true,
'not': true
};
var extra_nodes = {}; // current extra nodes
var expression = ''; // current expression
var comment = ''; // last parsed comment
var index = 0; // current index in expr
var c = ''; // current token character in expr
var token = ''; // current token
v ...
n/a
function factory(type, config, load, typed) {
var asc = load(require('../relational/compare'));
function desc(a, b) {
return -asc(a, b);
}
/**
* Partition-based selection of an array or 1D matrix.
* Will find the kth smallest value, and mutates the input array.
* Uses Quickselect.
*
* Syntax:
*
* math.partitionSelect(x, k)
* math.partitionSelect(x, k, compare)
*
* Examples:
*
* math.partitionSelect([5, 10, 1], 2); // returns 10
* math.partitionSelect(['C', 'B', 'A', 'D'], 1); // returns 'B'
*
* function sortByLength (a, b) {
* return a.length - b.length;
* }
* math.partitionSelect(['Langdon', 'Tom', 'Sara'], 2, sortByLength); // returns 'Langdon'
*
* See also:
*
* sort
*
* @param {Matrix | Array} x A one dimensional matrix or array to sort
* @param {Number} k The kth smallest value to be retrieved; zero-based index
* @param {Function | 'asc' | 'desc'} [compare='asc']
* An optional comparator function. The function is called as
* `compare(a, b)`, and must return 1 when a > b, -1 when a < b,
* and 0 when a == b.
* @return {*} Returns the kth lowest value.
*/
return typed('partitionSelect', {
'Array | Matrix, number': function (x, k) {
return _partitionSelect(x, k, asc);
},
'Array | Matrix, number, string': function (x, k, compare) {
if (compare === 'asc') {
return _partitionSelect(x, k, asc);
}
else if (compare === 'desc') {
return _partitionSelect(x, k, desc);
}
else {
throw new Error('Compare string must be "asc" or "desc"');
}
},
'Array | Matrix, number, function': _partitionSelect
});
function _partitionSelect(x, k, compare) {
if (!isInteger(k) || k < 0) {
throw new Error('k must be a non-negative integer');
}
if (x && x.isMatrix) {
var size = x.size();
if (size.length > 1) {
throw new Error('Only one dimensional matrices supported');
}
return quickSelect(x.valueOf(), k, compare);
}
if (Array.isArray(x)) {
return quickSelect(x, k, compare);
}
}
/**
* Quickselect algorithm.
* Code adapted from:
* http://blog.teamleadnet.com/2012/07/quick-select-algorithm-find-kth-element.html
*
* @param {Array} arr
* @param {Number} k
* @param {Function} compare
* @private
*/
function quickSelect(arr, k, compare) {
if (k >= arr.length) {
throw new Error('k out of bounds');
}
var from = 0;
var to = arr.length - 1;
// if from == to we reached the kth element
while (from < to) {
var r = from;
var w = to;
var pivot = arr[Math.floor(Math.random() * (to - from + 1)) + from];
// stop if the reader and writer meets
while (r < w) {
// arr[r] >= pivot
if (compare(arr[r], pivot) >= 0) { // put the large values at the end
var tmp = arr[w];
arr[w] = arr[r];
arr[r] = tmp;
--w;
} else { // the value is smaller than the pivot, skip
++r;
}
}
// if we stepped up (r++) we need to step one down (arr[r] > pivot)
if (compare(arr[r], pivot) > 0) {
--r;
}
// the r pointer is on the end of the first k elements
if (k <= r) {
to = r;
} else {
from = r + 1;
}
}
return arr[k];
}
}
n/a
function factory(type, config, load, typed) {
var factorial = load(require('./factorial'));
/**
* Compute the number of ways of obtaining an ordered subset of `k` elements
* from a set of `n` elements.
*
* Permutations only takes integer arguments.
* The following condition must be enforced: k <= n.
*
* Syntax:
*
* math.permutations(n)
* math.permutations(n, k)
*
* Examples:
*
* math.permutations(5); // 120
* math.permutations(5, 3); // 60
*
* See also:
*
* combinations, factorial
*
* @param {number | BigNumber} n The number of objects in total
* @param {number | BigNumber} [k] The number of objects in the subset
* @return {number | BigNumber} The number of permutations
*/
var permutations = typed('permutations', {
'number | BigNumber': factorial,
'number, number': function (n, k) {
var result, i;
if (!isInteger(n) || n < 0) {
throw new TypeError('Positive integer value expected in function permutations');
}
if (!isInteger(k) || k < 0) {
throw new TypeError('Positive integer value expected in function permutations');
}
if (k > n) {
throw new TypeError('second argument k must be less than or equal to first argument n');
}
// Permute n objects, k at a time
result = 1;
for (i = n - k + 1; i <= n; i++) {
result = result * i;
}
return result;
},
'BigNumber, BigNumber': function (n, k) {
var result, i;
if (!isPositiveInteger(n) || !isPositiveInteger(k)) {
throw new TypeError('Positive integer value expected in function permutations');
}
if (k.gt(n)) {
throw new TypeError('second argument k must be less than or equal to first argument n');
}
result = new type.BigNumber(1);
for (i = n.minus(k).plus(1); i.lte(n); i = i.plus(1)) {
result = result.times(i);
}
return result;
}
// TODO: implement support for collection in permutations
});
permutations.toTex = undefined; // use default template
return permutations;
}
n/a
function factory(type, config, load, typed, math) { // helper function to create a unit with a fixed prefix function fixedUnit(str) { var unit = type.Unit.parse(str); unit.fixPrefix = true; return unit; } // Source: http://www.wikiwand.com/en/Physical_constant // Universal constants lazy(math, 'speedOfLight', function () {return fixedUnit('299792458 m s^-1')}); lazy(math, 'gravitationConstant', function () {return fixedUnit('6.6738480e-11 m^3 kg^-1 s^-2')}); lazy(math, 'planckConstant', function () {return fixedUnit('6.626069311e-34 J s')}); lazy(math, 'reducedPlanckConstant',function () {return fixedUnit('1.05457172647e-34 J s')}); // Electromagnetic constants lazy(math, 'magneticConstant', function () {return fixedUnit('1.2566370614e-6 N A^-2')}); lazy(math, 'electricConstant', function () {return fixedUnit('8.854187817e-12 F m^-1')}); lazy(math, 'vacuumImpedance', function () {return fixedUnit('376.730313461 ohm')}); lazy(math, 'coulomb', function () {return fixedUnit('8.9875517873681764e9 N m^2 C^-2')}); lazy(math, 'elementaryCharge', function () {return fixedUnit('1.60217656535e-19 C')}); lazy(math, 'bohrMagneton', function () {return fixedUnit('9.2740096820e-24 J T^-1')}); lazy(math, 'conductanceQuantum', function () {return fixedUnit('7.748091734625e-5 S')}); lazy(math, 'inverseConductanceQuantum', function () {return fixedUnit('12906.403721742 ohm')}); lazy(math, 'magneticFluxQuantum', function () {return fixedUnit('2.06783375846e-15 Wb')}); lazy(math, 'nuclearMagneton', function () {return fixedUnit('5.0507835311e-27 J T^-1')}); lazy(math, 'klitzing', function () {return fixedUnit('25812.807443484 ohm')}); //lazy(math, 'josephson', function () {return fixedUnit('4.8359787011e-14 Hz V^-1')}); // TODO: support for Hz needed // Atomic and nuclear constants lazy(math, 'bohrRadius', function () {return fixedUnit('5.291772109217e-11 m')}); lazy(math, 'classicalElectronRadius', function () {return fixedUnit('2.817940326727e-15 m')}); lazy(math, 'electronMass', function () {return fixedUnit('9.1093829140e-31 kg')}); lazy(math, 'fermiCoupling', function () {return fixedUnit('1.1663645e-5 GeV^-2')}); lazy(math, 'fineStructure', function () {return 7.297352569824e-3}); lazy(math, 'hartreeEnergy', function () {return fixedUnit('4.3597443419e-18 J')}); lazy(math, 'protonMass', function () {return fixedUnit('1.67262177774e-27 kg')}); lazy(math, 'deuteronMass', function () {return fixedUnit('3.3435830926e-27 kg')}); lazy(math, 'neutronMass', function () {return fixedUnit('1.6749271613e-27 kg')}); lazy(math, 'quantumOfCirculation', function () {return fixedUnit('3.636947552024e-4 m^2 s^-1')}); lazy(math, 'rydberg', function () {return fixedUnit('10973731.56853955 m^-1')}); lazy(math, 'thomsonCrossSection', function () {return fixedUnit('6.65245873413e-29 m^2')}); lazy(math, 'weakMixingAngle', function () {return 0.222321}); lazy(math, 'efimovFactor', function () {return 22.7}); // Physico-chemical constants lazy(math, 'atomicMass', function () {return fixedUnit('1.66053892173e-27 kg')}); lazy(math, 'avogadro', function () {return fixedUnit('6.0221412927e23 mol^-1')}); lazy(math, 'boltzmann', function () {return fixedUnit('1.380648813e-23 J K^-1')}); lazy(math, 'faraday', function () {return fixedUnit('96485.336521 C mol^-1')}); lazy(math, 'firstRadiation', function () {return fixedUnit('3.7417715317e-16 W m^2')}); // lazy(math, 'spectralRadiance', function () {return fixedUnit('1.19104286953e-16 W m^2 sr^-1')}); // TODO spectralRadiance lazy(math, 'loschmidt', function () {return fixedUnit('2.686780524e25 m^-3')}); lazy(math, 'gasConstant', function () {return fixedUnit('8.314462175 J K ...
n/a
function factory(type, config, load, typed) {
var distribution = load(require('./distribution'));
/**
* Random pick one or more values from a one dimensional array.
* Array elements are picked using a random function with uniform or weighted distribution.
*
* Syntax:
*
* math.pickRandom(array)
* math.pickRandom(array, number)
* math.pickRandom(array, weights)
* math.pickRandom(array, number, weights)
* math.pickRandom(array, weights, number)
*
* Examples:
*
* math.pickRandom([3, 6, 12, 2]); // returns one of the values in the array
* math.pickRandom([3, 6, 12, 2], 2); // returns an array of two of the values in the array
* math.pickRandom([3, 6, 12, 2], [1, 3, 2, 1]); // returns one of the values in the array with weighted distribution
* math.pickRandom([3, 6, 12, 2], 2, [1, 3, 2, 1]); // returns an array of two of the values in the array with weighted distribution
* math.pickRandom([3, 6, 12, 2], [1, 3, 2, 1], 2); // returns an array of two of the values in the array with weighted distribution
*
* See also:
*
* random, randomInt
*
* @param {Array} array A one dimensional array
* @param {Int} number An int or float
* @param {Array} weights An array of ints or floats
* @return {number} One of the elements of the provided input array
* @return {array} An array of elements of the provided input array
*/
// TODO: rework pickRandom to a typed-function
var pickRandom = distribution('uniform').pickRandom;
pickRandom.toTex = undefined; // use default template
return pickRandom;
}
n/a
function factory(type, config, load, typed) {
var latex = require('../../utils/latex');
var eye = load(require('../matrix/eye'));
var multiply = load(require('./multiply'));
var matrix = load(require('../../type/matrix/function/matrix'));
var fraction = load(require('../../type/fraction/function/fraction'));
var number = load(require('../../type/number'));
/**
* Calculates the power of x to y, `x ^ y`.
* Matrix exponentiation is supported for square matrices `x`, and positive
* integer exponents `y`.
*
* For cubic roots of negative numbers, the function returns the principal
* root by default. In order to let the function return the real root,
* math.js can be configured with `math.config({predictable: true})`.
* To retrieve all cubic roots of a value, use `math.cbrt(x, true)`.
*
* Syntax:
*
* math.pow(x, y)
*
* Examples:
*
* math.pow(2, 3); // returns number 8
*
* var a = math.complex(2, 3);
* math.pow(a, 2) // returns Complex -5 + 12i
*
* var b = [[1, 2], [4, 3]];
* math.pow(b, 2); // returns Array [[9, 8], [16, 17]]
*
* See also:
*
* multiply, sqrt, cbrt, nthRoot
*
* @param {number | BigNumber | Complex | Array | Matrix} x The base
* @param {number | BigNumber | Complex} y The exponent
* @return {number | BigNumber | Complex | Array | Matrix} The value of `x` to the power `y`
*/
var pow = typed('pow', {
'number, number': _pow,
'Complex, Complex': function (x, y) {
return x.pow(y);
},
'BigNumber, BigNumber': function (x, y) {
if (y.isInteger() || x >= 0 || config.predictable) {
return x.pow(y);
}
else {
return new type.Complex(x.toNumber(), 0).pow(y.toNumber(), 0);
}
},
'Fraction, Fraction': function (x, y) {
if (y.d !== 1) {
if (config.predictable) {
throw new Error('Function pow does not support non-integer exponents for fractions.');
}
else {
return _pow(x.valueOf(), y.valueOf());
}
}
else {
return x.pow(y);
}
},
'Array, number': _powArray,
'Array, BigNumber': function (x, y) {
return _powArray(x, y.toNumber());
},
'Matrix, number': _powMatrix,
'Matrix, BigNumber': function (x, y) {
return _powMatrix(x, y.toNumber());
},
'Unit, number': function (x, y) {
return x.pow(y);
}
});
/**
* Calculates the power of x to y, x^y, for two numbers.
* @param {number} x
* @param {number} y
* @return {number | Complex} res
* @private
*/
function _pow(x, y) {
// Alternatively could define a 'realmode' config option or something, but
// 'predictable' will work for now
if (config.predictable && !isInteger(y) && x < 0) {
// Check to see if y can be represented as a fraction
try {
var yFrac = fraction(y);
var yNum = number(yFrac);
if(y === yNum || Math.abs((y - yNum) / y) < 1e-14) {
if(yFrac.d % 2 === 1) {
return (yFrac.n % 2 === 0 ? 1 : -1) * Math.pow(-x, y);
}
}
}
catch (ex) {
// fraction() throws an error if y is Infinity, etc.
}
// Unable to express y as a fraction, so continue on
}
if (isInteger(y) || x >= 0 || config.predictable) {
return Math.pow(x, y);
}
else {
return new type.Complex(x, 0).pow(y, 0);
}
}
/**
* Calculate the power of a 2d array
* @param {Array} x must be a 2 dimensional, square matrix
* @param {number} y a positive, integer value
* @returns {Array}
* @private
*/
function _powArray(x, y) {
if (!isInteger(y) || y < 0) {
throw new TypeError('For A^b, b must be a positive integer (value is ' + y + ')');
}
// verify that A is a 2 dimensional square matrix
var s = size(x);
if (s.length != 2) {
throw new Error('For A^b, A must be 2 dimensional (A has ' + s.length + ' dimension ...
n/a
function factory(type, config, load, typed) {
/**
* Interpolate values into a string template.
*
* Syntax:
*
* math.print(template, values)
* math.print(template, values, precision)
* math.print(template, values, options)
*
* Example usage:
*
* // the following outputs: 'Lucy is 5 years old'
* math.print('Lucy is $age years old', {age: 5});
*
* // the following outputs: 'The value of pi is 3.141592654'
* math.print('The value of pi is $pi', {pi: math.pi}, 10);
*
* // the following outputs: 'hello Mary! The date is 2013-03-23'
* math.print('Hello $user.name! The date is $date', {
* user: {
* name: 'Mary',
* },
* date: new Date(2013, 2, 23).toISOString().substring(0, 10)
* });
*
* See also:
*
* format
*
* @param {string} template A string containing variable placeholders.
* @param {Object} values An object containing variables which will
* be filled in in the template.
* @param {number | Object} [options] Formatting options,
* or the number of digits to format numbers.
* See function math.format for a description
* of all options.
* @return {string} Interpolated string
*/
var print = typed ('print', {
'string, Object': _print,
'string, Object, number | Object': _print
});
print.toTex = undefined; // use default template
return print;
}
n/a
function factory(type, config, load, typed) {
var multiply = load(require('../arithmetic/multiplyScalar'));
/**
* Compute the product of a matrix or a list with values.
* In case of a (multi dimensional) array or matrix, the sum of all
* elements will be calculated.
*
* Syntax:
*
* math.prod(a, b, c, ...)
* math.prod(A)
*
* Examples:
*
* math.multiply(2, 3); // returns 6
* math.prod(2, 3); // returns 6
* math.prod(2, 3, 4); // returns 24
* math.prod([2, 3, 4]); // returns 24
* math.prod([[2, 5], [4, 3]]); // returns 120
*
* See also:
*
* mean, median, min, max, sum, std, var
*
* @param {... *} args A single matrix or or multiple scalar values
* @return {*} The product of all values
*/
var prod = typed('prod', {
// prod([a, b, c, d, ...])
'Array | Matrix': _prod,
// prod([a, b, c, d, ...], dim)
'Array | Matrix, number | BigNumber': function (array, dim) {
// TODO: implement prod(A, dim)
throw new Error('prod(A, dim) is not yet supported');
//return reduce(arguments[0], arguments[1], math.prod);
},
// prod(a, b, c, d, ...)
'...': function (args) {
return _prod(args);
}
});
prod.toTex = undefined; // use default template
return prod;
/**
* Recursively calculate the product of an n-dimensional array
* @param {Array} array
* @return {number} prod
* @private
*/
function _prod(array) {
var prod = undefined;
deepForEach(array, function (value) {
prod = (prod === undefined) ? value : multiply(prod, value);
});
if (prod === undefined) {
throw new Error('Cannot calculate prod of an empty array');
}
return prod;
}
}
n/a
function factory(type, config, load, typed) {
var add = load(require('../arithmetic/add'));
var multiply = load(require('../arithmetic/multiply'));
var partitionSelect = load(require('../matrix/partitionSelect'));
var compare = load(require('../relational/compare'));
/**
* Compute the prob order quantile of a matrix or a list with values.
* The sequence is sorted and the middle value is returned.
* Supported types of sequence values are: Number, BigNumber, Unit
* Supported types of probability are: Number, BigNumber
*
* In case of a (multi dimensional) array or matrix, the prob order quantile
* of all elements will be calculated.
*
* Syntax:
*
* math.quantileSeq(A, prob[, sorted])
* math.quantileSeq(A, [prob1, prob2, ...][, sorted])
* math.quantileSeq(A, N[, sorted])
*
* Examples:
*
* math.quantileSeq([3, -1, 5, 7], 0.5); // returns 4
* math.quantileSeq([3, -1, 5, 7], [1/3, 2/3]); // returns [3, 5]
* math.quantileSeq([3, -1, 5, 7], 2); // returns [3, 5]
* math.quantileSeq([-1, 3, 5, 7], 0.5, true); // returns 4
*
* See also:
*
* median, mean, min, max, sum, prod, std, var
*
* @param {Array, Matrix} data A single matrix or Array
* @param {Number, BigNumber, Array} probOrN prob is the order of the quantile, while N is
* the amount of evenly distributed steps of
* probabilities; only one of these options can
* be provided
* @param {Boolean} sorted=false is data sorted in ascending order
* @return {Number, BigNumber, Unit, Array} Quantile(s)
*/
function quantileSeq(data, probOrN, sorted) {
var probArr, dataArr, one;
if (arguments.length < 2 || arguments.length > 3) {
throw new SyntaxError('Function quantileSeq requires two or three parameters');
}
if (isCollection(data)) {
sorted = sorted || false;
if (typeof sorted === 'boolean') {
dataArr = data.valueOf();
if (isNumber(probOrN)) {
if (probOrN < 0) {
throw new Error('N/prob must be non-negative');
}
if (probOrN <= 1) {
// quantileSeq([a, b, c, d, ...], prob[,sorted])
return _quantileSeq(dataArr, probOrN, sorted);
}
if (probOrN > 1) {
// quantileSeq([a, b, c, d, ...], N[,sorted])
if (!isInteger(probOrN)) {
throw new Error('N must be a positive integer');
}
var nPlusOne = probOrN + 1;
probArr = new Array(probOrN);
for (var i = 0; i < probOrN;) {
probArr[i] = _quantileSeq(dataArr, (++i) / nPlusOne, sorted);
}
return probArr;
}
}
if (probOrN && probOrN.isBigNumber) {
if (probOrN.isNegative()) {
throw new Error('N/prob must be non-negative');
}
one = new probOrN.constructor(1);
if (probOrN.lte(one)) {
// quantileSeq([a, b, c, d, ...], prob[,sorted])
return _quantileSeq(dataArr, probOrN, sorted);
}
if (probOrN.gt(one)) {
// quantileSeq([a, b, c, d, ...], N[,sorted])
if (!probOrN.isInteger()) {
throw new Error('N must be a positive integer');
}
// largest possible Array length is 2^32-1;
// 2^32 < 10^15, thus safe conversion guaranteed
var intN = probOrN.toNumber();
if (intN > 4294967295) {
throw new Error('N must be less than or equal to 2^32-1, as that is the maximum length of an Array');
}
var nPlusOne = new type.BigNumber(intN + 1);
probArr = new Array(intN);
for (var i = 0; i < intN;) {
probArr[i] = _quantileSeq(dataArr, new type.BigNumber(++i).div(nPlusOne), sorted);
}
return ...
n/a
function factory(type, config, load, typed) {
var distribution = load(require('./distribution'));
/**
* Return a random number larger or equal to `min` and smaller than `max`
* using a uniform distribution.
*
* Syntax:
*
* math.random() // generate a random number between 0 and 1
* math.random(max) // generate a random number between 0 and max
* math.random(min, max) // generate a random number between min and max
* math.random(size) // generate a matrix with random numbers between 0 and 1
* math.random(size, max) // generate a matrix with random numbers between 0 and max
* math.random(size, min, max) // generate a matrix with random numbers between min and max
*
* Examples:
*
* math.random(); // returns a random number between 0 and 1
* math.random(100); // returns a random number between 0 and 100
* math.random(30, 40); // returns a random number between 30 and 40
* math.random([2, 3]); // returns a 2x3 matrix with random numbers between 0 and 1
*
* See also:
*
* randomInt, pickRandom
*
* @param {Array | Matrix} [size] If provided, an array or matrix with given
* size and filled with random values is returned
* @param {number} [min] Minimum boundary for the random value, included
* @param {number} [max] Maximum boundary for the random value, excluded
* @return {number | Array | Matrix} A random number
*/
// TODO: rework random to a typed-function
var random = distribution('uniform').random;
random.toTex = undefined; // use default template
return random;
}
n/a
function factory(type, config, load, typed) {
var distribution = load(require('./distribution'));
/**
* Return a random integer number larger or equal to `min` and smaller than `max`
* using a uniform distribution.
*
* Syntax:
*
* math.randomInt(max) // generate a random integer between 0 and max
* math.randomInt(min, max) // generate a random integer between min and max
* math.randomInt(size) // generate a matrix with random integer between 0 and 1
* math.randomInt(size, max) // generate a matrix with random integer between 0 and max
* math.randomInt(size, min, max) // generate a matrix with random integer between min and max
*
* Examples:
*
* math.randomInt(100); // returns a random integer between 0 and 100
* math.randomInt(30, 40); // returns a random integer between 30 and 40
* math.randomInt([2, 3]); // returns a 2x3 matrix with random integers between 0 and 1
*
* See also:
*
* random, pickRandom
*
* @param {Array | Matrix} [size] If provided, an array or matrix with given
* size and filled with random values is returned
* @param {number} [min] Minimum boundary for the random value, included
* @param {number} [max] Maximum boundary for the random value, excluded
* @return {number | Array | Matrix} A random integer value
*/
// TODO: rework randomInt to a typed-function
var randomInt = distribution('uniform').randomInt;
randomInt.toTex = undefined; // use default template
return randomInt;
}
n/a
function factory(type, config, load, typed) {
var matrix = load(require('../../type/matrix/function/matrix'));
var ZERO = new type.BigNumber(0);
var ONE = new type.BigNumber(1);
/**
* Create an array from a range.
* By default, the range end is excluded. This can be customized by providing
* an extra parameter `includeEnd`.
*
* Syntax:
*
* math.range(str [, includeEnd]) // Create a range from a string,
* // where the string contains the
* // start, optional step, and end,
* // separated by a colon.
* math.range(start, end [, includeEnd]) // Create a range with start and
* // end and a step size of 1.
* math.range(start, end, step [, includeEnd]) // Create a range with start, step,
* // and end.
*
* Where:
*
* - `str: string`
* A string 'start:end' or 'start:step:end'
* - `start: {number | BigNumber}`
* Start of the range
* - `end: number | BigNumber`
* End of the range, excluded by default, included when parameter includeEnd=true
* - `step: number | BigNumber`
* Step size. Default value is 1.
* - `includeEnd: boolean`
* Option to specify whether to include the end or not. False by default.
*
* Examples:
*
* math.range(2, 6); // [2, 3, 4, 5]
* math.range(2, -3, -1); // [2, 1, 0, -1, -2]
* math.range('2:1:6'); // [2, 3, 4, 5]
* math.range(2, 6, true); // [2, 3, 4, 5, 6]
*
* See also:
*
* ones, zeros, size, subset
*
* @param {*} args Parameters describing the ranges `start`, `end`, and optional `step`.
* @return {Array | Matrix} range
*/
var range = typed('range', {
// TODO: simplify signatures when typed-function supports default values and optional arguments
// TODO: a number or boolean should not be converted to string here
'string': _strRange,
'string, boolean': _strRange,
'number, number': function (start, end) {
return _out(_rangeEx(start, end, 1));
},
'number, number, number': function (start, end, step) {
return _out(_rangeEx(start, end, step));
},
'number, number, boolean': function (start, end, includeEnd) {
return includeEnd
? _out(_rangeInc(start, end, 1))
: _out(_rangeEx(start, end, 1));
},
'number, number, number, boolean': function (start, end, step, includeEnd) {
return includeEnd
? _out(_rangeInc(start, end, step))
: _out(_rangeEx(start, end, step));
},
'BigNumber, BigNumber': function (start, end) {
return _out(_bigRangeEx(start, end, ONE));
},
'BigNumber, BigNumber, BigNumber': function (start, end, step) {
return _out(_bigRangeEx(start, end, step));
},
'BigNumber, BigNumber, boolean': function (start, end, includeEnd) {
return includeEnd
? _out(_bigRangeInc(start, end, ONE))
: _out(_bigRangeEx(start, end, ONE));
},
'BigNumber, BigNumber, BigNumber, boolean': function (start, end, step, includeEnd) {
return includeEnd
? _out(_bigRangeInc(start, end, step))
: _out(_bigRangeEx(start, end, step));
}
});
range.toTex = undefined; // use default template
return range;
function _out(arr) {
return config.matrix === 'Array' ? arr : matrix(arr);
}
function _strRange (str, includeEnd) {
var r = _parse(str);
if (!r){
throw new SyntaxError('String "' + str + '" is no valid range');
}
var fn;
if (config.number === 'BigNumber') {
fn = includeEnd ? _bigRangeInc : _bigRangeEx;
return _out(fn(
new type.BigNumber(r.start),
new type.BigNumber(r.end),
new type.BigNumber(r.step)));
}
else {
fn = includeEnd ? _rangeInc : _rangeEx;
return _out(fn(r.start, r. ...
n/a
function factory(type, config, load, typed) { var range = load(require('../../function/matrix/range')); return typed('range', { '...any': function (args) { var lastIndex = args.length - 1; var last = args[lastIndex]; if (typeof last !== 'boolean') { // append a parameter includeEnd=true args.push(true); } return range.apply(null, args); } }); }
n/a
function factory(type, config, load, typed) {
/**
* Get the real part of a complex number.
* For a complex number `a + bi`, the function returns `a`.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.re(x)
*
* Examples:
*
* var a = math.complex(2, 3);
* math.re(a); // returns number 2
* math.im(a); // returns number 3
*
* math.re(math.complex('-5.2i')); // returns number 0
* math.re(math.complex(2.4)); // returns number 2.4
*
* See also:
*
* im, conj, abs, arg
*
* @param {number | BigNumber | Complex | Array | Matrix} x
* A complex number or array with complex numbers
* @return {number | BigNumber | Array | Matrix} The real part of x
*/
var re = typed('re', {
'number': function (x) {
return x;
},
'BigNumber': function (x) {
return x;
},
'Complex': function (x) {
return x.re;
},
'Array | Matrix': function (x) {
return deepMap(x, re);
}
});
re.toTex = {1: '\\Re\\left\\lbrace${args[0]}\\right\\rbrace'};
return re;
}
n/a
function factory(type, config, load, typed) {
var matrix = load(require('../../type/matrix/function/matrix'));
/**
* Reshape a multi dimensional array to fit the specified dimensions
*
* Syntax:
*
* math.reshape(x, sizes)
*
* Examples:
*
* math.reshape([1, 2, 3, 4, 5, 6], [2, 3]);
* // returns Array [[1, 2, 3], [4, 5, 6]]
*
* math.reshape([[1, 2], [3, 4]], [1, 4]);
* // returns Array [[1, 2, 3, 4]]
*
* math.reshape([[1, 2], [3, 4]], [4]);
* // returns Array [1, 2, 3, 4]
*
* var x = math.matrix([1, 2, 3, 4, 5, 6, 7, 8]);
* math.reshape(x, [2, 2, 2]);
* // returns Matrix [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]
*
* See also:
*
* size, squeeze, resize
*
* @param {Array | Matrix | *} x Matrix to be reshaped
* @param {number[]} sizes One dimensional array with integral sizes for
* each dimension
*
* @return {* | Array | Matrix} A reshaped clone of matrix `x`
*
* @throws {TypeError} If `sizes` does not contain solely integers
* @throws {DimensionError} If the product of the new dimension sizes does
* not equal that of the old ones
*/
var reshape = typed('reshape', {
'Matrix, Array': function (x, sizes) {
if(x.reshape) {
return x.reshape(sizes);
} else {
return matrix(array.reshape(x.valueOf(), sizes));
}
},
'Array, Array': function (x, sizes) {
sizes.forEach(function (size) {
if (!isInteger(size)) {
throw new TypeError('Invalid size for dimension: ' + size);
}
});
return array.reshape(x, sizes);
}
});
reshape.toTex = undefined; // use default template
return reshape;
}
n/a
function factory(type, config, load, typed) {
var matrix = load(require('../../type/matrix/function/matrix'));
/**
* Resize a matrix
*
* Syntax:
*
* math.resize(x, size)
* math.resize(x, size, defaultValue)
*
* Examples:
*
* math.resize([1, 2, 3, 4, 5], [3]); // returns Array [1, 2, 3]
* math.resize([1, 2, 3], [5], 0); // returns Array [1, 2, 3, 0, 0]
* math.resize(2, [2, 3], 0); // returns Matrix [[2, 0, 0], [0, 0, 0]]
* math.resize("hello", [8], "!"); // returns string 'hello!!!'
*
* See also:
*
* size, squeeze, subset, reshape
*
* @param {Array | Matrix | *} x Matrix to be resized
* @param {Array | Matrix} size One dimensional array with numbers
* @param {number | string} [defaultValue=0] Zero by default, except in
* case of a string, in that case
* defaultValue = ' '
* @return {* | Array | Matrix} A resized clone of matrix `x`
*/
// TODO: rework resize to a typed-function
var resize = function resize (x, size, defaultValue) {
if (arguments.length != 2 && arguments.length != 3) {
throw new ArgumentsError('resize', arguments.length, 2, 3);
}
if (size && size.isMatrix === true) {
size = size.valueOf(); // get Array
}
if (size.length && size[0] && size[0].isBigNumber === true) {
// convert bignumbers to numbers
size = size.map(function (value) {
return (value && value.isBigNumber === true) ? value.toNumber() : value;
});
}
// check x is a Matrix
if (x && x.isMatrix === true) {
// use optimized matrix implementation, return copy
return x.resize(size, defaultValue, true);
}
if (typeof x === 'string') {
// resize string
return _resizeString(x, size, defaultValue);
}
// check result should be a matrix
var asMatrix = Array.isArray(x) ? false : (config.matrix !== 'Array');
if (size.length == 0) {
// output a scalar
while (Array.isArray(x)) {
x = x[0];
}
return clone(x);
}
else {
// output an array/matrix
if (!Array.isArray(x)) {
x = [x];
}
x = clone(x);
var res = array.resize(x, size, defaultValue);
return asMatrix ? matrix(res) : res;
}
};
resize.toTex = undefined; // use default template
return resize;
/**
* Resize a string
* @param {string} str
* @param {number[]} size
* @param {string} [defaultChar=' ']
* @private
*/
function _resizeString(str, size, defaultChar) {
if (defaultChar !== undefined) {
if (typeof defaultChar !== 'string' || defaultChar.length !== 1) {
throw new TypeError('Single character expected as defaultValue');
}
}
else {
defaultChar = ' ';
}
if (size.length !== 1) {
throw new DimensionError(size.length, 1);
}
var len = size[0];
if (typeof len !== 'number' || !isInteger(len)) {
throw new TypeError('Invalid size, must contain positive integers ' +
'(size: ' + format(size) + ')');
}
if (str.length > len) {
return str.substring(0, len);
}
else if (str.length < len) {
var res = str;
for (var i = 0, ii = len - str.length; i < ii; i++) {
res += defaultChar;
}
return res;
}
else {
return str;
}
}
}
n/a
function factory(type, config, load, typed) {
/**
* Instantiate mathjs data types from their JSON representation
* @param {string} key
* @param {*} value
* @returns {*} Returns the revived object
*/
return function reviver(key, value) {
var constructor = type[value && value.mathjs];
if (constructor && typeof constructor.fromJSON === 'function') {
return constructor.fromJSON(value);
}
return value;
}
}
n/a
function factory(type, config, load, typed) {
var latex = require('../../utils/latex');
var matrix = load(require('../../type/matrix/function/matrix'));
var equalScalar = load(require('../relational/equalScalar'));
var zeros = load(require('../matrix/zeros'));
var algorithm01 = load(require('../../type/matrix/utils/algorithm01'));
var algorithm02 = load(require('../../type/matrix/utils/algorithm02'));
var algorithm08 = load(require('../../type/matrix/utils/algorithm08'));
var algorithm10 = load(require('../../type/matrix/utils/algorithm10'));
var algorithm11 = load(require('../../type/matrix/utils/algorithm11'));
var algorithm13 = load(require('../../type/matrix/utils/algorithm13'));
var algorithm14 = load(require('../../type/matrix/utils/algorithm14'));
/**
* Bitwise right arithmetic shift of a value x by y number of bits, `x >> y`.
* For matrices, the function is evaluated element wise.
* For units, the function is evaluated on the best prefix base.
*
* Syntax:
*
* math.rightArithShift(x, y)
*
* Examples:
*
* math.rightArithShift(4, 2); // returns number 1
*
* math.rightArithShift([16, -32, 64], 4); // returns Array [1, -2, 3]
*
* See also:
*
* bitAnd, bitNot, bitOr, bitXor, rightArithShift, rightLogShift
*
* @param {number | BigNumber | Array | Matrix} x Value to be shifted
* @param {number | BigNumber} y Amount of shifts
* @return {number | BigNumber | Array | Matrix} `x` sign-filled shifted right `y` times
*/
var rightArithShift = typed('rightArithShift', {
'number, number': function (x, y) {
if (!isInteger(x) || !isInteger(y)) {
throw new Error('Integers expected in function rightArithShift');
}
return x >> y;
},
'BigNumber, BigNumber': bigRightArithShift,
'Matrix, Matrix': function (x, y) {
// result
var c;
// process matrix storage
switch (x.storage()) {
case 'sparse':
switch (y.storage()) {
case 'sparse':
// sparse & sparse
c = algorithm08(x, y, rightArithShift, false);
break;
default:
// sparse & dense
c = algorithm02(y, x, rightArithShift, true);
break;
}
break;
default:
switch (y.storage()) {
case 'sparse':
// dense & sparse
c = algorithm01(x, y, rightArithShift, false);
break;
default:
// dense & dense
c = algorithm13(x, y, rightArithShift);
break;
}
break;
}
return c;
},
'Array, Array': function (x, y) {
// use matrix implementation
return rightArithShift(matrix(x), matrix(y)).valueOf();
},
'Array, Matrix': function (x, y) {
// use matrix implementation
return rightArithShift(matrix(x), y);
},
'Matrix, Array': function (x, y) {
// use matrix implementation
return rightArithShift(x, matrix(y));
},
'Matrix, number | BigNumber': function (x, y) {
// check scalar
if (!equalScalar(y, 0)) {
// result
var c;
// check storage format
switch (x.storage()) {
case 'sparse':
c = algorithm11(x, y, rightArithShift, false);
break;
default:
c = algorithm14(x, y, rightArithShift, false);
break;
}
return c;
}
return x.clone();
},
'number | BigNumber, Matrix': function (x, y) {
// check scalar
if (!equalScalar(x, 0)) {
// result
var c;
// check storage format
switch (y.storage()) {
case 'sparse':
c = algorithm10(y, x, rightArithShift, true);
break;
default:
c = algorithm14(y, x, rightArithShift, true);
break;
}
return c;
}
return zeros(y.size(), y.storage());
},
'Array, n ...
n/a
function factory(type, config, load, typed) {
var latex = require('../../utils/latex');
var matrix = load(require('../../type/matrix/function/matrix'));
var equalScalar = load(require('../relational/equalScalar'));
var zeros = load(require('../matrix/zeros'));
var algorithm01 = load(require('../../type/matrix/utils/algorithm01'));
var algorithm02 = load(require('../../type/matrix/utils/algorithm02'));
var algorithm08 = load(require('../../type/matrix/utils/algorithm08'));
var algorithm10 = load(require('../../type/matrix/utils/algorithm10'));
var algorithm11 = load(require('../../type/matrix/utils/algorithm11'));
var algorithm13 = load(require('../../type/matrix/utils/algorithm13'));
var algorithm14 = load(require('../../type/matrix/utils/algorithm14'));
/**
* Bitwise right logical shift of value x by y number of bits, `x >>> y`.
* For matrices, the function is evaluated element wise.
* For units, the function is evaluated on the best prefix base.
*
* Syntax:
*
* math.rightLogShift(x, y)
*
* Examples:
*
* math.rightLogShift(4, 2); // returns number 1
*
* math.rightLogShift([16, -32, 64], 4); // returns Array [1, 2, 3]
*
* See also:
*
* bitAnd, bitNot, bitOr, bitXor, leftShift, rightLogShift
*
* @param {number | Array | Matrix} x Value to be shifted
* @param {number} y Amount of shifts
* @return {number | Array | Matrix} `x` zero-filled shifted right `y` times
*/
var rightLogShift = typed('rightLogShift', {
'number, number': function (x, y) {
if (!isInteger(x) || !isInteger(y)) {
throw new Error('Integers expected in function rightLogShift');
}
return x >>> y;
},
// 'BigNumber, BigNumber': ..., // TODO: implement BigNumber support for rightLogShift
'Matrix, Matrix': function (x, y) {
// result
var c;
// process matrix storage
switch (x.storage()) {
case 'sparse':
switch (y.storage()) {
case 'sparse':
// sparse & sparse
c = algorithm08(x, y, rightLogShift, false);
break;
default:
// sparse & dense
c = algorithm02(y, x, rightLogShift, true);
break;
}
break;
default:
switch (y.storage()) {
case 'sparse':
// dense & sparse
c = algorithm01(x, y, rightLogShift, false);
break;
default:
// dense & dense
c = algorithm13(x, y, rightLogShift);
break;
}
break;
}
return c;
},
'Array, Array': function (x, y) {
// use matrix implementation
return rightLogShift(matrix(x), matrix(y)).valueOf();
},
'Array, Matrix': function (x, y) {
// use matrix implementation
return rightLogShift(matrix(x), y);
},
'Matrix, Array': function (x, y) {
// use matrix implementation
return rightLogShift(x, matrix(y));
},
'Matrix, number | BigNumber': function (x, y) {
// check scalar
if (!equalScalar(y, 0)) {
// result
var c;
// check storage format
switch (x.storage()) {
case 'sparse':
c = algorithm11(x, y, rightLogShift, false);
break;
default:
c = algorithm14(x, y, rightLogShift, false);
break;
}
return c;
}
return x.clone();
},
'number | BigNumber, Matrix': function (x, y) {
// check scalar
if (!equalScalar(x, 0)) {
// result
var c;
// check storage format
switch (y.storage()) {
case 'sparse':
c = algorithm10(y, x, rightLogShift, true);
break;
default:
c = algorithm14(y, x, rightLogShift, true);
break;
}
return c;
}
return zeros(y.size(), y.storage());
},
'Array, number | BigNumber': function (x, y) ...
n/a
function factory(type, config, load, typed) {
var matrix = load(require('../../type/matrix/function/matrix'));
var equalScalar = load(require('../relational/equalScalar'));
var zeros = load(require('../matrix/zeros'));
var algorithm11 = load(require('../../type/matrix/utils/algorithm11'));
var algorithm12 = load(require('../../type/matrix/utils/algorithm12'));
var algorithm14 = load(require('../../type/matrix/utils/algorithm14'));
/**
* Round a value towards the nearest integer.
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.round(x)
* math.round(x, n)
*
* Examples:
*
* math.round(3.2); // returns number 3
* math.round(3.8); // returns number 4
* math.round(-4.2); // returns number -4
* math.round(-4.7); // returns number -5
* math.round(math.pi, 3); // returns number 3.142
* math.round(123.45678, 2); // returns number 123.46
*
* var c = math.complex(3.2, -2.7);
* math.round(c); // returns Complex 3 - 3i
*
* math.round([3.2, 3.8, -4.7]); // returns Array [3, 4, -5]
*
* See also:
*
* ceil, fix, floor
*
* @param {number | BigNumber | Fraction | Complex | Array | Matrix} x Number to be rounded
* @param {number | BigNumber | Array} [n=0] Number of decimals
* @return {number | BigNumber | Fraction | Complex | Array | Matrix} Rounded value
*/
var round = typed('round', {
'number': Math.round,
'number, number': function (x, n) {
if (!isInteger(n)) {throw new TypeError(NO_INT);}
if (n < 0 || n > 15) {throw new Error('Number of decimals in function round must be in te range of 0-15');}
return _round(x, n);
},
'Complex': function (x) {
return x.round();
},
'Complex, number': function (x, n) {
if (n % 1) {throw new TypeError(NO_INT);}
return x.round(n);
},
'Complex, BigNumber': function (x, n) {
if (!n.isInteger()) {throw new TypeError(NO_INT);}
var _n = n.toNumber();
return x.round(_n);
},
'number, BigNumber': function (x, n) {
if (!n.isInteger()) {throw new TypeError(NO_INT);}
return new type.BigNumber(x).toDecimalPlaces(n.toNumber());
},
'BigNumber': function (x) {
return x.toDecimalPlaces(0);
},
'BigNumber, BigNumber': function (x, n) {
if (!n.isInteger()) {throw new TypeError(NO_INT);}
return x.toDecimalPlaces(n.toNumber());
},
'Fraction': function (x) {
return x.round();
},
'Fraction, number': function (x, n) {
if (n % 1) {throw new TypeError(NO_INT);}
return x.round(n);
},
'Array | Matrix': function (x) {
// deep map collection, skip zeros since round(0) = 0
return deepMap(x, round, true);
},
'Matrix, number | BigNumber': function (x, y) {
// result
var c;
// check storage format
switch (x.storage()) {
case 'sparse':
c = algorithm11(x, y, round, false);
break;
default:
c = algorithm14(x, y, round, false);
break;
}
return c;
},
'number | Complex | BigNumber, Matrix': function (x, y) {
// check scalar is zero
if (!equalScalar(x, 0)) {
// result
var c;
// check storage format
switch (y.storage()) {
case 'sparse':
c = algorithm12(y, x, round, true);
break;
default:
c = algorithm14(y, x, round, true);
break;
}
return c;
}
// do not execute algorithm, result will be a zero matrix
return zeros(y.size(), y.storage());
},
'Array, number | BigNumber': function (x, y) {
// use matrix implementation
return algorithm14(matrix(x), y, round, false).valueOf();
},
'number | Complex | BigNumber, Array': function (x, y) {
// use matrix implementation
return algo ...
n/a
function factory(type, config, load, typed) {
/**
* Calculate the secant of a value, defined as `sec(x) = 1/cos(x)`.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.sec(x)
*
* Examples:
*
* math.sec(2); // returns number -2.4029979617223822
* 1 / math.cos(2); // returns number -2.4029979617223822
*
* See also:
*
* cos, csc, cot
*
* @param {number | Complex | Unit | Array | Matrix} x Function input
* @return {number | Complex | Array | Matrix} Secant of x
*/
var sec = typed('sec', {
'number': function (x) {
return 1 / Math.cos(x);
},
'Complex': function (x) {
return x.sec();
},
'BigNumber': function (x) {
return new type.BigNumber(1).div(x.cos());
},
'Unit': function (x) {
if (!x.hasBase(type.Unit.BASE_UNITS.ANGLE)) {
throw new TypeError ('Unit in function sec is no angle');
}
return sec(x.value);
},
'Array | Matrix': function (x) {
return deepMap(x, sec);
}
});
sec.toTex = {1: '\\sec\\left(${args[0]}\\right)'};
return sec;
}
n/a
function factory(type, config, load, typed) { /** * Calculate the hyperbolic secant of a value, * defined as `sech(x) = 1 / cosh(x)`. * * For matrices, the function is evaluated element wise. * * Syntax: * * math.sech(x) * * Examples: * * // sech(x) = 1/ cosh(x) * math.sech(0.5); // returns 0.886818883970074 * 1 / math.cosh(0.5); // returns 0.886818883970074 * * See also: * * cosh, csch, coth * * @param {number | Complex | Unit | Array | Matrix} x Function input * @return {number | Complex | Array | Matrix} Hyperbolic secant of x */ var sech = typed('sech', { 'number': _sech, 'Complex': function (x) { return x.sech(); }, 'BigNumber': function (x) { return new type.BigNumber(1).div(x.cosh()); }, 'Unit': function (x) { if (!x.hasBase(type.Unit.BASE_UNITS.ANGLE)) { throw new TypeError ('Unit in function sech is no angle'); } return sech(x.value); }, 'Array | Matrix': function (x) { return deepMap(x, sech); } }); sech.toTex = {1: '\\mathrm{sech}\\left(${args[0]}\\right)'}; return sech; }
n/a
function factory(type, config, load, typed) {
/**
* Compute the sign of a value. The sign of a value x is:
*
* - 1 when x > 1
* - -1 when x < 0
* - 0 when x == 0
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.sign(x)
*
* Examples:
*
* math.sign(3.5); // returns 1
* math.sign(-4.2); // returns -1
* math.sign(0); // returns 0
*
* math.sign([3, 5, -2, 0, 2]); // returns [1, 1, -1, 0, 1]
*
* See also:
*
* abs
*
* @param {number | BigNumber | Fraction | Complex | Array | Matrix | Unit} x
* The number for which to determine the sign
* @return {number | BigNumber | Fraction | Complex | Array | Matrix | Unit}e
* The sign of `x`
*/
var sign = typed('sign', {
'number': number.sign,
'Complex': function (x) {
return x.sign();
},
'BigNumber': function (x) {
return new type.BigNumber(x.cmp(0));
},
'Fraction': function (x) {
return new type.Fraction(x.s, 1);
},
'Array | Matrix': function (x) {
// deep map collection, skip zeros since sign(0) = 0
return deepMap(x, sign, true);
},
'Unit': function(x) {
return sign(x.value);
}
});
sign.toTex = {1: '\\mathrm{${name}}\\left(${args[0]}\\right)'};
return sign;
}
n/a
function factory(type, config, load, typed) {
var parse = load(require('../../expression/parse'));
var ConstantNode = load(require('../../expression/node/ConstantNode'));
var FunctionNode = load(require('../../expression/node/FunctionNode'));
var OperatorNode = load(require('../../expression/node/OperatorNode'));
var ParenthesisNode = load(require('../../expression/node/ParenthesisNode'));
var SymbolNode = load(require('../../expression/node/SymbolNode'));
var Node = load(require('../../expression/node/Node'));
var simplifyConstant = load(require('./simplify/simplifyConstant'));
var util = load(require('./simplify/util'));
var isCommutative = util.isCommutative;
var isAssociative = util.isAssociative;
var flatten = util.flatten;
var unflattenr = util.unflattenr;
var unflattenl = util.unflattenl;
var createMakeNodeFunction = util.createMakeNodeFunction;
/**
* Simplify an expression tree.
*
* It's possible to pass a custom set of rules to the function as second
* argument. A rule can be specified as an object, string, or function:
*
* var rules = [
* { l: 'n1*n3 + n2*n3', r: '(n1+n2)*n3' },
* 'n1*n3 + n2*n3 -> (n1+n2)*n3',
* function (node) {
* // ... return a new node or return the node unchanged
* return node
* }
* ]
*
*
* The default list with rules is exposed on the function as `simplify.rules`
* and can be used as a basis to built a set of custom rules.
*
* For more details on the theory, see:
*
* - [Strategies for simplifying math expressions (Stackoverflow)](http://stackoverflow.com/questions/7540227/strategies-for-simplifying
-math-expressions)
* - [Symbolic computation - Simplification (Wikipedia)](https://en.wikipedia.org/wiki/Symbolic_computation#Simplification)
*
* Syntax:
*
* simplify(expr)
* simplify(expr, rules)
*
* Examples:
*
* math.simplify('2 * 1 * x ^ (2 - 1)'); // Node {2 * x}
* var f = math.parse('2 * 1 * x ^ (2 - 1)');
* math.simplify(f); // Node {2 * x}
*
* See also:
*
* derivative, parse, eval
*
* @param {Node | string} expr
* The expression to be simplified
* @param {Array<{l:string, r: string} | string | function>} [rules]
* Optional list with custom rules
* @return {Node} Returns the simplified form of `expr`
*/
var simplify = typed('simplify', {
'string': function (expr) {
return simplify(parse(expr), simplify.rules);
},
'string, Array': function (expr, rules) {
return simplify(parse(expr), rules);
},
'Node': function (expr) {
return simplify(expr, simplify.rules);
},
'Node, Array': function (expr, rules) {
rules = _buildRules(rules);
var res = removeParens(expr);
var after = res.toString({parenthesis: 'all'});
var before = null;
while(before != after) {
lastsym = 0;
before = after;
for (var i=0; i<rules.length; i++) {
if (typeof rules[i] === 'function') {
res = rules[i](res);
}
else {
flatten(res);
res = applyRule(res, rules[i]);
}
unflattenl(res); // using left-heavy binary tree here since custom rule functions may expect it
}
after = res.toString({parenthesis: 'all'});
}
return res;
}
});
function removeParens(node) {
return node.transform(function(node, path, parent) {
if(node.isParenthesisNode) {
return node.content;
}
else {
return node;
}
});
}
// Array of strings, used to build the ruleSet.
// Each l (left side) and r (right side) are parsed by
// the expression parser into a node tree.
// Left hand sides are matched to subtrees within the
// expression to be parsed and replaced with the right
// hand side.
// TODO: Add support for constraints on constants (either in the form of a '=' expression or a callback [ca ...
n/a
function factory(type, config, load, typed) {
/**
* Calculate the sine of a value.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.sin(x)
*
* Examples:
*
* math.sin(2); // returns number 0.9092974268256813
* math.sin(math.pi / 4); // returns number 0.7071067811865475
* math.sin(math.unit(90, 'deg')); // returns number 1
* math.sin(math.unit(30, 'deg')); // returns number 0.5
*
* var angle = 0.2;
* math.pow(math.sin(angle), 2) + math.pow(math.cos(angle), 2); // returns number ~1
*
* See also:
*
* cos, tan
*
* @param {number | BigNumber | Complex | Unit | Array | Matrix} x Function input
* @return {number | BigNumber | Complex | Array | Matrix} Sine of x
*/
var sin = typed('sin', {
'number': Math.sin,
'Complex': function (x) {
return x.sin();
},
'BigNumber': function (x) {
return x.sin();
},
'Unit': function (x) {
if (!x.hasBase(type.Unit.BASE_UNITS.ANGLE)) {
throw new TypeError ('Unit in function sin is no angle');
}
return sin(x.value);
},
'Array | Matrix': function (x) {
// deep map collection, skip zeros since sin(0) = 0
return deepMap(x, sin, true);
}
});
sin.toTex = {1: '\\sin\\left(${args[0]}\\right)'};
return sin;
}
n/a
function factory(type, config, load, typed) { /** * Calculate the hyperbolic sine of a value, * defined as `sinh(x) = 1/2 * (exp(x) - exp(-x))`. * * For matrices, the function is evaluated element wise. * * Syntax: * * math.sinh(x) * * Examples: * * math.sinh(0.5); // returns number 0.5210953054937474 * * See also: * * cosh, tanh * * @param {number | BigNumber | Complex | Unit | Array | Matrix} x Function input * @return {number | BigNumber | Complex | Array | Matrix} Hyperbolic sine of x */ var sinh = typed('sinh', { 'number': _sinh, 'Complex': function (x) { return x.sinh(); }, 'BigNumber': function (x) { return x.sinh(); }, 'Unit': function (x) { if (!x.hasBase(type.Unit.BASE_UNITS.ANGLE)) { throw new TypeError ('Unit in function sinh is no angle'); } return sinh(x.value); }, 'Array | Matrix': function (x) { // deep map collection, skip zeros since sinh(0) = 0 return deepMap(x, sinh, true); } }); sinh.toTex = {1: '\\sinh\\left(${args[0]}\\right)'}; return sinh; }
n/a
function factory(type, config, load, typed) {
var matrix = load(require('../../type/matrix/function/matrix'));
/**
* Calculate the size of a matrix or scalar.
*
* Syntax:
*
* math.size(x)
*
* Examples:
*
* math.size(2.3); // returns []
* math.size('hello world'); // returns [11]
*
* var A = [[1, 2, 3], [4, 5, 6]];
* math.size(A); // returns [2, 3]
* math.size(math.range(1,6)); // returns [5]
*
* See also:
*
* resize, squeeze, subset
*
* @param {boolean | number | Complex | Unit | string | Array | Matrix} x A matrix
* @return {Array | Matrix} A vector with size of `x`.
*/
var size = typed('size', {
'Matrix': function (x) {
// TODO: return the same matrix type as the input
return matrix(x.size());
},
'Array': array.size,
'string': function (x) {
return (config.matrix === 'Array') ? [x.length] : matrix([x.length]);
},
'number | Complex | BigNumber | Unit | boolean | null': function (x) {
// scalar
return (config.matrix === 'Array') ? [] : matrix([]);
}
});
size.toTex = undefined; // use default template
return size;
}
n/a
function factory(type, config, load, typed) {
var matrix = load(require('../../type/matrix/function/matrix'));
var algorithm03 = load(require('../../type/matrix/utils/algorithm03'));
var algorithm07 = load(require('../../type/matrix/utils/algorithm07'));
var algorithm12 = load(require('../../type/matrix/utils/algorithm12'));
var algorithm13 = load(require('../../type/matrix/utils/algorithm13'));
var algorithm14 = load(require('../../type/matrix/utils/algorithm14'));
var latex = require('../../utils/latex');
/**
* Test whether value x is smaller than y.
*
* The function returns true when x is smaller than y and the relative
* difference between x and y is smaller than the configured epsilon. The
* function cannot be used to compare values smaller than approximately 2.22e-16.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.smaller(x, y)
*
* Examples:
*
* math.smaller(2, 3); // returns true
* math.smaller(5, 2 * 2); // returns false
*
* var a = math.unit('5 cm');
* var b = math.unit('2 inch');
* math.smaller(a, b); // returns true
*
* See also:
*
* equal, unequal, smallerEq, smaller, smallerEq, compare
*
* @param {number | BigNumber | Fraction | boolean | Unit | string | Array | Matrix} x First value to compare
* @param {number | BigNumber | Fraction | boolean | Unit | string | Array | Matrix} y Second value to compare
* @return {boolean | Array | Matrix} Returns true when the x is smaller than y, else returns false
*/
var smaller = typed('smaller', {
'boolean, boolean': function (x, y) {
return x < y;
},
'number, number': function (x, y) {
return x < y && !nearlyEqual(x, y, config.epsilon);
},
'BigNumber, BigNumber': function (x, y) {
return x.lt(y) && !bigNearlyEqual(x, y, config.epsilon);
},
'Fraction, Fraction': function (x, y) {
return x.compare(y) === -1;
},
'Complex, Complex': function (x, y) {
throw new TypeError('No ordering relation is defined for complex numbers');
},
'Unit, Unit': function (x, y) {
if (!x.equalBase(y)) {
throw new Error('Cannot compare units with different base');
}
return smaller(x.value, y.value);
},
'string, string': function (x, y) {
return x < y;
},
'Matrix, Matrix': function (x, y) {
// result
var c;
// process matrix storage
switch (x.storage()) {
case 'sparse':
switch (y.storage()) {
case 'sparse':
// sparse + sparse
c = algorithm07(x, y, smaller);
break;
default:
// sparse + dense
c = algorithm03(y, x, smaller, true);
break;
}
break;
default:
switch (y.storage()) {
case 'sparse':
// dense + sparse
c = algorithm03(x, y, smaller, false);
break;
default:
// dense + dense
c = algorithm13(x, y, smaller);
break;
}
break;
}
return c;
},
'Array, Array': function (x, y) {
// use matrix implementation
return smaller(matrix(x), matrix(y)).valueOf();
},
'Array, Matrix': function (x, y) {
// use matrix implementation
return smaller(matrix(x), y);
},
'Matrix, Array': function (x, y) {
// use matrix implementation
return smaller(x, matrix(y));
},
'Matrix, any': function (x, y) {
// result
var c;
// check storage format
switch (x.storage()) {
case 'sparse':
c = algorithm12(x, y, smaller, false);
break;
default:
c = algorithm14(x, y, smaller, false);
break;
}
return c;
},
'any, Matrix': function (x, y) {
// result
var c;
// check storage format
switch (y.storage()) { ...
n/a
function factory(type, config, load, typed) {
var matrix = load(require('../../type/matrix/function/matrix'));
var algorithm03 = load(require('../../type/matrix/utils/algorithm03'));
var algorithm07 = load(require('../../type/matrix/utils/algorithm07'));
var algorithm12 = load(require('../../type/matrix/utils/algorithm12'));
var algorithm13 = load(require('../../type/matrix/utils/algorithm13'));
var algorithm14 = load(require('../../type/matrix/utils/algorithm14'));
var latex = require('../../utils/latex');
/**
* Test whether value x is smaller or equal to y.
*
* The function returns true when x is smaller than y or the relative
* difference between x and y is smaller than the configured epsilon. The
* function cannot be used to compare values smaller than approximately 2.22e-16.
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.smallerEq(x, y)
*
* Examples:
*
* math.smaller(1 + 2, 3); // returns false
* math.smallerEq(1 + 2, 3); // returns true
*
* See also:
*
* equal, unequal, smaller, larger, largerEq, compare
*
* @param {number | BigNumber | Fraction | boolean | Unit | string | Array | Matrix} x First value to compare
* @param {number | BigNumber | Fraction | boolean | Unit | string | Array | Matrix} y Second value to compare
* @return {boolean | Array | Matrix} Returns true when the x is smaller than y, else returns false
*/
var smallerEq = typed('smallerEq', {
'boolean, boolean': function (x, y) {
return x <= y;
},
'number, number': function (x, y) {
return x <= y || nearlyEqual(x, y, config.epsilon);
},
'BigNumber, BigNumber': function (x, y) {
return x.lte(y) || bigNearlyEqual(x, y, config.epsilon);
},
'Fraction, Fraction': function (x, y) {
return x.compare(y) !== 1;
},
'Complex, Complex': function () {
throw new TypeError('No ordering relation is defined for complex numbers');
},
'Unit, Unit': function (x, y) {
if (!x.equalBase(y)) {
throw new Error('Cannot compare units with different base');
}
return smallerEq(x.value, y.value);
},
'string, string': function (x, y) {
return x <= y;
},
'Matrix, Matrix': function (x, y) {
// result
var c;
// process matrix storage
switch (x.storage()) {
case 'sparse':
switch (y.storage()) {
case 'sparse':
// sparse + sparse
c = algorithm07(x, y, smallerEq);
break;
default:
// sparse + dense
c = algorithm03(y, x, smallerEq, true);
break;
}
break;
default:
switch (y.storage()) {
case 'sparse':
// dense + sparse
c = algorithm03(x, y, smallerEq, false);
break;
default:
// dense + dense
c = algorithm13(x, y, smallerEq);
break;
}
break;
}
return c;
},
'Array, Array': function (x, y) {
// use matrix implementation
return smallerEq(matrix(x), matrix(y)).valueOf();
},
'Array, Matrix': function (x, y) {
// use matrix implementation
return smallerEq(matrix(x), y);
},
'Matrix, Array': function (x, y) {
// use matrix implementation
return smallerEq(x, matrix(y));
},
'Matrix, any': function (x, y) {
// result
var c;
// check storage format
switch (x.storage()) {
case 'sparse':
c = algorithm12(x, y, smallerEq, false);
break;
default:
c = algorithm14(x, y, smallerEq, false);
break;
}
return c;
},
'any, Matrix': function (x, y) {
// result
var c;
// check storage format
switch (y.storage()) {
case 'sparse':
c = algorithm12(y, x, smallerEq, true);
break;
default: ...
n/a
function factory(type, config, load, typed) {
var matrix = load(require('../../type/matrix/function/matrix'));
var asc = load(require('../relational/compare'));
var desc = function (a, b) {
return -asc(a, b);
};
/**
* Sort the items in a matrix.
*
* Syntax:
*
* math.sort(x)
* math.sort(x, compare)
*
* Examples:
*
* math.sort([5, 10, 1]); // returns [1, 5, 10]
* math.sort(['C', 'B', 'A', 'D']); // returns ['A', 'B', 'C', 'D']
*
* function sortByLength (a, b) {
* return a.length - b.length;
* }
* math.sort(['Langdon', 'Tom', 'Sara'], sortByLength); // returns ['Tom', 'Sara', 'Langdon']
*
* See also:
*
* filter, forEach, map
*
* @param {Matrix | Array} x A one dimensional matrix or array to sort
* @param {Function | 'asc' | 'desc'} [compare='asc']
* An optional _comparator function. The function is called as
* `compare(a, b)`, and must return 1 when a > b, -1 when a < b,
* and 0 when a == b.
* @return {Matrix | Array} Returns the sorted matrix.
*/
var sort = typed('sort', {
'Array': function (x) {
_arrayIsVector(x);
return x.sort(asc);
},
'Matrix': function (x) {
_matrixIsVector(x);
return matrix(x.toArray().sort(asc), x.storage());
},
'Array, function': function (x, _comparator) {
_arrayIsVector(x);
return x.sort(_comparator);
},
'Matrix, function': function (x, _comparator) {
_matrixIsVector(x);
return matrix(x.toArray().sort(_comparator), x.storage());
},
'Array, string': function (x, order) {
_arrayIsVector(x);
return x.sort(_comparator(order));
},
'Matrix, string': function (x, order) {
_matrixIsVector(x);
return matrix(x.toArray().sort(_comparator(order)), x.storage());
}
});
sort.toTex = undefined; // use default template
/**
* Get the comparator for given order ('asc' or 'desc')
* @param {'asc' | 'desc'} order
* @return {Function} Returns a _comparator function
*/
function _comparator (order) {
if (order === 'asc') {
return asc;
}
else if (order === 'desc') {
return desc;
}
else {
throw new Error('String "asc" or "desc" expected');
}
}
/**
* Validate whether an array is one dimensional
* Throws an error when this is not the case
* @param {Array} array
* @private
*/
function _arrayIsVector (array) {
if (size(array).length !== 1) {
throw new Error('One dimensional array expected');
}
}
/**
* Validate whether a matrix is one dimensional
* Throws an error when this is not the case
* @param {Matrix} matrix
* @private
*/
function _matrixIsVector (matrix) {
if (matrix.size().length !== 1) {
throw new Error('One dimensional matrix expected');
}
}
return sort;
}
n/a
function factory(type, config, load, typed) {
/**
* Calculate the square root of a value.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.sqrt(x)
*
* Examples:
*
* math.sqrt(25); // returns 5
* math.square(5); // returns 25
* math.sqrt(-4); // returns Complex 2i
*
* See also:
*
* square, multiply, cube, cbrt
*
* @param {number | BigNumber | Complex | Array | Matrix | Unit} x
* Value for which to calculate the square root.
* @return {number | BigNumber | Complex | Array | Matrix | Unit}
* Returns the square root of `x`
*/
var sqrt = typed('sqrt', {
'number': _sqrtNumber,
'Complex': function (x) {
return x.sqrt();
},
'BigNumber': function (x) {
if (!x.isNegative() || config.predictable) {
return x.sqrt();
}
else {
// negative value -> downgrade to number to do complex value computation
return _sqrtNumber(x.toNumber());
}
},
'Array | Matrix': function (x) {
// deep map collection, skip zeros since sqrt(0) = 0
return deepMap(x, sqrt, true);
},
'Unit': function (x) {
// Someday will work for complex units when they are implemented
return x.pow(0.5);
}
});
/**
* Calculate sqrt for a number
* @param {number} x
* @returns {number | Complex} Returns the square root of x
* @private
*/
function _sqrtNumber(x) {
if (x >= 0 || config.predictable) {
return Math.sqrt(x);
}
else {
return new type.Complex(x, 0).sqrt();
}
}
sqrt.toTex = {1: '\\sqrt{${args[0]}}'};
return sqrt;
}
n/a
function factory(type, config, load, typed) {
/**
* Compute the square of a value, `x * x`.
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.square(x)
*
* Examples:
*
* math.square(2); // returns number 4
* math.square(3); // returns number 9
* math.pow(3, 2); // returns number 9
* math.multiply(3, 3); // returns number 9
*
* math.square([1, 2, 3, 4]); // returns Array [1, 4, 9, 16]
*
* See also:
*
* multiply, cube, sqrt, pow
*
* @param {number | BigNumber | Fraction | Complex | Array | Matrix | Unit} x
* Number for which to calculate the square
* @return {number | BigNumber | Fraction | Complex | Array | Matrix | Unit}
* Squared value
*/
var square = typed('square', {
'number': function (x) {
return x * x;
},
'Complex': function (x) {
return x.mul(x);
},
'BigNumber': function (x) {
return x.times(x);
},
'Fraction': function (x) {
return x.mul(x);
},
'Array | Matrix': function (x) {
// deep map collection, skip zeros since square(0) = 0
return deepMap(x, square, true);
},
'Unit': function(x) {
return x.pow(2);
}
});
square.toTex = {1: '\\left(${args[0]}\\right)^2'};
return square;
}
n/a
function factory(type, config, load, typed) {
var matrix = load(require('../../type/matrix/function/matrix'));
/**
* Squeeze a matrix, remove inner and outer singleton dimensions from a matrix.
*
* Syntax:
*
* math.squeeze(x)
*
* Examples:
*
* math.squeeze([3]); // returns 3
* math.squeeze([[3]]); // returns 3
*
* var A = math.zeros(3, 1); // returns [[0], [0], [0]] (size 3x1)
* math.squeeze(A); // returns [0, 0, 0] (size 3)
*
* var B = math.zeros(1, 3); // returns [[0, 0, 0]] (size 1x3)
* math.squeeze(B); // returns [0, 0, 0] (size 3)
*
* // only inner and outer dimensions are removed
* var C = math.zeros(2, 1, 3); // returns [[[0, 0, 0]], [[0, 0, 0]]] (size 2x1x3)
* math.squeeze(C); // returns [[[0, 0, 0]], [[0, 0, 0]]] (size 2x1x3)
*
* See also:
*
* subset
*
* @param {Matrix | Array} x Matrix to be squeezed
* @return {Matrix | Array} Squeezed matrix
*/
var squeeze = typed('squeeze', {
'Array': function (x) {
return array.squeeze(object.clone(x));
},
'Matrix': function (x) {
var res = array.squeeze(x.toArray());
// FIXME: return the same type of matrix as the input
return Array.isArray(res) ? matrix(res) : res;
},
'any': function (x) {
// scalar
return object.clone(x);
}
});
squeeze.toTex = undefined; // use default template
return squeeze;
}
n/a
function factory(type, config, load, typed) {
var sqrt = load(require('../arithmetic/sqrt'));
var variance = load(require('../statistics/var'));
/**
* Compute the standard deviation of a matrix or a list with values.
* The standard deviations is defined as the square root of the variance:
* `std(A) = sqrt(var(A))`.
* In case of a (multi dimensional) array or matrix, the standard deviation
* over all elements will be calculated.
*
* Optionally, the type of normalization can be specified as second
* parameter. The parameter `normalization` can be one of the following values:
*
* - 'unbiased' (default) The sum of squared errors is divided by (n - 1)
* - 'uncorrected' The sum of squared errors is divided by n
* - 'biased' The sum of squared errors is divided by (n + 1)
*
* Syntax:
*
* math.std(a, b, c, ...)
* math.std(A)
* math.std(A, normalization)
*
* Examples:
*
* math.std(2, 4, 6); // returns 2
* math.std([2, 4, 6, 8]); // returns 2.581988897471611
* math.std([2, 4, 6, 8], 'uncorrected'); // returns 2.23606797749979
* math.std([2, 4, 6, 8], 'biased'); // returns 2
*
* math.std([[1, 2, 3], [4, 5, 6]]); // returns 1.8708286933869707
*
* See also:
*
* mean, median, max, min, prod, sum, var
*
* @param {Array | Matrix} array
* A single matrix or or multiple scalar values
* @param {string} [normalization='unbiased']
* Determines how to normalize the variance.
* Choose 'unbiased' (default), 'uncorrected', or 'biased'.
* @return {*} The standard deviation
*/
var std = typed('std', {
// std([a, b, c, d, ...])
'Array | Matrix': _std,
// std([a, b, c, d, ...], normalization)
'Array | Matrix, string': _std,
// std(a, b, c, d, ...)
'...': function (args) {
return _std(args);
}
});
std.toTex = undefined; // use default template
return std;
function _std(array, normalization) {
if (array.length == 0) {
throw new SyntaxError('Function std requires one or more parameters (0 provided)');
}
return sqrt(variance.apply(null, arguments));
}
}
n/a
function factory(type, config, load, typed) {
var add = load(require('../arithmetic/add'));
var subtract = load(require('../arithmetic/subtract'));
var multiply = load(require('../arithmetic/multiply'));
var divide = load(require('../arithmetic/divide'));
var pow = load(require('../arithmetic/pow'));
var factorial = load(require('../probability/factorial'));
var combinations = load(require('../probability/combinations'));
var isNegative = load(require('../utils/isNegative'));
var isInteger = load(require('../utils/isInteger'));
var larger = load(require('../relational/larger'));
/**
* The Stirling numbers of the second kind, counts the number of ways to partition
* a set of n labelled objects into k nonempty unlabelled subsets.
* stirlingS2 only takes integer arguments.
* The following condition must be enforced: k <= n.
*
* If n = k or k = 1, then s(n,k) = 1
*
* Syntax:
*
* math.stirlingS2(n, k)
*
* Examples:
*
* math.stirlingS2(5, 3); //returns 25
*
* See also:
*
* Bell numbers
*
* @param {Number | BigNumber} n Total number of objects in the set
* @param {Number | BigNumber} k Number of objects in the subset
* @return {Number | BigNumber} S(n,k)
*/
var stirlingS2 = typed('stirlingS2', {
'number | BigNumber, number | BigNumber': function (n, k) {
if (!isInteger(n) || isNegative(n) || !isInteger(k) || isNegative(k)) {
throw new TypeError('Non-negative integer value expected in function stirlingS2');
}
else if (larger(k, n)) {
throw new TypeError('k must be less than or equal to n in function stirlingS2');
}
// 1/k! Sum(i=0 -> k) [(-1)^(k-i)*C(k,j)* i^n]
var kFactorial = factorial(k);
var result = 0;
for(var i = 0; i <= k; i++) {
var negativeOne = pow(-1, subtract(k,i));
var kChooseI = combinations(k,i);
var iPower = pow(i,n);
result = add(result, multiply(multiply(kChooseI, iPower), negativeOne));
}
return divide(result, kFactorial);
}
});
stirlingS2.toTex = {2: '\\mathrm{S}\\left(${args}\\right)'};
return stirlingS2;
}
n/a
function factory(type, config, load, typed) {
/**
* Create a string or convert any object into a string.
* Elements of Arrays and Matrices are processed element wise.
*
* Syntax:
*
* math.string(value)
*
* Examples:
*
* math.string(4.2); // returns string '4.2'
* math.string(math.complex(3, 2); // returns string '3 + 2i'
*
* var u = math.unit(5, 'km');
* math.string(u.to('m')); // returns string '5000 m'
*
* math.string([true, false]); // returns ['true', 'false']
*
* See also:
*
* bignumber, boolean, complex, index, matrix, number, unit
*
* @param {* | Array | Matrix | null} [value] A value to convert to a string
* @return {string | Array | Matrix} The created string
*/
var string = typed('string', {
'': function () {
return '';
},
'number': number.format,
'null': function (x) {
return 'null';
},
'boolean': function (x) {
return x + '';
},
'string': function (x) {
return x;
},
'Array | Matrix': function (x) {
return deepMap(x, string);
},
'any': function (x) {
return String(x);
}
});
string.toTex = {
0: '\\mathtt{""}',
1: '\\mathrm{string}\\left(${args[0]}\\right)'
};
return string;
}
n/a
function factory(type, config, load, typed) {
var matrix = load(require('../../type/matrix/function/matrix'));
/**
* Get or set a subset of a matrix or string.
*
* Syntax:
* math.subset(value, index) // retrieve a subset
* math.subset(value, index, replacement [, defaultValue]) // replace a subset
*
* Examples:
*
* // get a subset
* var d = [[1, 2], [3, 4]];
* math.subset(d, math.index(1, 0)); // returns 3
* math.subset(d, math.index([0, 2], 1)); // returns [[2], [4]]
*
* // replace a subset
* var e = [];
* var f = math.subset(e, math.index(0, [0, 2]), [5, 6]); // f = [[5, 6]]
* var g = math.subset(f, math.index(1, 1), 7, 0); // g = [[5, 6], [0, 7]]
*
* See also:
*
* size, resize, squeeze, index
*
* @param {Array | Matrix | string} matrix An array, matrix, or string
* @param {Index} index An index containing ranges for each
* dimension
* @param {*} [replacement] An array, matrix, or scalar.
* If provided, the subset is replaced with replacement.
* If not provided, the subset is returned
* @param {*} [defaultValue=undefined] Default value, filled in on new entries when
* the matrix is resized. If not provided,
* math.matrix elements will be left undefined.
* @return {Array | Matrix | string} Either the retrieved subset or the updated matrix.
*/
var subset = typed('subset', {
// get subset
'Array, Index': function (value, index) {
var m = matrix(value);
var subset = m.subset(index); // returns a Matrix
return subset && subset.valueOf(); // return an Array (like the input)
},
'Matrix, Index': function (value, index) {
return value.subset(index);
},
'Object, Index': _getObjectProperty,
'string, Index': _getSubstring,
// set subset
'Array, Index, any': function (value, index, replacement) {
return matrix(clone(value))
.subset(index, replacement, undefined)
.valueOf();
},
'Array, Index, any, any': function (value, index, replacement, defaultValue) {
return matrix(clone(value))
.subset(index, replacement, defaultValue)
.valueOf();
},
'Matrix, Index, any': function (value, index, replacement) {
return value.clone().subset(index, replacement);
},
'Matrix, Index, any, any': function (value, index, replacement, defaultValue) {
return value.clone().subset(index, replacement, defaultValue);
},
'string, Index, string': _setSubstring,
'string, Index, string, string': _setSubstring,
'Object, Index, any': _setObjectProperty
});
subset.toTex = undefined; // use default template
return subset;
/**
* Retrieve a subset of a string
* @param {string} str string from which to get a substring
* @param {Index} index An index containing ranges for each dimension
* @returns {string} substring
* @private
*/
function _getSubstring(str, index) {
if (!index || index.isIndex !== true) {
// TODO: better error message
throw new TypeError('Index expected');
}
if (index.size().length != 1) {
throw new DimensionError(index.size().length, 1);
}
// validate whether the range is out of range
var strLen = str.length;
validateIndex(index.min()[0], strLen);
validateIndex(index.max()[0], strLen);
var range = index.dimension(0);
var substr = '';
range.forEach(function (v) {
substr += str.charAt(v);
});
return substr;
}
/**
* Replace a substring in a string
* @param {string} str string to be replaced
* @param {Index} index An index containing ranges for each dimension
* @param {string} ...
n/a
function factory(type, config, load, typed) { var subset = load(require('../../function/matrix/subset')); return typed('subset', { '...any': function (args) { try { return subset.apply(null, args); } catch (err) { throw errorTransform(err); } } }); }
n/a
function factory(type, config, load, typed) {
var latex = require('../../utils/latex');
var matrix = load(require('../../type/matrix/function/matrix'));
var addScalar = load(require('./addScalar'));
var unaryMinus = load(require('./unaryMinus'));
var algorithm01 = load(require('../../type/matrix/utils/algorithm01'));
var algorithm03 = load(require('../../type/matrix/utils/algorithm03'));
var algorithm05 = load(require('../../type/matrix/utils/algorithm05'));
var algorithm10 = load(require('../../type/matrix/utils/algorithm10'));
var algorithm13 = load(require('../../type/matrix/utils/algorithm13'));
var algorithm14 = load(require('../../type/matrix/utils/algorithm14'));
// TODO: split function subtract in two: subtract and subtractScalar
/**
* Subtract two values, `x - y`.
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.subtract(x, y)
*
* Examples:
*
* math.subtract(5.3, 2); // returns number 3.3
*
* var a = math.complex(2, 3);
* var b = math.complex(4, 1);
* math.subtract(a, b); // returns Complex -2 + 2i
*
* math.subtract([5, 7, 4], 4); // returns Array [1, 3, 0]
*
* var c = math.unit('2.1 km');
* var d = math.unit('500m');
* math.subtract(c, d); // returns Unit 1.6 km
*
* See also:
*
* add
*
* @param {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} x
* Initial value
* @param {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} y
* Value to subtract from `x`
* @return {number | BigNumber | Fraction | Complex | Unit | Array | Matrix}
* Subtraction of `x` and `y`
*/
var subtract = typed('subtract', {
'number, number': function (x, y) {
return x - y;
},
'Complex, Complex': function (x, y) {
return x.sub(y);
},
'BigNumber, BigNumber': function (x, y) {
return x.minus(y);
},
'Fraction, Fraction': function (x, y) {
return x.sub(y);
},
'Unit, Unit': function (x, y) {
if (x.value == null) {
throw new Error('Parameter x contains a unit with undefined value');
}
if (y.value == null) {
throw new Error('Parameter y contains a unit with undefined value');
}
if (!x.equalBase(y)) {
throw new Error('Units do not match');
}
var res = x.clone();
res.value = subtract(res.value, y.value);
res.fixPrefix = false;
return res;
},
'Matrix, Matrix': function (x, y) {
// matrix sizes
var xsize = x.size();
var ysize = y.size();
// check dimensions
if (xsize.length !== ysize.length)
throw new DimensionError(xsize.length, ysize.length);
// result
var c;
// process matrix storage
switch (x.storage()) {
case 'sparse':
switch (y.storage()) {
case 'sparse':
// sparse - sparse
c = algorithm05(x, y, subtract);
break;
default:
// sparse - dense
c = algorithm03(y, x, subtract, true);
break;
}
break;
default:
switch (y.storage()) {
case 'sparse':
// dense - sparse
c = algorithm01(x, y, subtract, false);
break;
default:
// dense - dense
c = algorithm13(x, y, subtract);
break;
}
break;
}
return c;
},
'Array, Array': function (x, y) {
// use matrix implementation
return subtract(matrix(x), matrix(y)).valueOf();
},
'Array, Matrix': function (x, y) {
// use matrix implementation
return subtract(matrix(x), y);
},
'Matrix, Array': function (x, y) {
// use matrix implementation
return subtract(x, matrix(y));
},
'Matrix, any': function (x, y) {
// result
var c;
// check stor ...
n/a
function factory(type, config, load, typed) {
var add = load(require('../arithmetic/addScalar'));
/**
* Compute the sum of a matrix or a list with values.
* In case of a (multi dimensional) array or matrix, the sum of all
* elements will be calculated.
*
* Syntax:
*
* math.sum(a, b, c, ...)
* math.sum(A)
*
* Examples:
*
* math.sum(2, 1, 4, 3); // returns 10
* math.sum([2, 1, 4, 3]); // returns 10
* math.sum([[2, 5], [4, 3], [1, 7]]); // returns 22
*
* See also:
*
* mean, median, min, max, prod, std, var
*
* @param {... *} args A single matrix or or multiple scalar values
* @return {*} The sum of all values
*/
var sum = typed('sum', {
'Array | Matrix': function (args) {
// sum([a, b, c, d, ...])
return _sum(args);
},
'Array | Matrix, number | BigNumber': function () {
// sum([a, b, c, d, ...], dim)
// TODO: implement sum(A, dim)
throw new Error('sum(A, dim) is not yet supported');
},
'...': function (args) {
// sum(a, b, c, d, ...)
return _sum(args);
}
});
sum.toTex = undefined; // use default template
return sum;
/**
* Recursively calculate the sum of an n-dimensional array
* @param {Array} array
* @return {number} sum
* @private
*/
function _sum(array) {
var sum = undefined;
deepForEach(array, function (value) {
sum = (sum === undefined) ? value : add(sum, value);
});
if (sum === undefined) {
switch (config.number) {
case 'number':
return 0;
case 'BigNumber':
return new type.BigNumber(0);
case 'Fraction':
return new type.Fraction(0);
default:
return 0;
}
}
return sum;
}
}
n/a
function factory(type, config, load, typed) {
/**
* Calculate the tangent of a value. `tan(x)` is equal to `sin(x) / cos(x)`.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.tan(x)
*
* Examples:
*
* math.tan(0.5); // returns number 0.5463024898437905
* math.sin(0.5) / math.cos(0.5); // returns number 0.5463024898437905
* math.tan(math.pi / 4); // returns number 1
* math.tan(math.unit(45, 'deg')); // returns number 1
*
* See also:
*
* atan, sin, cos
*
* @param {number | BigNumber | Complex | Unit | Array | Matrix} x Function input
* @return {number | BigNumber | Complex | Array | Matrix} Tangent of x
*/
var tan = typed('tan', {
'number': Math.tan,
'Complex': function (x) {
return x.tan();
},
'BigNumber': function (x) {
return x.tan();
},
'Unit': function (x) {
if (!x.hasBase(type.Unit.BASE_UNITS.ANGLE)) {
throw new TypeError ('Unit in function tan is no angle');
}
return tan(x.value);
},
'Array | Matrix': function (x) {
// deep map collection, skip zeros since tan(0) = 0
return deepMap(x, tan, true);
}
});
tan.toTex = {1: '\\tan\\left(${args[0]}\\right)'};
return tan;
}
n/a
function factory(type, config, load, typed) { /** * Calculate the hyperbolic tangent of a value, * defined as `tanh(x) = (exp(2 * x) - 1) / (exp(2 * x) + 1)`. * * For matrices, the function is evaluated element wise. * * Syntax: * * math.tanh(x) * * Examples: * * // tanh(x) = sinh(x) / cosh(x) = 1 / coth(x) * math.tanh(0.5); // returns 0.46211715726000974 * math.sinh(0.5) / math.cosh(0.5); // returns 0.46211715726000974 * 1 / math.coth(0.5); // returns 0.46211715726000974 * * See also: * * sinh, cosh, coth * * @param {number | BigNumber | Complex | Unit | Array | Matrix} x Function input * @return {number | BigNumber | Complex | Array | Matrix} Hyperbolic tangent of x */ var tanh = typed('tanh', { 'number': _tanh, 'Complex': function (x) { return x.tanh(); }, 'BigNumber': function (x) { return x.tanh(); }, 'Unit': function (x) { if (!x.hasBase(type.Unit.BASE_UNITS.ANGLE)) { throw new TypeError ('Unit in function tanh is no angle'); } return tanh(x.value); }, 'Array | Matrix': function (x) { // deep map collection, skip zeros since tanh(0) = 0 return deepMap(x, tanh, true); } }); tanh.toTex = {1: '\\tanh\\left(${args[0]}\\right)'}; return tanh; }
n/a
function factory(type, config, load, typed) {
var latex = require('../../utils/latex');
var matrix = load(require('../../type/matrix/function/matrix'));
var algorithm13 = load(require('../../type/matrix/utils/algorithm13'));
var algorithm14 = load(require('../../type/matrix/utils/algorithm14'));
/**
* Change the unit of a value.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.to(x, unit)
*
* Examples:
*
* math.to(math.unit('2 inch'), 'cm'); // returns Unit 5.08 cm
* math.to(math.unit('2 inch'), math.unit(null, 'cm')); // returns Unit 5.08 cm
* math.to(math.unit(16, 'bytes'), 'bits'); // returns Unit 128 bits
*
* See also:
*
* unit
*
* @param {Unit | Array | Matrix} x The unit to be converted.
* @param {Unit | Array | Matrix} unit New unit. Can be a string like "cm"
* or a unit without value.
* @return {Unit | Array | Matrix} value with changed, fixed unit.
*/
var to = typed('to', {
'Unit, Unit | string': function (x, unit) {
return x.to(unit);
},
'Matrix, Matrix': function (x, y) {
// SparseMatrix does not support Units
return algorithm13(x, y, to);
},
'Array, Array': function (x, y) {
// use matrix implementation
return to(matrix(x), matrix(y)).valueOf();
},
'Array, Matrix': function (x, y) {
// use matrix implementation
return to(matrix(x), y);
},
'Matrix, Array': function (x, y) {
// use matrix implementation
return to(x, matrix(y));
},
'Matrix, any': function (x, y) {
// SparseMatrix does not support Units
return algorithm14(x, y, to, false);
},
'any, Matrix': function (x, y) {
// SparseMatrix does not support Units
return algorithm14(y, x, to, true);
},
'Array, any': function (x, y) {
// use matrix implementation
return algorithm14(matrix(x), y, to, false).valueOf();
},
'any, Array': function (x, y) {
// use matrix implementation
return algorithm14(matrix(y), x, to, true).valueOf();
}
});
to.toTex = {
2: '\\left(${args[0]}' + latex.operators['to'] + '${args[1]}\\right)'
};
return to;
}
n/a
function factory(type, config, load, typed) {
var matrix = load(require('../../type/matrix/function/matrix'));
var add = load(require('../arithmetic/add'));
/**
* Calculate the trace of a matrix: the sum of the elements on the main
* diagonal of a square matrix.
*
* Syntax:
*
* math.trace(x)
*
* Examples:
*
* math.trace([[1, 2], [3, 4]]); // returns 5
*
* var A = [
* [1, 2, 3],
* [-1, 2, 3],
* [2, 0, 3]
* ]
* math.trace(A); // returns 6
*
* See also:
*
* diag
*
* @param {Array | Matrix} x A matrix
*
* @return {number} The trace of `x`
*/
var trace = typed('trace', {
'Array': function (x) {
// use dense matrix implementation
return trace(matrix(x));
},
'Matrix': function (x) {
// result
var c;
// process storage format
switch (x.storage()) {
case 'dense':
c = _denseTrace(x);
break;
case 'sparse':
c = _sparseTrace(x);
break;
}
return c;
},
'any': clone
});
var _denseTrace = function (m) {
// matrix size & data
var size = m._size;
var data = m._data;
// process dimensions
switch (size.length) {
case 1:
// vector
if (size[0] == 1) {
// return data[0]
return clone(data[0]);
}
throw new RangeError('Matrix must be square (size: ' + format(size) + ')');
case 2:
// two dimensional
var rows = size[0];
var cols = size[1];
if (rows === cols) {
// calulate sum
var sum = 0;
// loop diagonal
for (var i = 0; i < rows; i++)
sum = add(sum, data[i][i]);
// return trace
return sum;
}
throw new RangeError('Matrix must be square (size: ' + format(size) + ')');
default:
// multi dimensional
throw new RangeError('Matrix must be two dimensional (size: ' + format(size) + ')');
}
};
var _sparseTrace = function (m) {
// matrix arrays
var values = m._values;
var index = m._index;
var ptr = m._ptr;
var size = m._size;
// check dimensions
var rows = size[0];
var columns = size[1];
// matrix must be square
if (rows === columns) {
// calulate sum
var sum = 0;
// check we have data (avoid looping columns)
if (values.length > 0) {
// loop columns
for (var j = 0; j < columns; j++) {
// k0 <= k < k1 where k0 = _ptr[j] && k1 = _ptr[j+1]
var k0 = ptr[j];
var k1 = ptr[j + 1];
// loop k within [k0, k1[
for (var k = k0; k < k1; k++) {
// row index
var i = index[k];
// check row
if (i === j) {
// accumulate value
sum = add(sum, values[k]);
// exit loop
break;
}
if (i > j) {
// exit loop, no value on the diagonal for column j
break;
}
}
}
}
// return trace
return sum;
}
throw new RangeError('Matrix must be square (size: ' + format(size) + ')');
};
trace.toTex = {1: '\\mathrm{tr}\\left(${args[0]}\\right)'};
return trace;
}
n/a
function factory(type, config, load, typed) {
var latex = require('../../utils/latex');
var matrix = load(require('../../type/matrix/function/matrix'));
var DenseMatrix = type.DenseMatrix,
SparseMatrix = type.SparseMatrix;
/**
* Transpose a matrix. All values of the matrix are reflected over its
* main diagonal. Only applicable to two dimensional matrices containing
* a vector (i.e. having size `[1,n]` or `[n,1]`). One dimensional
* vectors and scalars return the input unchanged.
*
* Syntax:
*
* math.transpose(x)
*
* Examples:
*
* var A = [[1, 2, 3], [4, 5, 6]];
* math.transpose(A); // returns [[1, 4], [2, 5], [3, 6]]
*
* See also:
*
* diag, inv, subset, squeeze
*
* @param {Array | Matrix} x Matrix to be transposed
* @return {Array | Matrix} The transposed matrix
*/
var transpose = typed('transpose', {
'Array': function (x) {
// use dense matrix implementation
return transpose(matrix(x)).valueOf();
},
'Matrix': function (x) {
// matrix size
var size = x.size();
// result
var c;
// process dimensions
switch (size.length) {
case 1:
// vector
c = x.clone();
break;
case 2:
// rows and columns
var rows = size[0];
var columns = size[1];
// check columns
if (columns === 0) {
// throw exception
throw new RangeError('Cannot transpose a 2D matrix with no columns (size: ' + format(size) + ')');
}
// process storage format
switch (x.storage()) {
case 'dense':
c = _denseTranspose(x, rows, columns);
break;
case 'sparse':
c = _sparseTranspose(x, rows, columns);
break;
}
break;
default:
// multi dimensional
throw new RangeError('Matrix must be a vector or two dimensional (size: ' + format(this._size) + ')');
}
return c;
},
// scalars
'any': function (x) {
return clone(x);
}
});
var _denseTranspose = function (m, rows, columns) {
// matrix array
var data = m._data;
// transposed matrix data
var transposed = [];
var transposedRow;
// loop columns
for (var j = 0; j < columns; j++) {
// initialize row
transposedRow = transposed[j] = [];
// loop rows
for (var i = 0; i < rows; i++) {
// set data
transposedRow[i] = clone(data[i][j]);
}
}
// return matrix
return new DenseMatrix({
data: transposed,
size: [columns, rows],
datatype: m._datatype
});
};
var _sparseTranspose = function (m, rows, columns) {
// matrix arrays
var values = m._values;
var index = m._index;
var ptr = m._ptr;
// result matrices
var cvalues = values ? [] : undefined;
var cindex = [];
var cptr = [];
// row counts
var w = [];
for (var x = 0; x < rows; x++)
w[x] = 0;
// vars
var p, l, j;
// loop values in matrix
for (p = 0, l = index.length; p < l; p++) {
// number of values in row
w[index[p]]++;
}
// cumulative sum
var sum = 0;
// initialize cptr with the cummulative sum of row counts
for (var i = 0; i < rows; i++) {
// update cptr
cptr.push(sum);
// update sum
sum += w[i];
// update w
w[i] = cptr[i];
}
// update cptr
cptr.push(sum);
// loop columns
for (j = 0; j < columns; j++) {
// values & index in column
for (var k0 = ptr[j], k1 = ptr[j + 1], k = k0; k < k1; k++) {
// C values & index
var q = w[index[k]]++;
// C[j, i] = A[i, j]
cindex[q] = j;
// check we need to process values (pattern matrix)
if (values)
cvalues[q] = clone(values[k]);
}
}
// return matrix
return new SparseMatrix({
values: cvalues,
index: ...
n/a
function Decimal(v) { var e, i, t, x = this; // Decimal called without new. if (!(x instanceof Decimal)) return new Decimal(v); // Retain a reference to this Decimal constructor, and shadow Decimal.prototype.constructor // which points to Object. x.constructor = Decimal; // Duplicate. if (v instanceof Decimal) { x.s = v.s; x.e = v.e; x.d = (v = v.d) ? v.slice() : v; return; } t = typeof v; if (t === 'number') { if (v === 0) { x.s = 1 / v < 0 ? -1 : 1; x.e = 0; x.d = [0]; return; } if (v < 0) { v = -v; x.s = -1; } else { x.s = 1; } // Fast path for small integers. if (v === ~~v && v < 1e7) { for (e = 0, i = v; i >= 10; i /= 10) e++; x.e = e; x.d = [v]; return; // Infinity, NaN. } else if (v * 0 !== 0) { if (!v) x.s = NaN; x.e = NaN; x.d = null; return; } return parseDecimal(x, v.toString()); } else if (t !== 'string') { throw Error(invalidArgument + v); } // Minus sign? if (v.charCodeAt(0) === 45) { v = v.slice(1); x.s = -1; } else { x.s = 1; } return isDecimal.test(v) ? parseDecimal(x, v) : parseOther(x, v); }
...
setConstant(math, 'true', true);
setConstant(math, 'false', false);
setConstant(math, 'null', null);
setConstant(math, 'uninitialized', require('./utils/array').UNINITIALIZED);
if (config.number === 'BigNumber') {
setConstant(math, 'Infinity', new type.BigNumber(Infinity));
setConstant(math, 'NaN', new type.BigNumber(NaN));
setLazyConstant(math, 'pi', function () {return bigConstants.pi(type.BigNumber)});
setLazyConstant(math, 'tau', function () {return bigConstants.tau(type.BigNumber)});
setLazyConstant(math, 'e', function () {return bigConstants.e(type.BigNumber)});
setLazyConstant(math, 'phi', function () {return bigConstants.phi(type.BigNumber)}); // golden ratio, (1+sqrt(5))/2
...
function Chain(value) { if (!(this instanceof Chain)) { throw new SyntaxError('Constructor must be called with the new operator'); } if (value && value.isChain) { this.value = value.value; } else { this.value = value; } }
n/a
function Complex(a, b) { if (!(this instanceof Complex)) { return new Complex(a, b); } parse(a, b); // mutates P this["re"] = P["re"]; this["im"] = P["im"]; }
...
}
return new type.BigNumber(x);
}
}, {
from: 'number',
to: 'Complex',
convert: function (x) {
return new type.Complex(x, 0);
}
}, {
from: 'number',
to: 'string',
convert: function (x) {
return x + '';
}
...
function DenseMatrix(data, datatype) { if (!(this instanceof DenseMatrix)) throw new SyntaxError('Constructor must be called with the new operator'); if (datatype && !isString(datatype)) throw new Error('Invalid datatype: ' + datatype); if (data && data.isMatrix === true) { // check data is a DenseMatrix if (data.type === 'DenseMatrix') { // clone data & size this._data = object.clone(data._data); this._size = object.clone(data._size); this._datatype = datatype || data._datatype; } else { // build data from existing matrix this._data = data.toArray(); this._size = data.size(); this._datatype = datatype || data._datatype; } } else if (data && isArray(data.data) && isArray(data.size)) { // initialize fields from JSON representation this._data = data.data; this._size = data.size; this._datatype = datatype || data.datatype; } else if (isArray(data)) { // replace nested Matrices with Arrays this._data = preprocess(data); // get the dimensions of the array this._size = array.size(this._data); // verify the dimensions of the array, TODO: compute size while processing array array.validate(this._data, this._size); // data type unknown this._datatype = datatype; } else if (data) { // unsupported type throw new TypeError('Unsupported type of data (' + util.types.type(data) + ')'); } else { // nothing provided this._data = []; this._size = [0]; this._datatype = datatype; } }
...
return new type.Fraction(0);
}
}, {
from: 'Array',
to: 'Matrix',
convert: function (array) {
// TODO: how to decide on the right type of matrix to create?
return new type.DenseMatrix(array);
}
}, {
from: 'Matrix',
to: 'Array',
convert: function (matrix) {
return matrix.valueOf();
}
...
function FibonacciHeap() { if (!(this instanceof FibonacciHeap)) throw new SyntaxError('Constructor must be called with the new operator'); // initialize fields this._minimum = null; this._size = 0; }
...
*/
function Spa() {
if (!(this instanceof Spa))
throw new SyntaxError('Constructor must be called with the new operator');
// allocate vector, TODO use typed arrays
this._values = [];
this._heap = new type.FibonacciHeap();
}
/**
* Attach type information
*/
Spa.prototype.type = 'Spa';
Spa.prototype.isSpa = true;
...
function Fraction(a, b) { if (!(this instanceof Fraction)) { return new Fraction(a, b); } parse(a, b); if (Fraction['REDUCE']) { a = gcd(P["d"], P["n"]); // Abuse a } else { a = 1; } this["s"] = P["s"]; this["n"] = P["n"] / a; this["d"] = P["d"] / a; }
...
to: 'Fraction',
convert: function (x) {
if (digits(x) > 15) {
throw new TypeError('Cannot implicitly convert a number with >15 significant digits to Fraction ' +
'(value: ' + x + '). ' +
'Use function fraction(x) to convert to Fraction.');
}
return new type.Fraction(x);
}
}, {
// FIXME: add conversion from Fraction to number, for example for `sqrt(fraction(1,3))`
// from: 'Fraction',
// to: 'number',
// convert: function (x) {
// return x.valueOf();
...
function Help(doc) { if (!(this instanceof Help)) { throw new SyntaxError('Constructor must be called with the new operator'); } if (!doc) throw new Error('Argument "doc" missing'); this.doc = doc; }
n/a
function ImmutableDenseMatrix(data, datatype) { if (!(this instanceof ImmutableDenseMatrix)) throw new SyntaxError('Constructor must be called with the new operator'); if (datatype && !isString(datatype)) throw new Error('Invalid datatype: ' + datatype); if ((data && data.isMatrix === true) || isArray(data)) { // use DenseMatrix implementation var matrix = new DenseMatrix(data, datatype); // internal structures this._data = matrix._data; this._size = matrix._size; this._datatype = matrix._datatype; this._min = null; this._max = null; } else if (data && isArray(data.data) && isArray(data.size)) { // initialize fields from JSON representation this._data = data.data; this._size = data.size; this._datatype = data.datatype; this._min = typeof data.min !== 'undefined' ? data.min : null; this._max = typeof data.max !== 'undefined' ? data.max : null; } else if (data) { // unsupported type throw new TypeError('Unsupported type of data (' + util.types.type(data) + ')'); } else { // nothing provided this._data = []; this._size = [0]; this._datatype = datatype; this._min = null; this._max = null; } }
...
// loop array elements
for (var i = 0, l = arg.length; i < l; i++) {
if (typeof arg[i] !== 'number' || !isInteger(arg[i])) {
throw new TypeError('Index parameters must be positive integer numbers');
}
}
// create matrix
return new type.ImmutableDenseMatrix(arg);
}
/**
* Create a clone of the index
* @memberof Index
* @return {Index} clone
*/
...
function Index(ranges) { if (!(this instanceof Index)) { throw new SyntaxError('Constructor must be called with the new operator'); } this._dimensions = []; this._isScalar = true; for (var i = 0, ii = arguments.length; i < ii; i++) { var arg = arguments[i]; if (arg && (arg.isRange === true)) { this._dimensions.push(arg); this._isScalar = false; } else if (arg && (Array.isArray(arg) || arg.isMatrix === true)) { // create matrix var m = _createImmutableMatrix(arg.valueOf()); this._dimensions.push(m); // size var size = m.size(); // scalar if (size.length !== 1 || size[0] !== 1) { this._isScalar = false; } } else if (typeof arg === 'number') { this._dimensions.push(_createImmutableMatrix([arg])); } else if (typeof arg === 'string') { // object property (arguments.count should be 1) this._dimensions.push(arg); } // TODO: implement support for wildcard '*' else { throw new TypeError('Dimension must be an Array, Matrix, number, string, or Range'); } } }
...
else {
throw new TypeError('Dimension must be an Array, Matrix, number, string, or Range');
}
args[i] = arg;
}
var res = new type.Index();
type.Index.apply(res, args);
return res;
};
}
exports.name = 'index';
exports.path = 'expression.transform';
...
function Matrix() { if (!(this instanceof Matrix)) { throw new SyntaxError('Constructor must be called with the new operator'); } }
n/a
function Range(start, end, step) { if (!(this instanceof Range)) { throw new SyntaxError('Constructor must be called with the new operator'); } if (start != null) { if (start.isBigNumber === true) start = start.toNumber(); else if (typeof start !== 'number') throw new TypeError('Parameter start must be a number'); } if (end != null) { if (end.isBigNumber === true) end = end.toNumber(); else if (typeof end !== 'number') throw new TypeError('Parameter end must be a number'); } if (step != null) { if (step.isBigNumber === true) step = step.toNumber(); else if (typeof step !== 'number') throw new TypeError('Parameter step must be a number'); } this.start = (start != null) ? parseFloat(start) : 0; this.end = (end != null) ? parseFloat(end) : 0; this.step = (step != null) ? parseFloat(step) : 1; }
n/a
function ResultSet(entries) { if (!(this instanceof ResultSet)) { throw new SyntaxError('Constructor must be called with the new operator'); } this.entries = entries || []; }
n/a
function Spa() { if (!(this instanceof Spa)) throw new SyntaxError('Constructor must be called with the new operator'); // allocate vector, TODO use typed arrays this._values = []; this._heap = new type.FibonacciHeap(); }
n/a
function SparseMatrix(data, datatype) { if (!(this instanceof SparseMatrix)) throw new SyntaxError('Constructor must be called with the new operator'); if (datatype && !isString(datatype)) throw new Error('Invalid datatype: ' + datatype); if (data && data.isMatrix === true) { // create from matrix _createFromMatrix(this, data, datatype); } else if (data && isArray(data.index) && isArray(data.ptr) && isArray(data.size)) { // initialize fields this._values = data.values; this._index = data.index; this._ptr = data.ptr; this._size = data.size; this._datatype = datatype || data.datatype; } else if (isArray(data)) { // create from array _createFromArray(this, data, datatype); } else if (data) { // unsupported type throw new TypeError('Unsupported type of data (' + util.types.type(data) + ')'); } else { // nothing provided this._values = []; this._index = []; this._ptr = [0]; this._size = [0, 0]; this._datatype = datatype; } }
n/a
function Unit(value, name) { if (!(this instanceof Unit)) { throw new Error('Constructor must be called with the new operator'); } if (!(value === undefined || isNumeric(value) || value.isComplex)) { throw new TypeError('First parameter in Unit constructor must be number, BigNumber, Fraction, Complex, or undefined'); } if (name != undefined && (typeof name !== 'string' || name == '')) { throw new TypeError('Second parameter in Unit constructor must be a string'); } if (name != undefined) { var u = Unit.parse(name); this.units = u.units; this.dimensions = u.dimensions; } else { this.units = [ { unit: UNIT_NONE, prefix: PREFIXES.NONE, // link to a list with supported prefixes power: 0 } ]; this.dimensions = []; for(var i=0; i<BASE_DIMENSIONS.length; i++) { this.dimensions[i] = 0; } } this.value = (value != undefined) ? this._normalize(value) : null; this.fixPrefix = false; // if true, function format will not search for the // best prefix but leave it as initially provided. // fixPrefix is set true by the method Unit.to // The justification behind this is that if the constructor is explicitly called, // the caller wishes the units to be returned exactly as he supplied. this.isUnitListSimplified = true; }
n/a
function Decimal(v) { var e, i, t, x = this; // Decimal called without new. if (!(x instanceof Decimal)) return new Decimal(v); // Retain a reference to this Decimal constructor, and shadow Decimal.prototype.constructor // which points to Object. x.constructor = Decimal; // Duplicate. if (v instanceof Decimal) { x.s = v.s; x.e = v.e; x.d = (v = v.d) ? v.slice() : v; return; } t = typeof v; if (t === 'number') { if (v === 0) { x.s = 1 / v < 0 ? -1 : 1; x.e = 0; x.d = [0]; return; } if (v < 0) { v = -v; x.s = -1; } else { x.s = 1; } // Fast path for small integers. if (v === ~~v && v < 1e7) { for (e = 0, i = v; i >= 10; i /= 10) e++; x.e = e; x.d = [v]; return; // Infinity, NaN. } else if (v * 0 !== 0) { if (!v) x.s = NaN; x.e = NaN; x.d = null; return; } return parseDecimal(x, v.toString()); } else if (t !== 'string') { throw Error(invalidArgument + v); } // Minus sign? if (v.charCodeAt(0) === 45) { v = v.slice(1); x.s = -1; } else { x.s = 1; } return isDecimal.test(v) ? parseDecimal(x, v) : parseOther(x, v); }
...
setConstant(math, 'true', true);
setConstant(math, 'false', false);
setConstant(math, 'null', null);
setConstant(math, 'uninitialized', require('./utils/array').UNINITIALIZED);
if (config.number === 'BigNumber') {
setConstant(math, 'Infinity', new type.BigNumber(Infinity));
setConstant(math, 'NaN', new type.BigNumber(NaN));
setLazyConstant(math, 'pi', function () {return bigConstants.pi(type.BigNumber)});
setLazyConstant(math, 'tau', function () {return bigConstants.tau(type.BigNumber)});
setLazyConstant(math, 'e', function () {return bigConstants.e(type.BigNumber)});
setLazyConstant(math, 'phi', function () {return bigConstants.phi(type.BigNumber)}); // golden ratio, (1+sqrt(5))/2
...
function abs(x) { return new this(x).abs(); }
...
function factory (type, config, load, typed) {
/**
* Calculate the absolute value of a number. For matrices, the function is
* evaluated element wise.
*
* Syntax:
*
* math.abs(x)
*
* Examples:
*
* math.abs(3.5); // returns number 3.5
* math.abs(-4.2); // returns number 4.2
*
* math.abs([3, -5, -1, 0, 2]); // returns Array [3, 5, 1, 0, 2]
...
function acos(x) { return new this(x).acos(); }
...
/**
* Calculate the inverse cosine of a value.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.acos(x)
*
* Examples:
*
* math.acos(0.5); // returns number 1.0471975511965979
* math.acos(math.cos(1.5)); // returns number 1.5
*
* math.acos(2); // returns Complex 0 + 1.3169578969248166 i
...
function acosh(x) { return new this(x).acosh(); }
...
* Calculate the hyperbolic arccos of a value,
* defined as `acosh(x) = ln(sqrt(x^2 - 1) + x)`.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.acosh(x)
*
* Examples:
*
* math.acosh(1.5); // returns 0.9624236501192069
*
* See also:
*
...
function add(x, y) { return new this(x).plus(y); }
...
math.eval('5.08 cm to inch'); // 2 inch
math.eval('sin(45 deg) ^ 2'); // 0.5
math.eval('9 / 3 + 2i'); // 3 + 2i
math.eval('det([-1, 2; 3, 1])'); // -7
// chaining
math.chain(3)
.add(4)
.multiply(2)
.done(); // 14
```
## Browser support
Math.js works on any ES5 compatible JavaScript engine: node.js 0.10, and Internet Explorer 9 and newer, and all other browsers (
Chrome, Firefox, Safari). If support for old browsers like Internet Explorer 8 is required, the [es5-shim](https://github.com/kriskowal
/es5-shim) library has to be loaded.
...
function asin(x) { return new this(x).asin(); }
...
*
* @param {number | Complex | Array | Matrix} x Function input
* @return {number | Complex | Array | Matrix} The arc cosecant of x
*/
var acsc = typed('acsc', {
'number': function (x) {
if (x <= -1 || x >= 1 || config.predictable) {
return Math.asin(1 / x);
}
return new type.Complex(x, 0).acsc();
},
'Complex': function (x) {
return x.acsc();
},
...
function asinh(x) { return new this(x).asinh(); }
...
},
'Complex': function (x) {
return x.acsch();
},
'BigNumber': function (x) {
return new type.BigNumber(1).div(x).asinh();
},
'Array | Matrix': function (x) {
return deepMap(x, acsch);
}
});
...
function atan(x) { return new this(x).atan(); }
...
* cot, atan
*
* @param {number | Complex | Array | Matrix} x Function input
* @return {number | Complex | Array | Matrix} The arc cotangent of x
*/
var acot = typed('acot', {
'number': function (x) {
return Math.atan(1 / x);
},
'Complex': function (x) {
return x.acot();
},
'BigNumber': function (x) {
...
function atan2(y, x) { y = new this(y); x = new this(x); var r, pr = this.precision, rm = this.rounding, wpr = pr + 4; // Either NaN if (!y.s || !x.s) { r = new this(NaN); // Both ±Infinity } else if (!y.d && !x.d) { r = getPi(this, wpr, 1).times(x.s > 0 ? 0.25 : 0.75); r.s = y.s; // x is ±Infinity or y is ±0 } else if (!x.d || y.isZero()) { r = x.s < 0 ? getPi(this, pr, rm) : new this(0); r.s = y.s; // y is ±Infinity or x is ±0 } else if (!y.d || x.isZero()) { r = getPi(this, wpr, 1).times(0.5); r.s = y.s; // Both non-zero and finite } else if (x.s < 0) { this.precision = wpr; this.rounding = 1; r = this.atan(divide(y, x, wpr, 1)); x = getPi(this, wpr, 1); this.precision = pr; this.rounding = rm; r = y.s < 0 ? r.minus(x) : r.plus(x); } else { r = this.atan(divide(y, x, wpr, 1)); } return r; }
...
```js
// load math.js
var math = require('mathjs');
// functions and constants
math.round(math.e, 3); // 2.718
math.atan2(3, -3) / math.pi; // 0.75
math.log(1000, 10); // 3
math.sqrt(-4); // 2i
math.pow([[-1, 2], [3, 1]], 2); // [[7, 0], [0, 7]]
math.derivative('x^2 + x', 'x'); // 2 * x + 1
// expressions
math.eval('12 / (2.3 + 0.7)'); // 4
...
function atanh(x) { return new this(x).atanh(); }
...
},
'Complex': function (x) {
return x.acoth();
},
'BigNumber': function (x) {
return new type.BigNumber(1).div(x).atanh();
},
'Array | Matrix': function (x) {
return deepMap(x, acoth);
}
});
...
function cbrt(x) { return new this(x).cbrt(); }
...
/**
* Calculate the cubic root of a value.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.cbrt(x)
* math.cbrt(x, allRoots)
*
* Examples:
*
* math.cbrt(27); // returns 3
* math.cube(3); // returns 27
* math.cbrt(-64); // returns -4
...
function ceil(x) { return finalise(x = new this(x), x.e + 1, 2); }
...
/**
* Round a value towards plus infinity
* If `x` is complex, both real and imaginary part are rounded towards plus infinity.
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.ceil(x)
*
* Examples:
*
* math.ceil(3.2); // returns number 4
* math.ceil(3.8); // returns number 4
* math.ceil(-4.2); // returns number -4
* math.ceil(-4.7); // returns number -4
...
function clone(obj) { var i, p, ps; /* * The Decimal constructor and exported function. * Return a new Decimal instance. * * v {number|string|Decimal} A numeric value. * */ function Decimal(v) { var e, i, t, x = this; // Decimal called without new. if (!(x instanceof Decimal)) return new Decimal(v); // Retain a reference to this Decimal constructor, and shadow Decimal.prototype.constructor // which points to Object. x.constructor = Decimal; // Duplicate. if (v instanceof Decimal) { x.s = v.s; x.e = v.e; x.d = (v = v.d) ? v.slice() : v; return; } t = typeof v; if (t === 'number') { if (v === 0) { x.s = 1 / v < 0 ? -1 : 1; x.e = 0; x.d = [0]; return; } if (v < 0) { v = -v; x.s = -1; } else { x.s = 1; } // Fast path for small integers. if (v === ~~v && v < 1e7) { for (e = 0, i = v; i >= 10; i /= 10) e++; x.e = e; x.d = [v]; return; // Infinity, NaN. } else if (v * 0 !== 0) { if (!v) x.s = NaN; x.e = NaN; x.d = null; return; } return parseDecimal(x, v.toString()); } else if (t !== 'string') { throw Error(invalidArgument + v); } // Minus sign? if (v.charCodeAt(0) === 45) { v = v.slice(1); x.s = -1; } else { x.s = 1; } return isDecimal.test(v) ? parseDecimal(x, v) : parseOther(x, v); } Decimal.prototype = P; Decimal.ROUND_UP = 0; Decimal.ROUND_DOWN = 1; Decimal.ROUND_CEIL = 2; Decimal.ROUND_FLOOR = 3; Decimal.ROUND_HALF_UP = 4; Decimal.ROUND_HALF_DOWN = 5; Decimal.ROUND_HALF_EVEN = 6; Decimal.ROUND_HALF_CEIL = 7; Decimal.ROUND_HALF_FLOOR = 8; Decimal.EUCLID = 9; Decimal.config = Decimal.set = config; Decimal.clone = clone; Decimal.abs = abs; Decimal.acos = acos; Decimal.acosh = acosh; // ES6 Decimal.add = add; Decimal.asin = asin; Decimal.asinh = asinh; // ES6 Decimal.atan = atan; Decimal.atanh = atanh; // ES6 Decimal.atan2 = atan2; Decimal.cbrt = cbrt; // ES6 Decimal.ceil = ceil; Decimal.cos = cos; Decimal.cosh = cosh; // ES6 Decimal.div = div; Decimal.exp = exp; Decimal.floor = floor; Decimal.hypot = hypot; // ES6 Decimal.ln = ln; Decimal.log = log; Decimal.log10 = log10; // ES6 Decimal.log2 = log2; // ES6 Decimal.max = max; Decimal.min = min; Decimal.mod = mod; Decimal.mul = mul; Decimal.pow = pow; Decimal.random = random; Decimal.round = round; Decimal.sign = sign; // ES6 Decimal.sin = sin; Decimal.sinh = sinh; // ES6 Decimal.sqrt = sqrt; Decimal.sub = sub; Decimal.tan = tan; Decimal.tanh = tanh; // ES6 Decimal.trunc = trunc; // ES6 if (obj === void 0) obj = {}; if (obj) { ps = ['precision', 'rounding', 'toExpNeg', 'toExpPos', 'maxE', 'minE', 'modulo', 'crypto']; for (i = 0; i < ps.length;) if (!obj.hasOwnProperty(p = ps[i++])) obj[p] = this[p]; } Decimal.config(obj); return Decimal; }
...
return desc;
};
/**
* Export the help object to JSON
*/
Help.prototype.toJSON = function () {
var obj = object.clone(this.doc);
obj.mathjs = 'Help';
return obj;
};
/**
* Instantiate a Help object from a JSON object
* @param {Object} json
...
function config(obj) { if (!obj || typeof obj !== 'object') throw Error(decimalError + 'Object expected'); var i, p, v, ps = [ 'precision', 1, MAX_DIGITS, 'rounding', 0, 8, 'toExpNeg', -EXP_LIMIT, 0, 'toExpPos', 0, EXP_LIMIT, 'maxE', 0, EXP_LIMIT, 'minE', -EXP_LIMIT, 0, 'modulo', 0, 9 ]; for (i = 0; i < ps.length; i += 3) { if ((v = obj[p = ps[i]]) !== void 0) { if (mathfloor(v) === v && v >= ps[i + 1] && v <= ps[i + 2]) this[p] = v; else throw Error(invalidArgument + p + ': ' + v); } } if ((v = obj[p = 'crypto']) !== void 0) { if (v === true || v === false || v === 0 || v === 1) { if (v) { if (typeof crypto != 'undefined' && crypto && (crypto.getRandomValues || crypto.randomBytes)) { this[p] = true; } else { throw Error(cryptoUnavailable); } } else { this[p] = false; } } else { throw Error(invalidArgument + p + ': ' + v); } } return this; }
...
/**
* Set configuration options for math.js, and get current options.
* Will emit a 'config' event, with arguments (curr, prev, changes).
*
* Syntax:
*
* math.config(config: Object): Object
*
* Examples:
*
* math.config().number; // outputs 'number'
* math.eval('0.4'); // outputs number 0.4
* math.config({number: 'Fraction'});
* math.eval('0.4'); // outputs Fraction 2/5
...
function cos(x) { return new this(x).cos(); }
...
var u1, u2,
picked = -1;
// We reject values outside of the interval [0, 1]
// TODO: check if it is ok to do that?
while (picked < 0 || picked > 1) {
u1 = rng();
u2 = rng();
picked = 1/6 * Math.pow(-2 * Math.log(u1), 0.5) * Math.cos(2 * Math.PI * u2) +
0.5;
}
return picked;
}
}
};
distribution.toTex = undefined; // use default template
...
function cosh(x) { return new this(x).cosh(); }
...
* Calculate the hyperbolic cosine of a value,
* defined as `cosh(x) = 1/2 * (exp(x) + exp(-x))`.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.cosh(x)
*
* Examples:
*
* math.cosh(0.5); // returns number 1.1276259652063807
*
* See also:
*
...
function div(x, y) { return new this(x).div(y); }
...
setLazyConstant(math, 'e', function () {return bigConstants.e(type.BigNumber)});
setLazyConstant(math, 'phi', function () {return bigConstants.phi(type.BigNumber)}); // golden ratio, (1+sqrt(5))/2
// uppercase constants (for compatibility with built-in Math)
setLazyConstant(math, 'E', function () {return math.e;});
setLazyConstant(math, 'LN2', function () {return new type.BigNumber(2).ln();});
setLazyConstant(math, 'LN10', function () {return new type.BigNumber(10).ln()});
setLazyConstant(math, 'LOG2E', function () {return new type.BigNumber(1).div
span>(new type.BigNumber(2).ln());});
setLazyConstant(math, 'LOG10E', function () {return new type.BigNumber(1).div(new type.BigNumber(10).ln())});
setLazyConstant(math, 'PI', function () {return math.pi});
setLazyConstant(math, 'SQRT1_2', function () {return new type.BigNumber('0.5').sqrt()});
setLazyConstant(math, 'SQRT2', function () {return new type.BigNumber(2).sqrt()});
}
else {
setConstant(math, 'Infinity', Infinity);
...
function exp(x) { return new this(x).exp(); }
...
// https://www.wikiwand.com/en/Cube_root#/Complex_numbers
var arg_3 = x.arg() / 3;
var abs = x.abs();
// principal root:
var principal = new type.Complex(_cbrtNumber(abs), 0).mul(
new type.Complex(0, arg_3).exp());
if (allRoots) {
var all = [
principal,
new type.Complex(_cbrtNumber(abs), 0).mul(
new type.Complex(0, arg_3 + Math.PI * 2 / 3).exp()),
new type.Complex(_cbrtNumber(abs), 0).mul(
...
function floor(x) { return finalise(x = new this(x), x.e + 1, 3); }
...
* ceil, floor, round
*
* @param {number | BigNumber | Fraction | Complex | Array | Matrix} x Number to be rounded
* @return {number | BigNumber | Fraction | Complex | Array | Matrix} Rounded value
*/
var fix = typed('fix', {
'number': function (x) {
return (x > 0) ? Math.floor(x) : Math.ceil(x);
},
'Complex': function (x) {
return new type.Complex(
(x.re > 0) ? Math.floor(x.re) : Math.ceil(x.re),
(x.im > 0) ? Math.floor(x.im) : Math.ceil(x.im)
);
...
fromJSON = function (json) { return new BigNumber(json.value); }
...
* @param {string} key
* @param {*} value
* @returns {*} Returns the revived object
*/
return function reviver(key, value) {
var constructor = type[value && value.mathjs];
if (constructor && typeof constructor.fromJSON === 'function') {
return constructor.fromJSON(value);
}
return value;
}
}
exports.name = 'reviver';
...
function hypot() { var i, n, t = new this(0); external = false; for (i = 0; i < arguments.length;) { n = new this(arguments[i++]); if (!n.d) { if (n.s) { external = true; return new this(1 / 0); } t = n; } else if (t.d) { t = t.plus(n.times(n)); } } external = true; return t.sqrt(); }
...
*
* hypot(a, b, c, ...) = sqrt(a^2 + b^2 + c^2 + ...)
*
* For matrix input, the hypotenusa is calculated for all values in the matrix.
*
* Syntax:
*
* math.hypot(a, b, ...)
* math.hypot([a, b, c, ...])
*
* Examples:
*
* math.hypot(3, 4); // 5
* math.hypot(3, 4, 5); // 7.0710678118654755
* math.hypot([3, 4, 5]); // 7.0710678118654755
...
function ln(x) { return new this(x).ln(); }
...
setLazyConstant(math, 'pi', function () {return bigConstants.pi(type.BigNumber)});
setLazyConstant(math, 'tau', function () {return bigConstants.tau(type.BigNumber)});
setLazyConstant(math, 'e', function () {return bigConstants.e(type.BigNumber)});
setLazyConstant(math, 'phi', function () {return bigConstants.phi(type.BigNumber)}); // golden ratio, (1+sqrt(5))/2
// uppercase constants (for compatibility with built-in Math)
setLazyConstant(math, 'E', function () {return math.e;});
setLazyConstant(math, 'LN2', function () {return new type.BigNumber(2).ln();});
setLazyConstant(math, 'LN10', function () {return new type.BigNumber(10).ln()});
setLazyConstant(math, 'LOG2E', function () {return new type.BigNumber(1).div(new type.BigNumber(2).ln());});
setLazyConstant(math, 'LOG10E', function () {return new type.BigNumber(1).div(new type.BigNumber(10).ln())});
setLazyConstant(math, 'PI', function () {return math.pi});
setLazyConstant(math, 'SQRT1_2', function () {return new type.BigNumber('0.5').sqrt()});
setLazyConstant(math, 'SQRT2', function () {return new type.BigNumber(2).sqrt()});
}
...
function log(x, y) { return new this(x).log(y); }
...
```js
// load math.js
var math = require('mathjs');
// functions and constants
math.round(math.e, 3); // 2.718
math.atan2(3, -3) / math.pi; // 0.75
math.log(1000, 10); // 3
math.sqrt(-4); // 2i
math.pow([[-1, 2], [3, 1]], 2); // [[7, 0], [0, 7]]
math.derivative('x^2 + x', 'x'); // 2 * x + 1
// expressions
math.eval('12 / (2.3 + 0.7)'); // 4
math.eval('5.08 cm to inch'); // 2 inch
...
function log10(x) { return new this(x).log(10); }
...
/**
* Calculate the 10-base logarithm of a value. This is the same as calculating `log(x, 10)`.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.log10(x)
*
* Examples:
*
* math.log10(0.00001); // returns -5
* math.log10(10000); // returns 4
* math.log(10000) / math.log(10); // returns 4
* math.pow(10, 4); // returns 10000
...
function log2(x) { return new this(x).log(2); }
n/a
function max() { return maxOrMin(this, arguments, 'lt'); }
...
* @return {number} Returns the maximum number of expected arguments.
* Returns -1 when no signatures where found on the function.
*/
exports.maxArgumentCount = function (fn) {
return Object.keys(fn.signatures || {})
.reduce(function (args, signature) {
var count = (signature.match(/,/g) || []).length + 1;
return Math.max(args, count);
}, -1);
};
...
function min() { return maxOrMin(this, arguments, 'gt'); }
...
* @private
*/
function _resize (array, size, dim, defaultValue) {
var i;
var elem;
var oldLen = array.length;
var newLen = size[dim];
var minLen = Math.min(oldLen, newLen);
// apply new length
array.length = newLen;
if (dim < size.length - 1) {
// non-last dimension
var dimNext = dim + 1;
...
function mod(x, y) { return new this(x).mod(y); }
...
if (!a.isInt() || !b.isInt()) {
throw new Error('Parameters in function gcd must be integer numbers');
}
// http://en.wikipedia.org/wiki/Euclidean_algorithm
var zero = new type.BigNumber(0);
while (!b.isZero()) {
var r = a.mod(b);
a = b;
b = r;
}
return a.lt(zero) ? a.neg() : a;
}
}
...
function mul(x, y) { return new this(x).mul(y); }
...
function _cbrtComplex(x, allRoots) {
// https://www.wikiwand.com/en/Cube_root#/Complex_numbers
var arg_3 = x.arg() / 3;
var abs = x.abs();
// principal root:
var principal = new type.Complex(_cbrtNumber(abs), 0).mul(
new type.Complex(0, arg_3).exp());
if (allRoots) {
var all = [
principal,
new type.Complex(_cbrtNumber(abs), 0).mul(
new type.Complex(0, arg_3 + Math.PI * 2 / 3).exp()),
...
function pow(x, y) { return new this(x).pow(y); }
...
var math = require('mathjs');
// functions and constants
math.round(math.e, 3); // 2.718
math.atan2(3, -3) / math.pi; // 0.75
math.log(1000, 10); // 3
math.sqrt(-4); // 2i
math.pow([[-1, 2], [3, 1]], 2); // [[7, 0], [0, 7]]
math.derivative('x^2 + x', 'x'); // 2 * x + 1
// expressions
math.eval('12 / (2.3 + 0.7)'); // 4
math.eval('5.08 cm to inch'); // 2 inch
math.eval('sin(45 deg) ^ 2'); // 0.5
math.eval('9 / 3 + 2i'); // 3 + 2i
...
function random(sd) { var d, e, k, n, i = 0, r = new this(1), rd = []; if (sd === void 0) sd = this.precision; else checkInt32(sd, 1, MAX_DIGITS); k = Math.ceil(sd / LOG_BASE); if (!this.crypto) { for (; i < k;) rd[i++] = Math.random() * 1e7 | 0; // Browsers supporting crypto.getRandomValues. } else if (crypto.getRandomValues) { d = crypto.getRandomValues(new Uint32Array(k)); for (; i < k;) { n = d[i]; // 0 <= n < 4294967296 // Probability n >= 4.29e9, is 4967296 / 4294967296 = 0.00116 (1 in 865). if (n >= 4.29e9) { d[i] = crypto.getRandomValues(new Uint32Array(1))[0]; } else { // 0 <= n <= 4289999999 // 0 <= (n % 1e7) <= 9999999 rd[i++] = n % 1e7; } } // Node.js supporting crypto.randomBytes. } else if (crypto.randomBytes) { // buffer d = crypto.randomBytes(k *= 4); for (; i < k;) { // 0 <= n < 2147483648 n = d[i] + (d[i + 1] << 8) + (d[i + 2] << 16) + ((d[i + 3] & 0x7f) << 24); // Probability n >= 2.14e9, is 7483648 / 2147483648 = 0.0035 (1 in 286). if (n >= 2.14e9) { crypto.randomBytes(4).copy(d, i); } else { // 0 <= n <= 2139999999 // 0 <= (n % 1e7) <= 9999999 rd.push(n % 1e7); i += 4; } } i = k / 4; } else { throw Error(cryptoUnavailable); } k = rd[--i]; sd %= LOG_BASE; // Convert trailing digits to zeros according to sd. if (k && sd) { n = mathpow(10, LOG_BASE - sd); rd[i] = (k / n | 0) * n; } // Remove trailing words which are zero. for (; rd[i] === 0; i--) rd.pop(); // Zero? if (i < 0) { e = 0; rd = [0]; } else { e = -1; // Remove leading words which are zero and adjust exponent accordingly. for (; rd[0] === 0; e -= LOG_BASE) rd.shift(); // Count the digits of the first word of rd to determine leading zeros. for (k = 1, n = rd[0]; n >= 10; n /= 10) k++; // Adjust the exponent for leading zeros of the first word of rd. if (k < LOG_BASE) e -= LOG_BASE - k; } r.e = e; r.d = rd; return r; }
...
var from = 0;
var to = arr.length - 1;
// if from == to we reached the kth element
while (from < to) {
var r = from;
var w = to;
var pivot = arr[Math.floor(Math.random() * (to - from + 1)) + from];
// stop if the reader and writer meets
while (r < w) {
// arr[r] >= pivot
if (compare(arr[r], pivot) >= 0) { // put the large values at the end
var tmp = arr[w];
arr[w] = arr[r];
...
function round(x) { return finalise(x = new this(x), x.e + 1, this.rounding); }
...
[chained operations](http://mathjs.org/docs/chained_operations.html).
```js
// load math.js
var math = require('mathjs');
// functions and constants
math.round(math.e, 3); // 2.718
math.atan2(3, -3) / math.pi; // 0.75
math.log(1000, 10); // 3
math.sqrt(-4); // 2i
math.pow([[-1, 2], [3, 1]], 2); // [[7, 0], [0, 7]]
math.derivative('x^2 + x', 'x'); // 2 * x + 1
// expressions
...
function config(obj) { if (!obj || typeof obj !== 'object') throw Error(decimalError + 'Object expected'); var i, p, v, ps = [ 'precision', 1, MAX_DIGITS, 'rounding', 0, 8, 'toExpNeg', -EXP_LIMIT, 0, 'toExpPos', 0, EXP_LIMIT, 'maxE', 0, EXP_LIMIT, 'minE', -EXP_LIMIT, 0, 'modulo', 0, 9 ]; for (i = 0; i < ps.length; i += 3) { if ((v = obj[p = ps[i]]) !== void 0) { if (mathfloor(v) === v && v >= ps[i + 1] && v <= ps[i + 2]) this[p] = v; else throw Error(invalidArgument + p + ': ' + v); } } if ((v = obj[p = 'crypto']) !== void 0) { if (v === true || v === false || v === 0 || v === 1) { if (v) { if (typeof crypto != 'undefined' && crypto && (crypto.getRandomValues || crypto.randomBytes)) { this[p] = true; } else { throw Error(cryptoUnavailable); } } else { this[p] = false; } } else { throw Error(invalidArgument + p + ': ' + v); } } return this; }
...
* keeps a scope containing variables in memory, which is used for all
* evaluations.
*
* Methods:
* var result = parser.eval(expr); // evaluate an expression
* var value = parser.get(name); // retrieve a variable from the parser
* var values = parser.getAll(); // retrieve all defined variables
* parser.set(name, value); // set a variable in the parser
* parser.remove(name); // clear a variable from the
* // parsers scope
* parser.clear(); // clear the parsers scope
*
* Example usage:
* var parser = new Parser();
* // Note: there is a convenience method which can be used instead:
...
function sign(x) { x = new this(x); return x.d ? (x.d[0] ? x.s : 0 * x.s) : x.s || NaN; }
...
* - -1 when x < 0
* - 0 when x == 0
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.sign(x)
*
* Examples:
*
* math.sign(3.5); // returns 1
* math.sign(-4.2); // returns -1
* math.sign(0); // returns 0
*
...
function sin(x) { return new this(x).sin(); }
...
res = 1; // 0! is per definition 1
}
return res;
}
if (n < 0.5) {
return Math.PI / (Math.sin(Math.PI * n) * gamma(1-n));
}
if (n >= 171.35) {
return Infinity; // will overflow
}
if (n > 85.0) { // Extended Stirling Approx
...
function sinh(x) { return new this(x).sinh(); }
...
*
* math.csch(x)
*
* Examples:
*
* // csch(x) = 1/ sinh(x)
* math.csch(0.5); // returns 1.9190347513349437
* 1 / math.sinh(0.5); // returns 1.9190347513349437
*
* See also:
*
* sinh, sech, coth
*
* @param {number | Complex | Unit | Array | Matrix} x Function input
* @return {number | Complex | Array | Matrix} Hyperbolic cosecant of x
...
function sqrt(x) { return new this(x).sqrt(); }
...
// load math.js
var math = require('mathjs');
// functions and constants
math.round(math.e, 3); // 2.718
math.atan2(3, -3) / math.pi; // 0.75
math.log(1000, 10); // 3
math.sqrt(-4); // 2i
math.pow([[-1, 2], [3, 1]], 2); // [[7, 0], [0, 7]]
math.derivative('x^2 + x', 'x'); // 2 * x + 1
// expressions
math.eval('12 / (2.3 + 0.7)'); // 4
math.eval('5.08 cm to inch'); // 2 inch
math.eval('sin(45 deg) ^ 2'); // 0.5
...
function sub(x, y) { return new this(x).sub(y); }
...
var subtract = typed('subtract', {
'number, number': function (x, y) {
return x - y;
},
'Complex, Complex': function (x, y) {
return x.sub(y);
},
'BigNumber, BigNumber': function (x, y) {
return x.minus(y);
},
'Fraction, Fraction': function (x, y) {
...
function tan(x) { return new this(x).tan(); }
...
* Syntax:
*
* math.atan(x)
*
* Examples:
*
* math.atan(0.5); // returns number 0.4636476090008061
* math.atan(math.tan(1.5)); // returns number 1.5
*
* math.atan(2); // returns Complex 1.5707963267948966 -1.3169578969248166 i
*
* See also:
*
* tan, asin, acos
*
...
function tanh(x) { return new this(x).tanh(); }
...
*
* math.coth(x)
*
* Examples:
*
* // coth(x) = 1 / tanh(x)
* math.coth(2); // returns 1.0373147207275482
* 1 / math.tanh(2); // returns 1.0373147207275482
*
* See also:
*
* sinh, tanh, cosh
*
* @param {number | Complex | Unit | Array | Matrix} x Function input
* @return {number | Complex | Array | Matrix} Hyperbolic cotangent of x
...
function trunc(x) { return finalise(x = new this(x), x.e + 1, 1); }
n/a
abs = function () { var x = new this.constructor(this); if (x.s < 0) x.s = 1; return finalise(x); }
...
function factory (type, config, load, typed) {
/**
* Calculate the absolute value of a number. For matrices, the function is
* evaluated element wise.
*
* Syntax:
*
* math.abs(x)
*
* Examples:
*
* math.abs(3.5); // returns number 3.5
* math.abs(-4.2); // returns number 4.2
*
* math.abs([3, -5, -1, 0, 2]); // returns Array [3, 5, 1, 0, 2]
...
absoluteValue = function () { var x = new this.constructor(this); if (x.s < 0) x.s = 1; return finalise(x); }
n/a
acos = function () { var halfPi, x = this, Ctor = x.constructor, k = x.abs().cmp(1), pr = Ctor.precision, rm = Ctor.rounding; if (k !== -1) { return k === 0 // |x| is 1 ? x.isNeg() ? getPi(Ctor, pr, rm) : new Ctor(0) // |x| > 1 or x is NaN : new Ctor(NaN); } if (x.isZero()) return getPi(Ctor, pr + 4, rm).times(0.5); // TODO? Special case acos(0.5) = pi/3 and acos(-0.5) = 2*pi/3 Ctor.precision = pr + 6; Ctor.rounding = 1; x = x.asin(); halfPi = getPi(Ctor, pr + 4, rm).times(0.5); Ctor.precision = pr; Ctor.rounding = rm; return halfPi.minus(x); }
...
/**
* Calculate the inverse cosine of a value.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.acos(x)
*
* Examples:
*
* math.acos(0.5); // returns number 1.0471975511965979
* math.acos(math.cos(1.5)); // returns number 1.5
*
* math.acos(2); // returns Complex 0 + 1.3169578969248166 i
...
acosh = function () { var pr, rm, x = this, Ctor = x.constructor; if (x.lte(1)) return new Ctor(x.eq(1) ? 0 : NaN); if (!x.isFinite()) return new Ctor(x); pr = Ctor.precision; rm = Ctor.rounding; Ctor.precision = pr + Math.max(Math.abs(x.e), x.sd()) + 4; Ctor.rounding = 1; external = false; x = x.times(x).minus(1).sqrt().plus(x); external = true; Ctor.precision = pr; Ctor.rounding = rm; return x.ln(); }
...
* Calculate the hyperbolic arccos of a value,
* defined as `acosh(x) = ln(sqrt(x^2 - 1) + x)`.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.acosh(x)
*
* Examples:
*
* math.acosh(1.5); // returns 0.9624236501192069
*
* See also:
*
...
add = function (y) { var carry, d, e, i, k, len, pr, rm, xd, yd, x = this, Ctor = x.constructor; y = new Ctor(y); // If either is not finite... if (!x.d || !y.d) { // Return NaN if either is NaN. if (!x.s || !y.s) y = new Ctor(NaN); // Return x if y is finite and x is ±Infinity. // Return x if both are ±Infinity with the same sign. // Return NaN if both are ±Infinity with different signs. // Return y if x is finite and y is ±Infinity. else if (!x.d) y = new Ctor(y.d || x.s === y.s ? x : NaN); return y; } // If signs differ... if (x.s != y.s) { y.s = -y.s; return x.minus(y); } xd = x.d; yd = y.d; pr = Ctor.precision; rm = Ctor.rounding; // If either is zero... if (!xd[0] || !yd[0]) { // Return x if y is zero. // Return y if y is non-zero. if (!yd[0]) y = new Ctor(x); return external ? finalise(y, pr, rm) : y; } // x and y are finite, non-zero numbers with the same sign. // Calculate base 1e7 exponents. k = mathfloor(x.e / LOG_BASE); e = mathfloor(y.e / LOG_BASE); xd = xd.slice(); i = k - e; // If base 1e7 exponents differ... if (i) { if (i < 0) { d = xd; i = -i; len = yd.length; } else { d = yd; e = k; len = xd.length; } // Limit number of zeros prepended to max(ceil(pr / LOG_BASE), len) + 1. k = Math.ceil(pr / LOG_BASE); len = k > len ? k + 1 : len + 1; if (i > len) { i = len; d.length = 1; } // Prepend zeros to equalise exponents. Note: Faster to use reverse then do unshifts. d.reverse(); for (; i--;) d.push(0); d.reverse(); } len = xd.length; i = yd.length; // If yd is longer than xd, swap xd and yd so xd points to the longer array. if (len - i < 0) { i = len; d = yd; yd = xd; xd = d; } // Only start adding at yd.length - 1 as the further digits of xd can be left as they are. for (carry = 0; i;) { carry = (xd[--i] = xd[i] + yd[i] + carry) / BASE | 0; xd[i] %= BASE; } if (carry) { xd.unshift(carry); ++e; } // Remove trailing zeros. // No need to check for zero, as +x + +y != 0 && -x + -y != 0 for (len = xd.length; xd[--len] == 0;) xd.pop(); y.d = xd; y.e = getBase10Exponent(xd, e); return external ? finalise(y, pr, rm) : y; }
...
math.eval('5.08 cm to inch'); // 2 inch
math.eval('sin(45 deg) ^ 2'); // 0.5
math.eval('9 / 3 + 2i'); // 3 + 2i
math.eval('det([-1, 2; 3, 1])'); // -7
// chaining
math.chain(3)
.add(4)
.multiply(2)
.done(); // 14
```
## Browser support
Math.js works on any ES5 compatible JavaScript engine: node.js 0.10, and Internet Explorer 9 and newer, and all other browsers (
Chrome, Firefox, Safari). If support for old browsers like Internet Explorer 8 is required, the [es5-shim](https://github.com/kriskowal
/es5-shim) library has to be loaded.
...
asin = function () { var halfPi, k, pr, rm, x = this, Ctor = x.constructor; if (x.isZero()) return new Ctor(x); k = x.abs().cmp(1); pr = Ctor.precision; rm = Ctor.rounding; if (k !== -1) { // |x| is 1 if (k === 0) { halfPi = getPi(Ctor, pr + 4, rm).times(0.5); halfPi.s = x.s; return halfPi; } // |x| > 1 or x is NaN return new Ctor(NaN); } // TODO? Special case asin(1/2) = pi/6 and asin(-1/2) = -pi/6 Ctor.precision = pr + 6; Ctor.rounding = 1; x = x.div(new Ctor(1).minus(x.times(x)).sqrt().plus(1)).atan(); Ctor.precision = pr; Ctor.rounding = rm; return x.times(2); }
...
*
* @param {number | Complex | Array | Matrix} x Function input
* @return {number | Complex | Array | Matrix} The arc cosecant of x
*/
var acsc = typed('acsc', {
'number': function (x) {
if (x <= -1 || x >= 1 || config.predictable) {
return Math.asin(1 / x);
}
return new type.Complex(x, 0).acsc();
},
'Complex': function (x) {
return x.acsc();
},
...
asinh = function () { var pr, rm, x = this, Ctor = x.constructor; if (!x.isFinite() || x.isZero()) return new Ctor(x); pr = Ctor.precision; rm = Ctor.rounding; Ctor.precision = pr + 2 * Math.max(Math.abs(x.e), x.sd()) + 6; Ctor.rounding = 1; external = false; x = x.times(x).plus(1).sqrt().plus(x); external = true; Ctor.precision = pr; Ctor.rounding = rm; return x.ln(); }
...
},
'Complex': function (x) {
return x.acsch();
},
'BigNumber': function (x) {
return new type.BigNumber(1).div(x).asinh();
},
'Array | Matrix': function (x) {
return deepMap(x, acsch);
}
});
...
atan = function () { var i, j, k, n, px, t, r, wpr, x2, x = this, Ctor = x.constructor, pr = Ctor.precision, rm = Ctor.rounding; if (!x.isFinite()) { if (!x.s) return new Ctor(NaN); if (pr + 4 <= PI_PRECISION) { r = getPi(Ctor, pr + 4, rm).times(0.5); r.s = x.s; return r; } } else if (x.isZero()) { return new Ctor(x); } else if (x.abs().eq(1) && pr + 4 <= PI_PRECISION) { r = getPi(Ctor, pr + 4, rm).times(0.25); r.s = x.s; return r; } Ctor.precision = wpr = pr + 10; Ctor.rounding = 1; // TODO? if (x >= 1 && pr <= PI_PRECISION) atan(x) = halfPi * x.s - atan(1 / x); // Argument reduction // Ensure |x| < 0.42 // atan(x) = 2 * atan(x / (1 + sqrt(1 + x^2))) k = Math.min(28, wpr / LOG_BASE + 2 | 0); for (i = k; i; --i) x = x.div(x.times(x).plus(1).sqrt().plus(1)); external = false; j = Math.ceil(wpr / LOG_BASE); n = 1; x2 = x.times(x); r = new Ctor(x); px = x; // atan(x) = x - x^3/3 + x^5/5 - x^7/7 + ... for (; i !== -1;) { px = px.times(x2); t = r.minus(px.div(n += 2)); px = px.times(x2); r = t.plus(px.div(n += 2)); if (r.d[j] !== void 0) for (i = j; r.d[i] === t.d[i] && i--;); } if (k) r = r.times(2 << (k - 1)); external = true; return finalise(r, Ctor.precision = pr, Ctor.rounding = rm, true); }
...
* cot, atan
*
* @param {number | Complex | Array | Matrix} x Function input
* @return {number | Complex | Array | Matrix} The arc cotangent of x
*/
var acot = typed('acot', {
'number': function (x) {
return Math.atan(1 / x);
},
'Complex': function (x) {
return x.acot();
},
'BigNumber': function (x) {
...
atanh = function () { var pr, rm, wpr, xsd, x = this, Ctor = x.constructor; if (!x.isFinite()) return new Ctor(NaN); if (x.e >= 0) return new Ctor(x.abs().eq(1) ? x.s / 0 : x.isZero() ? x : NaN); pr = Ctor.precision; rm = Ctor.rounding; xsd = x.sd(); if (Math.max(xsd, pr) < 2 * -x.e - 1) return finalise(new Ctor(x), pr, rm, true); Ctor.precision = wpr = xsd - x.e; x = divide(x.plus(1), new Ctor(1).minus(x), wpr + pr, 1); Ctor.precision = pr + 4; Ctor.rounding = 1; x = x.ln(); Ctor.precision = pr; Ctor.rounding = rm; return x.times(0.5); }
...
},
'Complex': function (x) {
return x.acoth();
},
'BigNumber': function (x) {
return new type.BigNumber(1).div(x).atanh();
},
'Array | Matrix': function (x) {
return deepMap(x, acoth);
}
});
...
cbrt = function () { var e, m, n, r, rep, s, sd, t, t3, t3plusx, x = this, Ctor = x.constructor; if (!x.isFinite() || x.isZero()) return new Ctor(x); external = false; // Initial estimate. s = x.s * Math.pow(x.s * x, 1 / 3); // Math.cbrt underflow/overflow? // Pass x to Math.pow as integer, then adjust the exponent of the result. if (!s || Math.abs(s) == 1 / 0) { n = digitsToString(x.d); e = x.e; // Adjust n exponent so it is a multiple of 3 away from x exponent. if (s = (e - n.length + 1) % 3) n += (s == 1 || s == -2 ? '0' : '00'); s = Math.pow(n, 1 / 3); // Rarely, e may be one less than the result exponent value. e = mathfloor((e + 1) / 3) - (e % 3 == (e < 0 ? -1 : 2)); if (s == 1 / 0) { n = '5e' + e; } else { n = s.toExponential(); n = n.slice(0, n.indexOf('e') + 1) + e; } r = new Ctor(n); r.s = x.s; } else { r = new Ctor(s.toString()); } sd = (e = Ctor.precision) + 3; // Halley's method. // TODO? Compare Newton's method. for (;;) { t = r; t3 = t.times(t).times(t); t3plusx = t3.plus(x); r = divide(t3plusx.plus(x).times(t), t3plusx.plus(t3), sd + 2, 1); // TODO? Replace with for-loop and checkRoundingDigits. if (digitsToString(t.d).slice(0, sd) === (n = digitsToString(r.d)).slice(0, sd)) { n = n.slice(sd - 3, sd + 1); // The 4th rounding digit may be in error by -1 so if the 4 rounding digits are 9999 or 4999 // , i.e. approaching a rounding boundary, continue the iteration. if (n == '9999' || !rep && n == '4999') { // On the first iteration only, check to see if rounding up gives the exact result as the // nines may infinitely repeat. if (!rep) { finalise(t, e + 1, 0); if (t.times(t).times(t).eq(x)) { r = t; break; } } sd += 4; rep = 1; } else { // If the rounding digits are null, 0{0,4} or 50{0,3}, check for an exact result. // If not, then there are further digits and m will be truthy. if (!+n || !+n.slice(1) && n.charAt(0) == '5') { // Truncate to the first rounding digit. finalise(r, e + 1, 1); m = !r.times(r).times(r).eq(x); } break; } } } external = true; return finalise(r, e, Ctor.rounding, m); }
...
/**
* Calculate the cubic root of a value.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.cbrt(x)
* math.cbrt(x, allRoots)
*
* Examples:
*
* math.cbrt(27); // returns 3
* math.cube(3); // returns 27
* math.cbrt(-64); // returns -4
...
ceil = function () { return finalise(new this.constructor(this), this.e + 1, 2); }
...
/**
* Round a value towards plus infinity
* If `x` is complex, both real and imaginary part are rounded towards plus infinity.
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.ceil(x)
*
* Examples:
*
* math.ceil(3.2); // returns number 4
* math.ceil(3.8); // returns number 4
* math.ceil(-4.2); // returns number -4
* math.ceil(-4.7); // returns number -4
...
cmp = function (y) { var i, j, xdL, ydL, x = this, xd = x.d, yd = (y = new x.constructor(y)).d, xs = x.s, ys = y.s; // Either NaN or ±Infinity? if (!xd || !yd) { return !xs || !ys ? NaN : xs !== ys ? xs : xd === yd ? 0 : !xd ^ xs < 0 ? 1 : -1; } // Either zero? if (!xd[0] || !yd[0]) return xd[0] ? xs : yd[0] ? -ys : 0; // Signs differ? if (xs !== ys) return xs; // Compare exponents. if (x.e !== y.e) return x.e > y.e ^ xs < 0 ? 1 : -1; xdL = xd.length; ydL = yd.length; // Compare digit by digit. for (i = 0, j = xdL < ydL ? xdL : ydL; i < j; ++i) { if (xd[i] !== yd[i]) return xd[i] > yd[i] ^ xs < 0 ? 1 : -1; } // Compare lengths. return xdL === ydL ? 0 : xdL > ydL ^ xs < 0 ? 1 : -1; }
...
'number': number.sign,
'Complex': function (x) {
return x.sign();
},
'BigNumber': function (x) {
return new type.BigNumber(x.cmp(0));
},
'Fraction': function (x) {
return new type.Fraction(x.s, 1);
},
'Array | Matrix': function (x) {
...
comparedTo = function (y) { var i, j, xdL, ydL, x = this, xd = x.d, yd = (y = new x.constructor(y)).d, xs = x.s, ys = y.s; // Either NaN or ±Infinity? if (!xd || !yd) { return !xs || !ys ? NaN : xs !== ys ? xs : xd === yd ? 0 : !xd ^ xs < 0 ? 1 : -1; } // Either zero? if (!xd[0] || !yd[0]) return xd[0] ? xs : yd[0] ? -ys : 0; // Signs differ? if (xs !== ys) return xs; // Compare exponents. if (x.e !== y.e) return x.e > y.e ^ xs < 0 ? 1 : -1; xdL = xd.length; ydL = yd.length; // Compare digit by digit. for (i = 0, j = xdL < ydL ? xdL : ydL; i < j; ++i) { if (xd[i] !== yd[i]) return xd[i] > yd[i] ^ xs < 0 ? 1 : -1; } // Compare lengths. return xdL === ydL ? 0 : xdL > ydL ^ xs < 0 ? 1 : -1; }
n/a
cos = function () { var pr, rm, x = this, Ctor = x.constructor; if (!x.d) return new Ctor(NaN); // cos(0) = cos(-0) = 1 if (!x.d[0]) return new Ctor(1); pr = Ctor.precision; rm = Ctor.rounding; Ctor.precision = pr + Math.max(x.e, x.sd()) + LOG_BASE; Ctor.rounding = 1; x = cosine(Ctor, toLessThanHalfPi(Ctor, x)); Ctor.precision = pr; Ctor.rounding = rm; return finalise(quadrant == 2 || quadrant == 3 ? x.neg() : x, pr, rm, true); }
...
var u1, u2,
picked = -1;
// We reject values outside of the interval [0, 1]
// TODO: check if it is ok to do that?
while (picked < 0 || picked > 1) {
u1 = rng();
u2 = rng();
picked = 1/6 * Math.pow(-2 * Math.log(u1), 0.5) * Math.cos(2 * Math.PI * u2) +
0.5;
}
return picked;
}
}
};
distribution.toTex = undefined; // use default template
...
cosh = function () { var k, n, pr, rm, len, x = this, Ctor = x.constructor, one = new Ctor(1); if (!x.isFinite()) return new Ctor(x.s ? 1 / 0 : NaN); if (x.isZero()) return one; pr = Ctor.precision; rm = Ctor.rounding; Ctor.precision = pr + Math.max(x.e, x.sd()) + 4; Ctor.rounding = 1; len = x.d.length; // Argument reduction: cos(4x) = 1 - 8cos^2(x) + 8cos^4(x) + 1 // i.e. cos(x) = 1 - cos^2(x/4)(8 - 8cos^2(x/4)) // Estimate the optimum number of times to use the argument reduction. // TODO? Estimation reused from cosine() and may not be optimal here. if (len < 32) { k = Math.ceil(len / 3); n = Math.pow(4, -k).toString(); } else { k = 16; n = '2.3283064365386962890625e-10'; } x = taylorSeries(Ctor, 1, x.times(n), new Ctor(1), true); // Reverse argument reduction var cosh2_x, i = k, d8 = new Ctor(8); for (; i--;) { cosh2_x = x.times(x); x = one.minus(cosh2_x.times(d8.minus(cosh2_x.times(d8)))); } return finalise(x, Ctor.precision = pr, Ctor.rounding = rm, true); }
...
* Calculate the hyperbolic cosine of a value,
* defined as `cosh(x) = 1/2 * (exp(x) + exp(-x))`.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.cosh(x)
*
* Examples:
*
* math.cosh(0.5); // returns number 1.1276259652063807
*
* See also:
*
...
cosine = function () { var pr, rm, x = this, Ctor = x.constructor; if (!x.d) return new Ctor(NaN); // cos(0) = cos(-0) = 1 if (!x.d[0]) return new Ctor(1); pr = Ctor.precision; rm = Ctor.rounding; Ctor.precision = pr + Math.max(x.e, x.sd()) + LOG_BASE; Ctor.rounding = 1; x = cosine(Ctor, toLessThanHalfPi(Ctor, x)); Ctor.precision = pr; Ctor.rounding = rm; return finalise(quadrant == 2 || quadrant == 3 ? x.neg() : x, pr, rm, true); }
n/a
cubeRoot = function () { var e, m, n, r, rep, s, sd, t, t3, t3plusx, x = this, Ctor = x.constructor; if (!x.isFinite() || x.isZero()) return new Ctor(x); external = false; // Initial estimate. s = x.s * Math.pow(x.s * x, 1 / 3); // Math.cbrt underflow/overflow? // Pass x to Math.pow as integer, then adjust the exponent of the result. if (!s || Math.abs(s) == 1 / 0) { n = digitsToString(x.d); e = x.e; // Adjust n exponent so it is a multiple of 3 away from x exponent. if (s = (e - n.length + 1) % 3) n += (s == 1 || s == -2 ? '0' : '00'); s = Math.pow(n, 1 / 3); // Rarely, e may be one less than the result exponent value. e = mathfloor((e + 1) / 3) - (e % 3 == (e < 0 ? -1 : 2)); if (s == 1 / 0) { n = '5e' + e; } else { n = s.toExponential(); n = n.slice(0, n.indexOf('e') + 1) + e; } r = new Ctor(n); r.s = x.s; } else { r = new Ctor(s.toString()); } sd = (e = Ctor.precision) + 3; // Halley's method. // TODO? Compare Newton's method. for (;;) { t = r; t3 = t.times(t).times(t); t3plusx = t3.plus(x); r = divide(t3plusx.plus(x).times(t), t3plusx.plus(t3), sd + 2, 1); // TODO? Replace with for-loop and checkRoundingDigits. if (digitsToString(t.d).slice(0, sd) === (n = digitsToString(r.d)).slice(0, sd)) { n = n.slice(sd - 3, sd + 1); // The 4th rounding digit may be in error by -1 so if the 4 rounding digits are 9999 or 4999 // , i.e. approaching a rounding boundary, continue the iteration. if (n == '9999' || !rep && n == '4999') { // On the first iteration only, check to see if rounding up gives the exact result as the // nines may infinitely repeat. if (!rep) { finalise(t, e + 1, 0); if (t.times(t).times(t).eq(x)) { r = t; break; } } sd += 4; rep = 1; } else { // If the rounding digits are null, 0{0,4} or 50{0,3}, check for an exact result. // If not, then there are further digits and m will be truthy. if (!+n || !+n.slice(1) && n.charAt(0) == '5') { // Truncate to the first rounding digit. finalise(r, e + 1, 1); m = !r.times(r).times(r).eq(x); } break; } } } external = true; return finalise(r, e, Ctor.rounding, m); }
n/a
decimalPlaces = function () { var w, d = this.d, n = NaN; if (d) { w = d.length - 1; n = (w - mathfloor(this.e / LOG_BASE)) * LOG_BASE; // Subtract the number of trailing zeros of the last word. w = d[w]; if (w) for (; w % 10 == 0; w /= 10) n--; if (n < 0) n = 0; } return n; }
n/a
div = function (y) { return divide(this, new this.constructor(y)); }
...
setLazyConstant(math, 'e', function () {return bigConstants.e(type.BigNumber)});
setLazyConstant(math, 'phi', function () {return bigConstants.phi(type.BigNumber)}); // golden ratio, (1+sqrt(5))/2
// uppercase constants (for compatibility with built-in Math)
setLazyConstant(math, 'E', function () {return math.e;});
setLazyConstant(math, 'LN2', function () {return new type.BigNumber(2).ln();});
setLazyConstant(math, 'LN10', function () {return new type.BigNumber(10).ln()});
setLazyConstant(math, 'LOG2E', function () {return new type.BigNumber(1).div
span>(new type.BigNumber(2).ln());});
setLazyConstant(math, 'LOG10E', function () {return new type.BigNumber(1).div(new type.BigNumber(10).ln())});
setLazyConstant(math, 'PI', function () {return math.pi});
setLazyConstant(math, 'SQRT1_2', function () {return new type.BigNumber('0.5').sqrt()});
setLazyConstant(math, 'SQRT2', function () {return new type.BigNumber(2).sqrt()});
}
else {
setConstant(math, 'Infinity', Infinity);
...
divToInt = function (y) { var x = this, Ctor = x.constructor; return finalise(divide(x, new Ctor(y), 0, 1, 1), Ctor.precision, Ctor.rounding); }
n/a
dividedBy = function (y) { return divide(this, new this.constructor(y)); }
...
throw new TypeError('k must be less than n in function combinations');
}
max = n.minus(k);
if (k.lt(max)) max = k;
result = one;
for (i = one, ii = n.minus(max); i.lte(ii); i = i.plus(1)) {
result = result.times(max.plus(i)).dividedBy(i);
}
return result;
}
// TODO: implement support for collection in combinations
});
...
dividedToIntegerBy = function (y) { var x = this, Ctor = x.constructor; return finalise(divide(x, new Ctor(y), 0, 1, 1), Ctor.precision, Ctor.rounding); }
n/a
dp = function () { var w, d = this.d, n = NaN; if (d) { w = d.length - 1; n = (w - mathfloor(this.e / LOG_BASE)) * LOG_BASE; // Subtract the number of trailing zeros of the last word. w = d[w]; if (w) for (; w % 10 == 0; w /= 10) n--; if (n < 0) n = 0; } return n; }
n/a
eq = function (y) { return this.cmp(y) === 0; }
...
'number, number': function (x, y) {
return (x === y || nearlyEqual(x, y, config.epsilon))
? 0
: (x > y ? 1 : -1);
},
'BigNumber, BigNumber': function (x, y) {
return (x.eq(y) || bigNearlyEqual(x, y, config.epsilon))
? new type.BigNumber(0)
: new type.BigNumber(x.cmp(y));
},
'Fraction, Fraction': function (x, y) {
return new type.Fraction(x.compare(y));
},
...
equals = function (y) { return this.cmp(y) === 0; }
...
if (inv) {
root = root.neg();
}
if (root.isZero()) {
throw new Error('Root must be non-zero');
}
if (a.isNegative() && !root.abs().mod(2).equals(1)) {
throw new Error('Root must be odd when a is negative.');
}
// edge cases zero and infinity
if (a.isZero()) {
return inv ? new Big(Infinity) : 0;
}
...
exp = function () { return naturalExponential(this); }
...
// https://www.wikiwand.com/en/Cube_root#/Complex_numbers
var arg_3 = x.arg() / 3;
var abs = x.abs();
// principal root:
var principal = new type.Complex(_cbrtNumber(abs), 0).mul(
new type.Complex(0, arg_3).exp());
if (allRoots) {
var all = [
principal,
new type.Complex(_cbrtNumber(abs), 0).mul(
new type.Complex(0, arg_3 + Math.PI * 2 / 3).exp()),
new type.Complex(_cbrtNumber(abs), 0).mul(
...
floor = function () { return finalise(new this.constructor(this), this.e + 1, 3); }
...
* ceil, floor, round
*
* @param {number | BigNumber | Fraction | Complex | Array | Matrix} x Number to be rounded
* @return {number | BigNumber | Fraction | Complex | Array | Matrix} Rounded value
*/
var fix = typed('fix', {
'number': function (x) {
return (x > 0) ? Math.floor(x) : Math.ceil(x);
},
'Complex': function (x) {
return new type.Complex(
(x.re > 0) ? Math.floor(x.re) : Math.ceil(x.re),
(x.im > 0) ? Math.floor(x.im) : Math.ceil(x.im)
);
...
greaterThan = function (y) { return this.cmp(y) > 0; }
n/a
greaterThanOrEqualTo = function (y) { var k = this.cmp(y); return k == 1 || k === 0; }
n/a
gt = function (y) { return this.cmp(y) > 0; }
...
* @param {BigNumber} step
* @returns {Array} range
* @private
*/
function _bigRangeEx (start, end, step) {
var array = [],
x = start;
if (step.gt(ZERO)) {
while (x.lt(end)) {
array.push(x);
x = x.plus(step);
}
}
else if (step.lt(ZERO)) {
while (x.gt(end)) {
...
gte = function (y) { var k = this.cmp(y); return k == 1 || k === 0; }
...
if (step.gt(ZERO)) {
while (x.lte(end)) {
array.push(x);
x = x.plus(step);
}
}
else if (step.lt(ZERO)) {
while (x.gte(end)) {
array.push(x);
x = x.plus(step);
}
}
return array;
}
...
hyperbolicCosine = function () { var k, n, pr, rm, len, x = this, Ctor = x.constructor, one = new Ctor(1); if (!x.isFinite()) return new Ctor(x.s ? 1 / 0 : NaN); if (x.isZero()) return one; pr = Ctor.precision; rm = Ctor.rounding; Ctor.precision = pr + Math.max(x.e, x.sd()) + 4; Ctor.rounding = 1; len = x.d.length; // Argument reduction: cos(4x) = 1 - 8cos^2(x) + 8cos^4(x) + 1 // i.e. cos(x) = 1 - cos^2(x/4)(8 - 8cos^2(x/4)) // Estimate the optimum number of times to use the argument reduction. // TODO? Estimation reused from cosine() and may not be optimal here. if (len < 32) { k = Math.ceil(len / 3); n = Math.pow(4, -k).toString(); } else { k = 16; n = '2.3283064365386962890625e-10'; } x = taylorSeries(Ctor, 1, x.times(n), new Ctor(1), true); // Reverse argument reduction var cosh2_x, i = k, d8 = new Ctor(8); for (; i--;) { cosh2_x = x.times(x); x = one.minus(cosh2_x.times(d8.minus(cosh2_x.times(d8)))); } return finalise(x, Ctor.precision = pr, Ctor.rounding = rm, true); }
n/a
hyperbolicSine = function () { var k, pr, rm, len, x = this, Ctor = x.constructor; if (!x.isFinite() || x.isZero()) return new Ctor(x); pr = Ctor.precision; rm = Ctor.rounding; Ctor.precision = pr + Math.max(x.e, x.sd()) + 4; Ctor.rounding = 1; len = x.d.length; if (len < 3) { x = taylorSeries(Ctor, 2, x, x, true); } else { // Alternative argument reduction: sinh(3x) = sinh(x)(3 + 4sinh^2(x)) // i.e. sinh(x) = sinh(x/3)(3 + 4sinh^2(x/3)) // 3 multiplications and 1 addition // Argument reduction: sinh(5x) = sinh(x)(5 + sinh^2(x)(20 + 16sinh^2(x))) // i.e. sinh(x) = sinh(x/5)(5 + sinh^2(x/5)(20 + 16sinh^2(x/5))) // 4 multiplications and 2 additions // Estimate the optimum number of times to use the argument reduction. k = 1.4 * Math.sqrt(len); k = k > 16 ? 16 : k | 0; x = x.times(Math.pow(5, -k)); x = taylorSeries(Ctor, 2, x, x, true); // Reverse argument reduction var sinh2_x, d5 = new Ctor(5), d16 = new Ctor(16), d20 = new Ctor(20); for (; k--;) { sinh2_x = x.times(x); x = x.times(d5.plus(sinh2_x.times(d16.times(sinh2_x).plus(d20)))); } } Ctor.precision = pr; Ctor.rounding = rm; return finalise(x, pr, rm, true); }
n/a
hyperbolicTangent = function () { var pr, rm, x = this, Ctor = x.constructor; if (!x.isFinite()) return new Ctor(x.s); if (x.isZero()) return new Ctor(x); pr = Ctor.precision; rm = Ctor.rounding; Ctor.precision = pr + 7; Ctor.rounding = 1; return divide(x.sinh(), x.cosh(), Ctor.precision = pr, Ctor.rounding = rm); }
n/a
inverseCosine = function () { var halfPi, x = this, Ctor = x.constructor, k = x.abs().cmp(1), pr = Ctor.precision, rm = Ctor.rounding; if (k !== -1) { return k === 0 // |x| is 1 ? x.isNeg() ? getPi(Ctor, pr, rm) : new Ctor(0) // |x| > 1 or x is NaN : new Ctor(NaN); } if (x.isZero()) return getPi(Ctor, pr + 4, rm).times(0.5); // TODO? Special case acos(0.5) = pi/3 and acos(-0.5) = 2*pi/3 Ctor.precision = pr + 6; Ctor.rounding = 1; x = x.asin(); halfPi = getPi(Ctor, pr + 4, rm).times(0.5); Ctor.precision = pr; Ctor.rounding = rm; return halfPi.minus(x); }
n/a
inverseHyperbolicCosine = function () { var pr, rm, x = this, Ctor = x.constructor; if (x.lte(1)) return new Ctor(x.eq(1) ? 0 : NaN); if (!x.isFinite()) return new Ctor(x); pr = Ctor.precision; rm = Ctor.rounding; Ctor.precision = pr + Math.max(Math.abs(x.e), x.sd()) + 4; Ctor.rounding = 1; external = false; x = x.times(x).minus(1).sqrt().plus(x); external = true; Ctor.precision = pr; Ctor.rounding = rm; return x.ln(); }
n/a
inverseHyperbolicSine = function () { var pr, rm, x = this, Ctor = x.constructor; if (!x.isFinite() || x.isZero()) return new Ctor(x); pr = Ctor.precision; rm = Ctor.rounding; Ctor.precision = pr + 2 * Math.max(Math.abs(x.e), x.sd()) + 6; Ctor.rounding = 1; external = false; x = x.times(x).plus(1).sqrt().plus(x); external = true; Ctor.precision = pr; Ctor.rounding = rm; return x.ln(); }
n/a
inverseHyperbolicTangent = function () { var pr, rm, wpr, xsd, x = this, Ctor = x.constructor; if (!x.isFinite()) return new Ctor(NaN); if (x.e >= 0) return new Ctor(x.abs().eq(1) ? x.s / 0 : x.isZero() ? x : NaN); pr = Ctor.precision; rm = Ctor.rounding; xsd = x.sd(); if (Math.max(xsd, pr) < 2 * -x.e - 1) return finalise(new Ctor(x), pr, rm, true); Ctor.precision = wpr = xsd - x.e; x = divide(x.plus(1), new Ctor(1).minus(x), wpr + pr, 1); Ctor.precision = pr + 4; Ctor.rounding = 1; x = x.ln(); Ctor.precision = pr; Ctor.rounding = rm; return x.times(0.5); }
n/a
inverseSine = function () { var halfPi, k, pr, rm, x = this, Ctor = x.constructor; if (x.isZero()) return new Ctor(x); k = x.abs().cmp(1); pr = Ctor.precision; rm = Ctor.rounding; if (k !== -1) { // |x| is 1 if (k === 0) { halfPi = getPi(Ctor, pr + 4, rm).times(0.5); halfPi.s = x.s; return halfPi; } // |x| > 1 or x is NaN return new Ctor(NaN); } // TODO? Special case asin(1/2) = pi/6 and asin(-1/2) = -pi/6 Ctor.precision = pr + 6; Ctor.rounding = 1; x = x.div(new Ctor(1).minus(x.times(x)).sqrt().plus(1)).atan(); Ctor.precision = pr; Ctor.rounding = rm; return x.times(2); }
n/a
inverseTangent = function () { var i, j, k, n, px, t, r, wpr, x2, x = this, Ctor = x.constructor, pr = Ctor.precision, rm = Ctor.rounding; if (!x.isFinite()) { if (!x.s) return new Ctor(NaN); if (pr + 4 <= PI_PRECISION) { r = getPi(Ctor, pr + 4, rm).times(0.5); r.s = x.s; return r; } } else if (x.isZero()) { return new Ctor(x); } else if (x.abs().eq(1) && pr + 4 <= PI_PRECISION) { r = getPi(Ctor, pr + 4, rm).times(0.25); r.s = x.s; return r; } Ctor.precision = wpr = pr + 10; Ctor.rounding = 1; // TODO? if (x >= 1 && pr <= PI_PRECISION) atan(x) = halfPi * x.s - atan(1 / x); // Argument reduction // Ensure |x| < 0.42 // atan(x) = 2 * atan(x / (1 + sqrt(1 + x^2))) k = Math.min(28, wpr / LOG_BASE + 2 | 0); for (i = k; i; --i) x = x.div(x.times(x).plus(1).sqrt().plus(1)); external = false; j = Math.ceil(wpr / LOG_BASE); n = 1; x2 = x.times(x); r = new Ctor(x); px = x; // atan(x) = x - x^3/3 + x^5/5 - x^7/7 + ... for (; i !== -1;) { px = px.times(x2); t = r.minus(px.div(n += 2)); px = px.times(x2); r = t.plus(px.div(n += 2)); if (r.d[j] !== void 0) for (i = j; r.d[i] === t.d[i] && i--;); } if (k) r = r.times(2 << (k - 1)); external = true; return finalise(r, Ctor.precision = pr, Ctor.rounding = rm, true); }
n/a
isFinite = function () { return !!this.d; }
...
throw new Error('Root must be odd when a is negative.');
}
// edge cases zero and infinity
if (a.isZero()) {
return inv ? new Big(Infinity) : 0;
}
if (!a.isFinite()) {
return inv ? zero : a;
}
var x = a.abs().pow(one.div(root));
// If a < 0, we require that root is an odd integer,
// so (-1) ^ (1/root) = -1
x = a.isNeg() ? x.neg() : x;
...
isInt = function () { return !!this.d && mathfloor(this.e / LOG_BASE) > this.d.length - 2; }
...
* Calculate gcd for BigNumbers
* @param {BigNumber} a
* @param {BigNumber} b
* @returns {BigNumber} Returns greatest common denominator of a and b
* @private
*/
function _gcdBigNumber(a, b) {
if (!a.isInt() || !b.isInt()) {
throw new Error('Parameters in function gcd must be integer numbers');
}
// http://en.wikipedia.org/wiki/Euclidean_algorithm
var zero = new type.BigNumber(0);
while (!b.isZero()) {
var r = a.mod(b);
...
isInteger = function () { return !!this.d && mathfloor(this.e / LOG_BASE) > this.d.length - 2; }
...
/**
* Test whether index is an integer number with index >= 0 and index < length
* when length is provided
* @param {number} index Zero-based index
* @param {number} [length] Length of the array
*/
exports.validateIndex = function(index, length) {
if (!number.isNumber(index) || !number.isInteger(index)) {
throw new TypeError('Index must be an integer (value: ' + index + ')');
}
if (index < 0 || (typeof length === 'number' && index >= length)) {
throw new IndexError(index, length);
}
};
...
isNaN = function () { return !this.s; }
...
},
'Complex, Complex': function (x, y) {
return (x.re !== 0 || x.im !== 0) && (y.re !== 0 || y.im !== 0);
},
'BigNumber, BigNumber': function (x, y) {
return !x.isZero() && !y.isZero() && !x.isNaN() && !y
.isNaN();
},
'Unit, Unit': function (x, y) {
return and(x.value, y.value);
},
'Matrix, Matrix': function (x, y) {
...
isNeg = function () { return this.s < 0; }
...
if (!a.isFinite()) {
return inv ? zero : a;
}
var x = a.abs().pow(one.div(root));
// If a < 0, we require that root is an odd integer,
// so (-1) ^ (1/root) = -1
x = a.isNeg() ? x.neg() : x;
return new type.BigNumber((inv ? one.div(x) : x).toPrecision(precision));
}
}
/**
* Calculate the nth root of a, solve x^root == a
* http://rosettacode.org/wiki/Nth_root#JavaScript
...
isNegative = function () { return this.s < 0; }
...
return new type.Complex(
(x.re > 0) ? Math.floor(x.re) : Math.ceil(x.re),
(x.im > 0) ? Math.floor(x.im) : Math.ceil(x.im)
);
},
'BigNumber': function (x) {
return x.isNegative() ? x.ceil() : x.floor();
},
'Fraction': function (x) {
return x.s < 0 ? x.ceil() : x.floor();
},
'Array | Matrix': function (x) {
...
isPos = function () { return this.s > 0; }
n/a
isPositive = function () { return this.s > 0; }
...
* Test whether a value is positive: larger than zero.
* The function supports types `number`, `BigNumber`, `Fraction`, and `Unit`.
*
* The function is evaluated element-wise in case of Array or Matrix input.
*
* Syntax:
*
* math.isPositive(x)
*
* Examples:
*
* math.isPositive(3); // returns true
* math.isPositive(-2); // returns false
* math.isPositive(0); // returns false
* math.isPositive(-0); // returns false
...
isZero = function () { return !!this.d && this.d[0] === 0; }
...
},
'number': function (x) {
return !!x;
},
'BigNumber': function (x) {
return !x.isZero();
},
'string': function (x) {
// try case insensitive
var lcase = x.toLowerCase();
if (lcase === 'true') {
return true;
...
lessThan = function (y) { return this.cmp(y) < 0; }
n/a
lessThanOrEqualTo = function (y) { return this.cmp(y) < 1; }
n/a
ln = function () { return naturalLogarithm(this); }
...
setLazyConstant(math, 'pi', function () {return bigConstants.pi(type.BigNumber)});
setLazyConstant(math, 'tau', function () {return bigConstants.tau(type.BigNumber)});
setLazyConstant(math, 'e', function () {return bigConstants.e(type.BigNumber)});
setLazyConstant(math, 'phi', function () {return bigConstants.phi(type.BigNumber)}); // golden ratio, (1+sqrt(5))/2
// uppercase constants (for compatibility with built-in Math)
setLazyConstant(math, 'E', function () {return math.e;});
setLazyConstant(math, 'LN2', function () {return new type.BigNumber(2).ln();});
setLazyConstant(math, 'LN10', function () {return new type.BigNumber(10).ln()});
setLazyConstant(math, 'LOG2E', function () {return new type.BigNumber(1).div(new type.BigNumber(2).ln());});
setLazyConstant(math, 'LOG10E', function () {return new type.BigNumber(1).div(new type.BigNumber(10).ln())});
setLazyConstant(math, 'PI', function () {return math.pi});
setLazyConstant(math, 'SQRT1_2', function () {return new type.BigNumber('0.5').sqrt()});
setLazyConstant(math, 'SQRT2', function () {return new type.BigNumber(2).sqrt()});
}
...
log = function (base) { var isBase10, d, denominator, k, inf, num, sd, r, arg = this, Ctor = arg.constructor, pr = Ctor.precision, rm = Ctor.rounding, guard = 5; // Default base is 10. if (base == null) { base = new Ctor(10); isBase10 = true; } else { base = new Ctor(base); d = base.d; // Return NaN if base is negative, or non-finite, or is 0 or 1. if (base.s < 0 || !d || !d[0] || base.eq(1)) return new Ctor(NaN); isBase10 = base.eq(10); } d = arg.d; // Is arg negative, non-finite, 0 or 1? if (arg.s < 0 || !d || !d[0] || arg.eq(1)) { return new Ctor(d && !d[0] ? -1 / 0 : arg.s != 1 ? NaN : d ? 0 : 1 / 0); } // The result will have a non-terminating decimal expansion if base is 10 and arg is not an // integer power of 10. if (isBase10) { if (d.length > 1) { inf = true; } else { for (k = d[0]; k % 10 === 0;) k /= 10; inf = k !== 1; } } external = false; sd = pr + guard; num = naturalLogarithm(arg, sd); denominator = isBase10 ? getLn10(Ctor, sd + 10) : naturalLogarithm(base, sd); // The result will have 5 rounding digits. r = divide(num, denominator, sd, 1); // If at a rounding boundary, i.e. the result's rounding digits are [49]9999 or [50]0000, // calculate 10 further digits. // // If the result is known to have an infinite decimal expansion, repeat this until it is clear // that the result is above or below the boundary. Otherwise, if after calculating the 10 // further digits, the last 14 are nines, round up and assume the result is exact. // Also assume the result is exact if the last 14 are zero. // // Example of a result that will be incorrectly rounded: // log[1048576](4503599627370502) = 2.60000000000000009610279511444746... // The above result correctly rounded using ROUND_CEIL to 1 decimal place should be 2.7, but it // will be given as 2.6 as there are 15 zeros immediately after the requested decimal place, so // the exact result would be assumed to be 2.6, which rounded using ROUND_CEIL to 1 decimal // place is still 2.6. if (checkRoundingDigits(r.d, k = pr, rm)) { do { sd += 10; num = naturalLogarithm(arg, sd); denominator = isBase10 ? getLn10(Ctor, sd + 10) : naturalLogarithm(base, sd); r = divide(num, denominator, sd, 1); if (!inf) { // Check for 14 nines from the 2nd rounding digit, as the first may be 4. if (+digitsToString(r.d).slice(k + 1, k + 15) + 1 == 1e14) { r = finalise(r, pr + 1, 0); } break; } } while (checkRoundingDigits(r.d, k += 10, rm)); } external = true; return finalise(r, pr, rm); }
...
```js
// load math.js
var math = require('mathjs');
// functions and constants
math.round(math.e, 3); // 2.718
math.atan2(3, -3) / math.pi; // 0.75
math.log(1000, 10); // 3
math.sqrt(-4); // 2i
math.pow([[-1, 2], [3, 1]], 2); // [[7, 0], [0, 7]]
math.derivative('x^2 + x', 'x'); // 2 * x + 1
// expressions
math.eval('12 / (2.3 + 0.7)'); // 4
math.eval('5.08 cm to inch'); // 2 inch
...
logarithm = function (base) { var isBase10, d, denominator, k, inf, num, sd, r, arg = this, Ctor = arg.constructor, pr = Ctor.precision, rm = Ctor.rounding, guard = 5; // Default base is 10. if (base == null) { base = new Ctor(10); isBase10 = true; } else { base = new Ctor(base); d = base.d; // Return NaN if base is negative, or non-finite, or is 0 or 1. if (base.s < 0 || !d || !d[0] || base.eq(1)) return new Ctor(NaN); isBase10 = base.eq(10); } d = arg.d; // Is arg negative, non-finite, 0 or 1? if (arg.s < 0 || !d || !d[0] || arg.eq(1)) { return new Ctor(d && !d[0] ? -1 / 0 : arg.s != 1 ? NaN : d ? 0 : 1 / 0); } // The result will have a non-terminating decimal expansion if base is 10 and arg is not an // integer power of 10. if (isBase10) { if (d.length > 1) { inf = true; } else { for (k = d[0]; k % 10 === 0;) k /= 10; inf = k !== 1; } } external = false; sd = pr + guard; num = naturalLogarithm(arg, sd); denominator = isBase10 ? getLn10(Ctor, sd + 10) : naturalLogarithm(base, sd); // The result will have 5 rounding digits. r = divide(num, denominator, sd, 1); // If at a rounding boundary, i.e. the result's rounding digits are [49]9999 or [50]0000, // calculate 10 further digits. // // If the result is known to have an infinite decimal expansion, repeat this until it is clear // that the result is above or below the boundary. Otherwise, if after calculating the 10 // further digits, the last 14 are nines, round up and assume the result is exact. // Also assume the result is exact if the last 14 are zero. // // Example of a result that will be incorrectly rounded: // log[1048576](4503599627370502) = 2.60000000000000009610279511444746... // The above result correctly rounded using ROUND_CEIL to 1 decimal place should be 2.7, but it // will be given as 2.6 as there are 15 zeros immediately after the requested decimal place, so // the exact result would be assumed to be 2.6, which rounded using ROUND_CEIL to 1 decimal // place is still 2.6. if (checkRoundingDigits(r.d, k = pr, rm)) { do { sd += 10; num = naturalLogarithm(arg, sd); denominator = isBase10 ? getLn10(Ctor, sd + 10) : naturalLogarithm(base, sd); r = divide(num, denominator, sd, 1); if (!inf) { // Check for 14 nines from the 2nd rounding digit, as the first may be 4. if (+digitsToString(r.d).slice(k + 1, k + 15) + 1 == 1e14) { r = finalise(r, pr + 1, 0); } break; } } while (checkRoundingDigits(r.d, k += 10, rm)); } external = true; return finalise(r, pr, rm); }
n/a
lt = function (y) { return this.cmp(y) < 0; }
...
// http://en.wikipedia.org/wiki/Euclidean_algorithm
var zero = new type.BigNumber(0);
while (!b.isZero()) {
var r = a.mod(b);
a = b;
b = r;
}
return a.lt(zero) ? a.neg() : a;
}
}
/**
* Calculate gcd for numbers
* @param {number} a
* @param {number} b
...
lte = function (y) { return this.cmp(y) < 1; }
...
* @returns {Array} range
* @private
*/
function _bigRangeInc (start, end, step) {
var array = [],
x = start;
if (step.gt(ZERO)) {
while (x.lte(end)) {
array.push(x);
x = x.plus(step);
}
}
else if (step.lt(ZERO)) {
while (x.gte(end)) {
array.push(x);
...
minus = function (y) { var d, e, i, j, k, len, pr, rm, xd, xe, xLTy, yd, x = this, Ctor = x.constructor; y = new Ctor(y); // If either is not finite... if (!x.d || !y.d) { // Return NaN if either is NaN. if (!x.s || !y.s) y = new Ctor(NaN); // Return y negated if x is finite and y is ±Infinity. else if (x.d) y.s = -y.s; // Return x if y is finite and x is ±Infinity. // Return x if both are ±Infinity with different signs. // Return NaN if both are ±Infinity with the same sign. else y = new Ctor(y.d || x.s !== y.s ? x : NaN); return y; } // If signs differ... if (x.s != y.s) { y.s = -y.s; return x.plus(y); } xd = x.d; yd = y.d; pr = Ctor.precision; rm = Ctor.rounding; // If either is zero... if (!xd[0] || !yd[0]) { // Return y negated if x is zero and y is non-zero. if (yd[0]) y.s = -y.s; // Return x if y is zero and x is non-zero. else if (xd[0]) y = new Ctor(x); // Return zero if both are zero. // From IEEE 754 (2008) 6.3: 0 - 0 = -0 - -0 = -0 when rounding to -Infinity. else return new Ctor(rm === 3 ? -0 : 0); return external ? finalise(y, pr, rm) : y; } // x and y are finite, non-zero numbers with the same sign. // Calculate base 1e7 exponents. e = mathfloor(y.e / LOG_BASE); xe = mathfloor(x.e / LOG_BASE); xd = xd.slice(); k = xe - e; // If base 1e7 exponents differ... if (k) { xLTy = k < 0; if (xLTy) { d = xd; k = -k; len = yd.length; } else { d = yd; e = xe; len = xd.length; } // Numbers with massively different exponents would result in a very high number of // zeros needing to be prepended, but this can be avoided while still ensuring correct // rounding by limiting the number of zeros to `Math.ceil(pr / LOG_BASE) + 2`. i = Math.max(Math.ceil(pr / LOG_BASE), len) + 2; if (k > i) { k = i; d.length = 1; } // Prepend zeros to equalise exponents. d.reverse(); for (i = k; i--;) d.push(0); d.reverse(); // Base 1e7 exponents equal. } else { // Check digits to determine which is the bigger number. i = xd.length; len = yd.length; xLTy = i < len; if (xLTy) len = i; for (i = 0; i < len; i++) { if (xd[i] != yd[i]) { xLTy = xd[i] < yd[i]; break; } } k = 0; } if (xLTy) { d = xd; xd = yd; yd = d; y.s = -y.s; } len = xd.length; // Append zeros to `xd` if shorter. // Don't add zeros to `yd` if shorter as subtraction only needs to start at `yd` length. for (i = yd.length - len; i > 0; --i) xd[len++] = 0; // Subtract yd from xd. for (i = yd.length; i > k;) { if (xd[--i] < yd[i]) { for (j = i; j && xd[--j] === 0;) xd[j] = BASE - 1; --xd[j]; xd[i] += BASE; } xd[i] -= yd[i]; } // Remove trailing zeros. for (; xd[--len] === 0;) xd.pop(); // Remove leading zeros and adjust exponent accordingly. for (; xd[0] === 0; xd.shift()) --e; // Zero? if (!xd[0]) return new Ctor(rm === 3 ? -0 : 0); y.d = xd; y.e = getBase10Exponent(xd, e); return external ? finalise(y, pr, rm) : y; }
...
// change last argument from one-based to zero-based
var lastIndex = args.length - 1;
var last = args[lastIndex];
if (typeof last === 'number') {
args[lastIndex] = last - 1;
}
else if (last && last.isBigNumber === true) {
args[lastIndex] = last.minus(1);
}
try {
return concat.apply(null, args);
}
catch (err) {
throw errorTransform(err);
...
mod = function (y) { var q, x = this, Ctor = x.constructor; y = new Ctor(y); // Return NaN if x is ±Infinity or NaN, or y is NaN or ±0. if (!x.d || !y.s || y.d && !y.d[0]) return new Ctor(NaN); // Return x if y is ±Infinity or x is ±0. if (!y.d || x.d && !x.d[0]) { return finalise(new Ctor(x), Ctor.precision, Ctor.rounding); } // Prevent rounding of intermediate calculations. external = false; if (Ctor.modulo == 9) { // Euclidian division: q = sign(y) * floor(x / abs(y)) // result = x - q * y where 0 <= result < abs(y) q = divide(x, y.abs(), 0, 3, 1); q.s *= y.s; } else { q = divide(x, y, 0, Ctor.modulo, 1); } q = q.times(y); external = true; return x.minus(q); }
...
if (!a.isInt() || !b.isInt()) {
throw new Error('Parameters in function gcd must be integer numbers');
}
// http://en.wikipedia.org/wiki/Euclidean_algorithm
var zero = new type.BigNumber(0);
while (!b.isZero()) {
var r = a.mod(b);
a = b;
b = r;
}
return a.lt(zero) ? a.neg() : a;
}
}
...
modulo = function (y) { var q, x = this, Ctor = x.constructor; y = new Ctor(y); // Return NaN if x is ±Infinity or NaN, or y is NaN or ±0. if (!x.d || !y.s || y.d && !y.d[0]) return new Ctor(NaN); // Return x if y is ±Infinity or x is ±0. if (!y.d || x.d && !x.d[0]) { return finalise(new Ctor(x), Ctor.precision, Ctor.rounding); } // Prevent rounding of intermediate calculations. external = false; if (Ctor.modulo == 9) { // Euclidian division: q = sign(y) * floor(x / abs(y)) // result = x - q * y where 0 <= result < abs(y) q = divide(x, y.abs(), 0, 3, 1); q.s *= y.s; } else { q = divide(x, y, 0, Ctor.modulo, 1); } q = q.times(y); external = true; return x.minus(q); }
n/a
mul = function (y) { var carry, e, i, k, r, rL, t, xdL, ydL, x = this, Ctor = x.constructor, xd = x.d, yd = (y = new Ctor(y)).d; y.s *= x.s; // If either is NaN, ±Infinity or ±0... if (!xd || !xd[0] || !yd || !yd[0]) { return new Ctor(!y.s || xd && !xd[0] && !yd || yd && !yd[0] && !xd // Return NaN if either is NaN. // Return NaN if x is ±0 and y is ±Infinity, or y is ±0 and x is ±Infinity. ? NaN // Return ±Infinity if either is ±Infinity. // Return ±0 if either is ±0. : !xd || !yd ? y.s / 0 : y.s * 0); } e = mathfloor(x.e / LOG_BASE) + mathfloor(y.e / LOG_BASE); xdL = xd.length; ydL = yd.length; // Ensure xd points to the longer array. if (xdL < ydL) { r = xd; xd = yd; yd = r; rL = xdL; xdL = ydL; ydL = rL; } // Initialise the result array with zeros. r = []; rL = xdL + ydL; for (i = rL; i--;) r.push(0); // Multiply! for (i = ydL; --i >= 0;) { carry = 0; for (k = xdL + i; k > i;) { t = r[k] + yd[i] * xd[k - i - 1] + carry; r[k--] = t % BASE | 0; carry = t / BASE | 0; } r[k] = (r[k] + carry) % BASE | 0; } // Remove trailing zeros. for (; !r[--rL];) r.pop(); if (carry) ++e; else r.shift(); y.d = r; y.e = getBase10Exponent(r, e); return external ? finalise(y, Ctor.precision, Ctor.rounding) : y; }
...
function _cbrtComplex(x, allRoots) {
// https://www.wikiwand.com/en/Cube_root#/Complex_numbers
var arg_3 = x.arg() / 3;
var abs = x.abs();
// principal root:
var principal = new type.Complex(_cbrtNumber(abs), 0).mul(
new type.Complex(0, arg_3).exp());
if (allRoots) {
var all = [
principal,
new type.Complex(_cbrtNumber(abs), 0).mul(
new type.Complex(0, arg_3 + Math.PI * 2 / 3).exp()),
...
naturalExponential = function () { return naturalExponential(this); }
n/a
naturalLogarithm = function () { return naturalLogarithm(this); }
n/a
neg = function () { var x = new this.constructor(this); x.s = -x.s; return finalise(x); }
...
// http://en.wikipedia.org/wiki/Euclidean_algorithm
var zero = new type.BigNumber(0);
while (!b.isZero()) {
var r = a.mod(b);
a = b;
b = r;
}
return a.lt(zero) ? a.neg() : a;
}
}
/**
* Calculate gcd for numbers
* @param {number} a
* @param {number} b
...
negated = function () { var x = new this.constructor(this); x.s = -x.s; return finalise(x); }
n/a
plus = function (y) { var carry, d, e, i, k, len, pr, rm, xd, yd, x = this, Ctor = x.constructor; y = new Ctor(y); // If either is not finite... if (!x.d || !y.d) { // Return NaN if either is NaN. if (!x.s || !y.s) y = new Ctor(NaN); // Return x if y is finite and x is ±Infinity. // Return x if both are ±Infinity with the same sign. // Return NaN if both are ±Infinity with different signs. // Return y if x is finite and y is ±Infinity. else if (!x.d) y = new Ctor(y.d || x.s === y.s ? x : NaN); return y; } // If signs differ... if (x.s != y.s) { y.s = -y.s; return x.minus(y); } xd = x.d; yd = y.d; pr = Ctor.precision; rm = Ctor.rounding; // If either is zero... if (!xd[0] || !yd[0]) { // Return x if y is zero. // Return y if y is non-zero. if (!yd[0]) y = new Ctor(x); return external ? finalise(y, pr, rm) : y; } // x and y are finite, non-zero numbers with the same sign. // Calculate base 1e7 exponents. k = mathfloor(x.e / LOG_BASE); e = mathfloor(y.e / LOG_BASE); xd = xd.slice(); i = k - e; // If base 1e7 exponents differ... if (i) { if (i < 0) { d = xd; i = -i; len = yd.length; } else { d = yd; e = k; len = xd.length; } // Limit number of zeros prepended to max(ceil(pr / LOG_BASE), len) + 1. k = Math.ceil(pr / LOG_BASE); len = k > len ? k + 1 : len + 1; if (i > len) { i = len; d.length = 1; } // Prepend zeros to equalise exponents. Note: Faster to use reverse then do unshifts. d.reverse(); for (; i--;) d.push(0); d.reverse(); } len = xd.length; i = yd.length; // If yd is longer than xd, swap xd and yd so xd points to the longer array. if (len - i < 0) { i = len; d = yd; yd = xd; xd = d; } // Only start adding at yd.length - 1 as the further digits of xd can be left as they are. for (carry = 0; i;) { carry = (xd[--i] = xd[i] + yd[i] + carry) / BASE | 0; xd[i] %= BASE; } if (carry) { xd.unshift(carry); ++e; } // Remove trailing zeros. // No need to check for zero, as +x + +y != 0 && -x + -y != 0 for (len = xd.length; xd[--len] == 0;) xd.pop(); y.d = xd; y.e = getBase10Exponent(xd, e); return external ? finalise(y, pr, rm) : y; }
...
},
'Complex, Complex': function (x, y) {
return x.add(y);
},
'BigNumber, BigNumber': function (x, y) {
return x.plus(y);
},
'Fraction, Fraction': function (x, y) {
return x.add(y);
},
'Unit, Unit': function (x, y) {
...
pow = function (y) { var e, k, pr, r, rm, sign, yIsInt, x = this, Ctor = x.constructor, yn = +(y = new Ctor(y)); // Either ±Infinity, NaN or ±0? if (!x.d || !y.d || !x.d[0] || !y.d[0]) return new Ctor(mathpow(+x, yn)); x = new Ctor(x); if (x.eq(1)) return x; pr = Ctor.precision; rm = Ctor.rounding; if (y.eq(1)) return finalise(x, pr, rm); e = mathfloor(y.e / LOG_BASE); k = y.d.length - 1; yIsInt = e >= k; sign = x.s; if (!yIsInt) { if (sign < 0) return new Ctor(NaN); // If y is a small integer use the 'exponentiation by squaring' algorithm. } else if ((k = yn < 0 ? -yn : yn) <= MAX_SAFE_INTEGER) { r = intPow(Ctor, x, k, pr); return y.s < 0 ? new Ctor(1).div(r) : finalise(r, pr, rm); } // Result is negative if x is negative and the last digit of integer y is odd. sign = sign < 0 && y.d[Math.max(e, k)] & 1 ? -1 : 1; // Estimate result exponent. // x^y = 10^e, where e = y * log10(x) // log10(x) = log10(x_significand) + x_exponent // log10(x_significand) = ln(x_significand) / ln(10) k = mathpow(+x, yn); e = k == 0 || !isFinite(k) ? mathfloor(yn * (Math.log('0.' + digitsToString(x.d)) / Math.LN10 + x.e + 1)) : new Ctor(k + '').e; // Estimate may be incorrect e.g. x: 0.999999999999999999, y: 2.29, e: 0, r.e: -1. // Overflow/underflow? if (e > Ctor.maxE + 1 || e < Ctor.minE - 1) return new Ctor(e > 0 ? sign / 0 : 0); external = false; Ctor.rounding = x.s = 1; // Estimate the extra guard digits needed to ensure five correct rounding digits from // naturalLogarithm(x). Example of failure without these extra digits (precision: 10): // new Decimal(2.32456).pow('2087987436534566.46411') // should be 1.162377823e+764914905173815, but is 1.162355823e+764914905173815 k = Math.min(12, (e + '').length); // r = x^y = exp(y*ln(x)) r = naturalExponential(y.times(naturalLogarithm(x, pr + k)), pr); // Truncate to the required precision plus five rounding digits. r = finalise(r, pr + 5, 1); // If the rounding digits are [49]9999 or [50]0000 increase the precision by 10 and recalculate // the result. if (checkRoundingDigits(r.d, pr, rm)) { e = pr + 10; // Truncate to the increased precision plus five rounding digits. r = finalise(naturalExponential(y.times(naturalLogarithm(x, e + k)), e), e + 5, 1); // Check for 14 nines from the 2nd rounding digit (the first rounding digit may be 4 or 9). if (+digitsToString(r.d).slice(pr + 1, pr + 15) + 1 == 1e14) { r = finalise(r, pr + 1, 0); } } r.s = sign; external = true; Ctor.rounding = rm; return finalise(r, pr, rm); }
...
var math = require('mathjs');
// functions and constants
math.round(math.e, 3); // 2.718
math.atan2(3, -3) / math.pi; // 0.75
math.log(1000, 10); // 3
math.sqrt(-4); // 2i
math.pow([[-1, 2], [3, 1]], 2); // [[7, 0], [0, 7]]
math.derivative('x^2 + x', 'x'); // 2 * x + 1
// expressions
math.eval('12 / (2.3 + 0.7)'); // 4
math.eval('5.08 cm to inch'); // 2 inch
math.eval('sin(45 deg) ^ 2'); // 0.5
math.eval('9 / 3 + 2i'); // 3 + 2i
...
precision = function (z) { var k, x = this; if (z !== void 0 && z !== !!z && z !== 1 && z !== 0) throw Error(invalidArgument + z); if (x.d) { k = getPrecision(x.d); if (z && x.e + 1 > k) k = x.e + 1; } else { k = NaN; } return k; }
n/a
round = function () { var x = this, Ctor = x.constructor; return finalise(new Ctor(x), x.e + 1, Ctor.rounding); }
...
[chained operations](http://mathjs.org/docs/chained_operations.html).
```js
// load math.js
var math = require('mathjs');
// functions and constants
math.round(math.e, 3); // 2.718
math.atan2(3, -3) / math.pi; // 0.75
math.log(1000, 10); // 3
math.sqrt(-4); // 2i
math.pow([[-1, 2], [3, 1]], 2); // [[7, 0], [0, 7]]
math.derivative('x^2 + x', 'x'); // 2 * x + 1
// expressions
...
sd = function (z) { var k, x = this; if (z !== void 0 && z !== !!z && z !== 1 && z !== 0) throw Error(invalidArgument + z); if (x.d) { k = getPrecision(x.d); if (z && x.e + 1 > k) k = x.e + 1; } else { k = NaN; } return k; }
n/a
sin = function () { var pr, rm, x = this, Ctor = x.constructor; if (!x.isFinite()) return new Ctor(NaN); if (x.isZero()) return new Ctor(x); pr = Ctor.precision; rm = Ctor.rounding; Ctor.precision = pr + Math.max(x.e, x.sd()) + LOG_BASE; Ctor.rounding = 1; x = sine(Ctor, toLessThanHalfPi(Ctor, x)); Ctor.precision = pr; Ctor.rounding = rm; return finalise(quadrant > 2 ? x.neg() : x, pr, rm, true); }
...
res = 1; // 0! is per definition 1
}
return res;
}
if (n < 0.5) {
return Math.PI / (Math.sin(Math.PI * n) * gamma(1-n));
}
if (n >= 171.35) {
return Infinity; // will overflow
}
if (n > 85.0) { // Extended Stirling Approx
...
sine = function () { var pr, rm, x = this, Ctor = x.constructor; if (!x.isFinite()) return new Ctor(NaN); if (x.isZero()) return new Ctor(x); pr = Ctor.precision; rm = Ctor.rounding; Ctor.precision = pr + Math.max(x.e, x.sd()) + LOG_BASE; Ctor.rounding = 1; x = sine(Ctor, toLessThanHalfPi(Ctor, x)); Ctor.precision = pr; Ctor.rounding = rm; return finalise(quadrant > 2 ? x.neg() : x, pr, rm, true); }
n/a
sinh = function () { var k, pr, rm, len, x = this, Ctor = x.constructor; if (!x.isFinite() || x.isZero()) return new Ctor(x); pr = Ctor.precision; rm = Ctor.rounding; Ctor.precision = pr + Math.max(x.e, x.sd()) + 4; Ctor.rounding = 1; len = x.d.length; if (len < 3) { x = taylorSeries(Ctor, 2, x, x, true); } else { // Alternative argument reduction: sinh(3x) = sinh(x)(3 + 4sinh^2(x)) // i.e. sinh(x) = sinh(x/3)(3 + 4sinh^2(x/3)) // 3 multiplications and 1 addition // Argument reduction: sinh(5x) = sinh(x)(5 + sinh^2(x)(20 + 16sinh^2(x))) // i.e. sinh(x) = sinh(x/5)(5 + sinh^2(x/5)(20 + 16sinh^2(x/5))) // 4 multiplications and 2 additions // Estimate the optimum number of times to use the argument reduction. k = 1.4 * Math.sqrt(len); k = k > 16 ? 16 : k | 0; x = x.times(Math.pow(5, -k)); x = taylorSeries(Ctor, 2, x, x, true); // Reverse argument reduction var sinh2_x, d5 = new Ctor(5), d16 = new Ctor(16), d20 = new Ctor(20); for (; k--;) { sinh2_x = x.times(x); x = x.times(d5.plus(sinh2_x.times(d16.times(sinh2_x).plus(d20)))); } } Ctor.precision = pr; Ctor.rounding = rm; return finalise(x, pr, rm, true); }
...
*
* math.csch(x)
*
* Examples:
*
* // csch(x) = 1/ sinh(x)
* math.csch(0.5); // returns 1.9190347513349437
* 1 / math.sinh(0.5); // returns 1.9190347513349437
*
* See also:
*
* sinh, sech, coth
*
* @param {number | Complex | Unit | Array | Matrix} x Function input
* @return {number | Complex | Array | Matrix} Hyperbolic cosecant of x
...
sqrt = function () { var m, n, sd, r, rep, t, x = this, d = x.d, e = x.e, s = x.s, Ctor = x.constructor; // Negative/NaN/Infinity/zero? if (s !== 1 || !d || !d[0]) { return new Ctor(!s || s < 0 && (!d || d[0]) ? NaN : d ? x : 1 / 0); } external = false; // Initial estimate. s = Math.sqrt(+x); // Math.sqrt underflow/overflow? // Pass x to Math.sqrt as integer, then adjust the exponent of the result. if (s == 0 || s == 1 / 0) { n = digitsToString(d); if ((n.length + e) % 2 == 0) n += '0'; s = Math.sqrt(n); e = mathfloor((e + 1) / 2) - (e < 0 || e % 2); if (s == 1 / 0) { n = '1e' + e; } else { n = s.toExponential(); n = n.slice(0, n.indexOf('e') + 1) + e; } r = new Ctor(n); } else { r = new Ctor(s.toString()); } sd = (e = Ctor.precision) + 3; // Newton-Raphson iteration. for (;;) { t = r; r = t.plus(divide(x, t, sd + 2, 1)).times(0.5); // TODO? Replace with for-loop and checkRoundingDigits. if (digitsToString(t.d).slice(0, sd) === (n = digitsToString(r.d)).slice(0, sd)) { n = n.slice(sd - 3, sd + 1); // The 4th rounding digit may be in error by -1 so if the 4 rounding digits are 9999 or // 4999, i.e. approaching a rounding boundary, continue the iteration. if (n == '9999' || !rep && n == '4999') { // On the first iteration only, check to see if rounding up gives the exact result as the // nines may infinitely repeat. if (!rep) { finalise(t, e + 1, 0); if (t.times(t).eq(x)) { r = t; break; } } sd += 4; rep = 1; } else { // If the rounding digits are null, 0{0,4} or 50{0,3}, check for an exact result. // If not, then there are further digits and m will be truthy. if (!+n || !+n.slice(1) && n.charAt(0) == '5') { // Truncate to the first rounding digit. finalise(r, e + 1, 1); m = !r.times(r).eq(x); } break; } } } external = true; return finalise(r, e, Ctor.rounding, m); }
...
// load math.js
var math = require('mathjs');
// functions and constants
math.round(math.e, 3); // 2.718
math.atan2(3, -3) / math.pi; // 0.75
math.log(1000, 10); // 3
math.sqrt(-4); // 2i
math.pow([[-1, 2], [3, 1]], 2); // [[7, 0], [0, 7]]
math.derivative('x^2 + x', 'x'); // 2 * x + 1
// expressions
math.eval('12 / (2.3 + 0.7)'); // 4
math.eval('5.08 cm to inch'); // 2 inch
math.eval('sin(45 deg) ^ 2'); // 0.5
...
squareRoot = function () { var m, n, sd, r, rep, t, x = this, d = x.d, e = x.e, s = x.s, Ctor = x.constructor; // Negative/NaN/Infinity/zero? if (s !== 1 || !d || !d[0]) { return new Ctor(!s || s < 0 && (!d || d[0]) ? NaN : d ? x : 1 / 0); } external = false; // Initial estimate. s = Math.sqrt(+x); // Math.sqrt underflow/overflow? // Pass x to Math.sqrt as integer, then adjust the exponent of the result. if (s == 0 || s == 1 / 0) { n = digitsToString(d); if ((n.length + e) % 2 == 0) n += '0'; s = Math.sqrt(n); e = mathfloor((e + 1) / 2) - (e < 0 || e % 2); if (s == 1 / 0) { n = '1e' + e; } else { n = s.toExponential(); n = n.slice(0, n.indexOf('e') + 1) + e; } r = new Ctor(n); } else { r = new Ctor(s.toString()); } sd = (e = Ctor.precision) + 3; // Newton-Raphson iteration. for (;;) { t = r; r = t.plus(divide(x, t, sd + 2, 1)).times(0.5); // TODO? Replace with for-loop and checkRoundingDigits. if (digitsToString(t.d).slice(0, sd) === (n = digitsToString(r.d)).slice(0, sd)) { n = n.slice(sd - 3, sd + 1); // The 4th rounding digit may be in error by -1 so if the 4 rounding digits are 9999 or // 4999, i.e. approaching a rounding boundary, continue the iteration. if (n == '9999' || !rep && n == '4999') { // On the first iteration only, check to see if rounding up gives the exact result as the // nines may infinitely repeat. if (!rep) { finalise(t, e + 1, 0); if (t.times(t).eq(x)) { r = t; break; } } sd += 4; rep = 1; } else { // If the rounding digits are null, 0{0,4} or 50{0,3}, check for an exact result. // If not, then there are further digits and m will be truthy. if (!+n || !+n.slice(1) && n.charAt(0) == '5') { // Truncate to the first rounding digit. finalise(r, e + 1, 1); m = !r.times(r).eq(x); } break; } } } external = true; return finalise(r, e, Ctor.rounding, m); }
n/a
sub = function (y) { var d, e, i, j, k, len, pr, rm, xd, xe, xLTy, yd, x = this, Ctor = x.constructor; y = new Ctor(y); // If either is not finite... if (!x.d || !y.d) { // Return NaN if either is NaN. if (!x.s || !y.s) y = new Ctor(NaN); // Return y negated if x is finite and y is ±Infinity. else if (x.d) y.s = -y.s; // Return x if y is finite and x is ±Infinity. // Return x if both are ±Infinity with different signs. // Return NaN if both are ±Infinity with the same sign. else y = new Ctor(y.d || x.s !== y.s ? x : NaN); return y; } // If signs differ... if (x.s != y.s) { y.s = -y.s; return x.plus(y); } xd = x.d; yd = y.d; pr = Ctor.precision; rm = Ctor.rounding; // If either is zero... if (!xd[0] || !yd[0]) { // Return y negated if x is zero and y is non-zero. if (yd[0]) y.s = -y.s; // Return x if y is zero and x is non-zero. else if (xd[0]) y = new Ctor(x); // Return zero if both are zero. // From IEEE 754 (2008) 6.3: 0 - 0 = -0 - -0 = -0 when rounding to -Infinity. else return new Ctor(rm === 3 ? -0 : 0); return external ? finalise(y, pr, rm) : y; } // x and y are finite, non-zero numbers with the same sign. // Calculate base 1e7 exponents. e = mathfloor(y.e / LOG_BASE); xe = mathfloor(x.e / LOG_BASE); xd = xd.slice(); k = xe - e; // If base 1e7 exponents differ... if (k) { xLTy = k < 0; if (xLTy) { d = xd; k = -k; len = yd.length; } else { d = yd; e = xe; len = xd.length; } // Numbers with massively different exponents would result in a very high number of // zeros needing to be prepended, but this can be avoided while still ensuring correct // rounding by limiting the number of zeros to `Math.ceil(pr / LOG_BASE) + 2`. i = Math.max(Math.ceil(pr / LOG_BASE), len) + 2; if (k > i) { k = i; d.length = 1; } // Prepend zeros to equalise exponents. d.reverse(); for (i = k; i--;) d.push(0); d.reverse(); // Base 1e7 exponents equal. } else { // Check digits to determine which is the bigger number. i = xd.length; len = yd.length; xLTy = i < len; if (xLTy) len = i; for (i = 0; i < len; i++) { if (xd[i] != yd[i]) { xLTy = xd[i] < yd[i]; break; } } k = 0; } if (xLTy) { d = xd; xd = yd; yd = d; y.s = -y.s; } len = xd.length; // Append zeros to `xd` if shorter. // Don't add zeros to `yd` if shorter as subtraction only needs to start at `yd` length. for (i = yd.length - len; i > 0; --i) xd[len++] = 0; // Subtract yd from xd. for (i = yd.length; i > k;) { if (xd[--i] < yd[i]) { for (j = i; j && xd[--j] === 0;) xd[j] = BASE - 1; --xd[j]; xd[i] += BASE; } xd[i] -= yd[i]; } // Remove trailing zeros. for (; xd[--len] === 0;) xd.pop(); // Remove leading zeros and adjust exponent accordingly. for (; xd[0] === 0; xd.shift()) --e; // Zero? if (!xd[0]) return new Ctor(rm === 3 ? -0 : 0); y.d = xd; y.e = getBase10Exponent(xd, e); return external ? finalise(y, pr, rm) : y; }
...
var subtract = typed('subtract', {
'number, number': function (x, y) {
return x - y;
},
'Complex, Complex': function (x, y) {
return x.sub(y);
},
'BigNumber, BigNumber': function (x, y) {
return x.minus(y);
},
'Fraction, Fraction': function (x, y) {
...
tan = function () { var pr, rm, x = this, Ctor = x.constructor; if (!x.isFinite()) return new Ctor(NaN); if (x.isZero()) return new Ctor(x); pr = Ctor.precision; rm = Ctor.rounding; Ctor.precision = pr + 10; Ctor.rounding = 1; x = x.sin(); x.s = 1; x = divide(x, new Ctor(1).minus(x.times(x)).sqrt(), pr + 10, 0); Ctor.precision = pr; Ctor.rounding = rm; return finalise(quadrant == 2 || quadrant == 4 ? x.neg() : x, pr, rm, true); }
...
* Syntax:
*
* math.atan(x)
*
* Examples:
*
* math.atan(0.5); // returns number 0.4636476090008061
* math.atan(math.tan(1.5)); // returns number 1.5
*
* math.atan(2); // returns Complex 1.5707963267948966 -1.3169578969248166 i
*
* See also:
*
* tan, asin, acos
*
...
tangent = function () { var pr, rm, x = this, Ctor = x.constructor; if (!x.isFinite()) return new Ctor(NaN); if (x.isZero()) return new Ctor(x); pr = Ctor.precision; rm = Ctor.rounding; Ctor.precision = pr + 10; Ctor.rounding = 1; x = x.sin(); x.s = 1; x = divide(x, new Ctor(1).minus(x.times(x)).sqrt(), pr + 10, 0); Ctor.precision = pr; Ctor.rounding = rm; return finalise(quadrant == 2 || quadrant == 4 ? x.neg() : x, pr, rm, true); }
n/a
tanh = function () { var pr, rm, x = this, Ctor = x.constructor; if (!x.isFinite()) return new Ctor(x.s); if (x.isZero()) return new Ctor(x); pr = Ctor.precision; rm = Ctor.rounding; Ctor.precision = pr + 7; Ctor.rounding = 1; return divide(x.sinh(), x.cosh(), Ctor.precision = pr, Ctor.rounding = rm); }
...
*
* math.coth(x)
*
* Examples:
*
* // coth(x) = 1 / tanh(x)
* math.coth(2); // returns 1.0373147207275482
* 1 / math.tanh(2); // returns 1.0373147207275482
*
* See also:
*
* sinh, tanh, cosh
*
* @param {number | Complex | Unit | Array | Matrix} x Function input
* @return {number | Complex | Array | Matrix} Hyperbolic cotangent of x
...
times = function (y) { var carry, e, i, k, r, rL, t, xdL, ydL, x = this, Ctor = x.constructor, xd = x.d, yd = (y = new Ctor(y)).d; y.s *= x.s; // If either is NaN, ±Infinity or ±0... if (!xd || !xd[0] || !yd || !yd[0]) { return new Ctor(!y.s || xd && !xd[0] && !yd || yd && !yd[0] && !xd // Return NaN if either is NaN. // Return NaN if x is ±0 and y is ±Infinity, or y is ±0 and x is ±Infinity. ? NaN // Return ±Infinity if either is ±Infinity. // Return ±0 if either is ±0. : !xd || !yd ? y.s / 0 : y.s * 0); } e = mathfloor(x.e / LOG_BASE) + mathfloor(y.e / LOG_BASE); xdL = xd.length; ydL = yd.length; // Ensure xd points to the longer array. if (xdL < ydL) { r = xd; xd = yd; yd = r; rL = xdL; xdL = ydL; ydL = rL; } // Initialise the result array with zeros. r = []; rL = xdL + ydL; for (i = rL; i--;) r.push(0); // Multiply! for (i = ydL; --i >= 0;) { carry = 0; for (k = xdL + i; k > i;) { t = r[k] + yd[i] * xd[k - i - 1] + carry; r[k--] = t % BASE | 0; carry = t / BASE | 0; } r[k] = (r[k] + carry) % BASE | 0; } // Remove trailing zeros. for (; !r[--rL];) r.pop(); if (carry) ++e; else r.shift(); y.d = r; y.e = getBase10Exponent(r, e); return external ? finalise(y, Ctor.precision, Ctor.rounding) : y; }
...
},
'Complex': function (x) {
return x.mul(x).mul(x); // Is faster than pow(x, 3)
},
'BigNumber': function (x) {
return x.times(x).times(x);
},
'Fraction': function (x) {
return x.pow(3); // Is faster than mul()mul()mul()
},
'Array | Matrix': function (x) {
...
toBinary = function (sd, rm) { return toStringBinary(this, 2, sd, rm); }
n/a
toDP = function (dp, rm) { var x = this, Ctor = x.constructor; x = new Ctor(x); if (dp === void 0) return x; checkInt32(dp, 0, MAX_DIGITS); if (rm === void 0) rm = Ctor.rounding; else checkInt32(rm, 0, 8); return finalise(x, dp + x.e + 1, rm); }
n/a
toDecimalPlaces = function (dp, rm) { var x = this, Ctor = x.constructor; x = new Ctor(x); if (dp === void 0) return x; checkInt32(dp, 0, MAX_DIGITS); if (rm === void 0) rm = Ctor.rounding; else checkInt32(rm, 0, 8); return finalise(x, dp + x.e + 1, rm); }
...
var _n = n.toNumber();
return x.round(_n);
},
'number, BigNumber': function (x, n) {
if (!n.isInteger()) {throw new TypeError(NO_INT);}
return new type.BigNumber(x).toDecimalPlaces(n.toNumber());
},
'BigNumber': function (x) {
return x.toDecimalPlaces(0);
},
'BigNumber, BigNumber': function (x, n) {
...
toExponential = function (dp, rm) { var str, x = this, Ctor = x.constructor; if (dp === void 0) { str = finiteToString(x, true); } else { checkInt32(dp, 0, MAX_DIGITS); if (rm === void 0) rm = Ctor.rounding; else checkInt32(rm, 0, 8); x = finalise(new Ctor(x), dp + 1, rm); str = finiteToString(x, true, dp + 1); } return x.isNeg() && !x.isZero() ? '-' + str : str; }
...
// handle the various notations
switch (notation) {
case 'fixed':
return exports.toFixed(value, precision);
case 'exponential':
return exports.toExponential(value, precision);
case 'auto':
// determine lower and upper bound for exponential notation.
// TODO: implement support for upper and lower to be BigNumbers themselves
var lower = 1e-3;
var upper = 1e5;
if (options && options.exponential) {
...
toFixed = function (dp, rm) { var str, y, x = this, Ctor = x.constructor; if (dp === void 0) { str = finiteToString(x); } else { checkInt32(dp, 0, MAX_DIGITS); if (rm === void 0) rm = Ctor.rounding; else checkInt32(rm, 0, 8); y = finalise(new Ctor(x), dp + x.e + 1, rm); str = finiteToString(y, false, dp + y.e + 1); } // To determine whether to add the minus sign look at the value before it was rounded, // i.e. look at `x` rather than `y`. return x.isNeg() && !x.isZero() ? '-' + str : str; }
...
* math.format(12.071, {notation: 'fixed'}); // returns '12'
* math.format(2.3, {notation: 'fixed', precision: 2}); // returns '2.30'
* math.format(52.8, {notation: 'exponential'}); // returns '5.28e+1'
* math.format(12400, {notation: 'engineering'}); // returns '12.400e+3'
*
* function formatCurrency(value) {
* // return currency notation with two digits:
* return '$' + value.toFixed(2);
*
* // you could also use math.format inside the callback:
* // return '$' + math.format(value, {notation: 'fixed', precision: 2});
* }
* math.format([2.1, 3, 0.016], formatCurrency}; // returns '[$2.10, $3.00, $0.02]'
*
* See also:
...
toFraction = function (maxD) { var d, d0, d1, d2, e, k, n, n0, n1, pr, q, r, x = this, xd = x.d, Ctor = x.constructor; if (!xd) return new Ctor(x); n1 = d0 = new Ctor(1); d1 = n0 = new Ctor(0); d = new Ctor(d1); e = d.e = getPrecision(xd) - x.e - 1; k = e % LOG_BASE; d.d[0] = mathpow(10, k < 0 ? LOG_BASE + k : k); if (maxD == null) { // d is 10**e, the minimum max-denominator needed. maxD = e > 0 ? d : n1; } else { n = new Ctor(maxD); if (!n.isInt() || n.lt(n1)) throw Error(invalidArgument + n); maxD = n.gt(d) ? (e > 0 ? d : n1) : n; } external = false; n = new Ctor(digitsToString(xd)); pr = Ctor.precision; Ctor.precision = e = xd.length * LOG_BASE * 2; for (;;) { q = divide(n, d, 0, 1, 1); d2 = d0.plus(q.times(d1)); if (d2.cmp(maxD) == 1) break; d0 = d1; d1 = d2; d2 = n1; n1 = n0.plus(q.times(d2)); n0 = d2; d2 = d; d = n.minus(q.times(d2)); n = d2; } d2 = divide(maxD.minus(d0), d1, 0, 1, 1); n0 = n0.plus(d2.times(n1)); d0 = d0.plus(d2.times(d1)); n0.s = n1.s = x.s; // Determine which fraction is closer to x, n0/d0 or n1/d1? r = divide(n1, d1, e, 1).minus(x).abs().cmp(divide(n0, d0, e, 1).minus(x).abs()) < 1 ? [n1, d1] : [n0, d0]; Ctor.precision = pr; external = true; return r; }
n/a
toHex = function (sd, rm) { return toStringBinary(this, 16, sd, rm); }
n/a
toHexadecimal = function (sd, rm) { return toStringBinary(this, 16, sd, rm); }
n/a
toJSON = function () { return { mathjs: 'BigNumber', value: this.toString() }; }
n/a
toNearest = function (y, rm) { var x = this, Ctor = x.constructor; x = new Ctor(x); if (y == null) { // If x is not finite, return x. if (!x.d) return x; y = new Ctor(1); rm = Ctor.rounding; } else { y = new Ctor(y); if (rm !== void 0) checkInt32(rm, 0, 8); // If x is not finite, return x if y is not NaN, else NaN. if (!x.d) return y.s ? x : y; // If y is not finite, return Infinity with the sign of x if y is Infinity, else NaN. if (!y.d) { if (y.s) y.s = x.s; return y; } } // If y is not zero, calculate the nearest multiple of y to x. if (y.d[0]) { external = false; if (rm < 4) rm = [4, 5, 7, 8][rm]; x = divide(x, y, 0, rm, 1).times(y); external = true; finalise(x); // If y is zero, return zero with the sign of x. } else { y.s = x.s; x = y; } return x; }
n/a
toNumber = function () { return +this; }
...
convert: function (x) {
return x + '';
}
}, {
from: 'BigNumber',
to: 'Complex',
convert: function (x) {
return new type.Complex(x.toNumber(), 0);
}
}, {
from: 'Fraction',
to: 'BigNumber',
convert: function (x) {
throw new TypeError('Cannot implicitly convert a Fraction to BigNumber or vice versa. ' +
'Use function bignumber(x) to convert to BigNumber or fraction(x) to convert to Fraction.');
...
toOctal = function (sd, rm) { return toStringBinary(this, 8, sd, rm); }
n/a
toPower = function (y) { var e, k, pr, r, rm, sign, yIsInt, x = this, Ctor = x.constructor, yn = +(y = new Ctor(y)); // Either ±Infinity, NaN or ±0? if (!x.d || !y.d || !x.d[0] || !y.d[0]) return new Ctor(mathpow(+x, yn)); x = new Ctor(x); if (x.eq(1)) return x; pr = Ctor.precision; rm = Ctor.rounding; if (y.eq(1)) return finalise(x, pr, rm); e = mathfloor(y.e / LOG_BASE); k = y.d.length - 1; yIsInt = e >= k; sign = x.s; if (!yIsInt) { if (sign < 0) return new Ctor(NaN); // If y is a small integer use the 'exponentiation by squaring' algorithm. } else if ((k = yn < 0 ? -yn : yn) <= MAX_SAFE_INTEGER) { r = intPow(Ctor, x, k, pr); return y.s < 0 ? new Ctor(1).div(r) : finalise(r, pr, rm); } // Result is negative if x is negative and the last digit of integer y is odd. sign = sign < 0 && y.d[Math.max(e, k)] & 1 ? -1 : 1; // Estimate result exponent. // x^y = 10^e, where e = y * log10(x) // log10(x) = log10(x_significand) + x_exponent // log10(x_significand) = ln(x_significand) / ln(10) k = mathpow(+x, yn); e = k == 0 || !isFinite(k) ? mathfloor(yn * (Math.log('0.' + digitsToString(x.d)) / Math.LN10 + x.e + 1)) : new Ctor(k + '').e; // Estimate may be incorrect e.g. x: 0.999999999999999999, y: 2.29, e: 0, r.e: -1. // Overflow/underflow? if (e > Ctor.maxE + 1 || e < Ctor.minE - 1) return new Ctor(e > 0 ? sign / 0 : 0); external = false; Ctor.rounding = x.s = 1; // Estimate the extra guard digits needed to ensure five correct rounding digits from // naturalLogarithm(x). Example of failure without these extra digits (precision: 10): // new Decimal(2.32456).pow('2087987436534566.46411') // should be 1.162377823e+764914905173815, but is 1.162355823e+764914905173815 k = Math.min(12, (e + '').length); // r = x^y = exp(y*ln(x)) r = naturalExponential(y.times(naturalLogarithm(x, pr + k)), pr); // Truncate to the required precision plus five rounding digits. r = finalise(r, pr + 5, 1); // If the rounding digits are [49]9999 or [50]0000 increase the precision by 10 and recalculate // the result. if (checkRoundingDigits(r.d, pr, rm)) { e = pr + 10; // Truncate to the increased precision plus five rounding digits. r = finalise(naturalExponential(y.times(naturalLogarithm(x, e + k)), e), e + 5, 1); // Check for 14 nines from the 2nd rounding digit (the first rounding digit may be 4 or 9). if (+digitsToString(r.d).slice(pr + 1, pr + 15) + 1 == 1e14) { r = finalise(r, pr + 1, 0); } } r.s = sign; external = true; Ctor.rounding = rm; return finalise(r, pr, rm); }
n/a
toPrecision = function (sd, rm) { var str, x = this, Ctor = x.constructor; if (sd === void 0) { str = finiteToString(x, x.e <= Ctor.toExpNeg || x.e >= Ctor.toExpPos); } else { checkInt32(sd, 1, MAX_DIGITS); if (rm === void 0) rm = Ctor.rounding; else checkInt32(rm, 0, 8); x = finalise(new Ctor(x), sd, rm); str = finiteToString(x, sd <= x.e || x.e <= Ctor.toExpNeg, sd); } return x.isNeg() && !x.isZero() ? '-' + str : str; }
...
return inv ? zero : a;
}
var x = a.abs().pow(one.div(root));
// If a < 0, we require that root is an odd integer,
// so (-1) ^ (1/root) = -1
x = a.isNeg() ? x.neg() : x;
return new type.BigNumber((inv ? one.div(x) : x).toPrecision(precision));
}
}
/**
* Calculate the nth root of a, solve x^root == a
* http://rosettacode.org/wiki/Nth_root#JavaScript
* @param {number} a
...
toSD = function (sd, rm) { var x = this, Ctor = x.constructor; if (sd === void 0) { sd = Ctor.precision; rm = Ctor.rounding; } else { checkInt32(sd, 1, MAX_DIGITS); if (rm === void 0) rm = Ctor.rounding; else checkInt32(rm, 0, 8); } return finalise(new Ctor(x), sd, rm); }
n/a
toSignificantDigits = function (sd, rm) { var x = this, Ctor = x.constructor; if (sd === void 0) { sd = Ctor.precision; rm = Ctor.rounding; } else { checkInt32(sd, 1, MAX_DIGITS); if (rm === void 0) rm = Ctor.rounding; else checkInt32(rm, 0, 8); } return finalise(new Ctor(x), sd, rm); }
...
if (value.isZero()) return '0';
// determine whether or not to output exponential notation
var str;
var abs = value.abs();
if (abs.gte(lower) && abs.lt(upper)) {
// normal number notation
str = value.toSignificantDigits(precision).toFixed();
}
else {
// exponential notation
str = exports.toExponential(value, precision);
}
// remove trailing zeros after the decimal point
...
toString = function () { var x = this, Ctor = x.constructor, str = finiteToString(x, x.e <= Ctor.toExpNeg || x.e >= Ctor.toExpPos); return x.isNeg() && !x.isZero() ? '-' + str : str; }
...
}
else {
scope.ans = res;
console.log(format(res));
}
}
else if (res instanceof math.type.Help) {
console.log(res.toString());
}
else {
scope.ans = res;
console.log(format(res));
}
}
}
...
trunc = function () { return finalise(new this.constructor(this), this.e + 1, 1); }
n/a
truncated = function () { return finalise(new this.constructor(this), this.e + 1, 1); }
n/a
valueOf = function () { var x = this, Ctor = x.constructor, str = finiteToString(x, x.e <= Ctor.toExpNeg || x.e >= Ctor.toExpPos); return x.isNeg() ? '-' + str : str; }
...
throw new TypeError('Cannot implicitly convert a Fraction to BigNumber or vice versa. ' +
'Use function bignumber(x) to convert to BigNumber or fraction(x) to convert to Fraction.');
}
}, {
from: 'Fraction',
to: 'Complex',
convert: function (x) {
return new type.Complex(x.valueOf(), 0);
}
}, {
from: 'number',
to: 'Fraction',
convert: function (x) {
if (digits(x) > 15) {
throw new TypeError('Cannot implicitly convert a number with >15 significant digits to Fraction ' +
...
function Chain(value) { if (!(this instanceof Chain)) { throw new SyntaxError('Constructor must be called with the new operator'); } if (value && value.isChain) { this.value = value.value; } else { this.value = value; } }
n/a
createProxy = function (arg0, arg1) { if (typeof arg0 === 'string') { // createProxy(name, value) createProxy(arg0, arg1); } else { // createProxy(values) for (var prop in arg0) { if (arg0.hasOwnProperty(prop)) { createProxy(prop, arg0[prop]); } } } }
...
}
}
/**
* Create a proxy for a single method, or an object with multiple methods.
* Example usage:
*
* Chain.createProxy('add', function add (x, y) {...});
* Chain.createProxy({
* add: function add (x, y) {...},
* subtract: function subtract (x, y) {...}
* }
*
* @param {string | Object} arg0 A name (string), or an object with
* functions
...
abs = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
function factory (type, config, load, typed) {
/**
* Calculate the absolute value of a number. For matrices, the function is
* evaluated element wise.
*
* Syntax:
*
* math.abs(x)
*
* Examples:
*
* math.abs(3.5); // returns number 3.5
* math.abs(-4.2); // returns number 4.2
*
* math.abs([3, -5, -1, 0, 2]); // returns Array [3, 5, 1, 0, 2]
...
acos = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
/**
* Calculate the inverse cosine of a value.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.acos(x)
*
* Examples:
*
* math.acos(0.5); // returns number 1.0471975511965979
* math.acos(math.cos(1.5)); // returns number 1.5
*
* math.acos(2); // returns Complex 0 + 1.3169578969248166 i
...
acosh = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
* Calculate the hyperbolic arccos of a value,
* defined as `acosh(x) = ln(sqrt(x^2 - 1) + x)`.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.acosh(x)
*
* Examples:
*
* math.acosh(1.5); // returns 0.9624236501192069
*
* See also:
*
...
acot = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
/**
* Calculate the inverse cotangent of a value, defined as `acot(x) = atan(1/x)`.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.acot(x)
*
* Examples:
*
* math.acot(0.5); // returns number 0.4636476090008061
* math.acot(math.cot(1.5)); // returns number 1.5
*
* math.acot(2); // returns Complex 1.5707963267948966 -1.3169578969248166 i
...
acoth = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
* Calculate the hyperbolic arccotangent of a value,
* defined as `acoth(x) = atanh(1/x) = (ln((x+1)/x) + ln(x/(x-1))) / 2`.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.acoth(x)
*
* Examples:
*
* math.acoth(0.5); // returns 0.8047189562170503
*
* See also:
*
...
acsc = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
/**
* Calculate the inverse cosecant of a value, defined as `acsc(x) = asin(1/x)`.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.acsc(x)
*
* Examples:
*
* math.acsc(0.5); // returns number 0.5235987755982989
* math.acsc(math.csc(1.5)); // returns number ~1.5
*
* math.acsc(2); // returns Complex 1.5707963267948966 -1.3169578969248166 i
...
acsch = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
* Calculate the hyperbolic arccosecant of a value,
* defined as `acsch(x) = asinh(1/x) = ln(1/x + sqrt(1/x^2 + 1))`.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.acsch(x)
*
* Examples:
*
* math.acsch(0.5); // returns 1.4436354751788103
*
* See also:
*
...
add = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
math.eval('5.08 cm to inch'); // 2 inch
math.eval('sin(45 deg) ^ 2'); // 0.5
math.eval('9 / 3 + 2i'); // 3 + 2i
math.eval('det([-1, 2; 3, 1])'); // -7
// chaining
math.chain(3)
.add(4)
.multiply(2)
.done(); // 14
```
## Browser support
Math.js works on any ES5 compatible JavaScript engine: node.js 0.10, and Internet Explorer 9 and newer, and all other browsers (
Chrome, Firefox, Safari). If support for old browsers like Internet Explorer 8 is required, the [es5-shim](https://github.com/kriskowal
/es5-shim) library has to be loaded.
...
and = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
/**
* Logical `and`. Test whether two values are both defined with a nonzero/nonempty value.
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.and(x, y)
*
* Examples:
*
* math.and(2, 4); // returns true
*
* a = [2, 0, 0];
* b = [3, 7, 0];
...
arg = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
* the principal root is returned.
* @returns {Complex | Array.<Complex> | Matrix.<Complex>} Returns the cubic root(s) of x
* @private
*/
function _cbrtComplex(x, allRoots) {
// https://www.wikiwand.com/en/Cube_root#/Complex_numbers
var arg_3 = x.arg() / 3;
var abs = x.abs();
// principal root:
var principal = new type.Complex(_cbrtNumber(abs), 0).mul(
new type.Complex(0, arg_3).exp());
if (allRoots) {
...
asec = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
/**
* Calculate the inverse secant of a value. Defined as `asec(x) = acos(1/x)`.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.asec(x)
*
* Examples:
*
* math.asec(0.5); // returns 1.0471975511965979
* math.asec(math.sec(1.5)); // returns 1.5
*
* math.asec(2); // returns 0 + 1.3169578969248166 i
...
asech = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
* Calculate the hyperbolic arcsecant of a value,
* defined as `asech(x) = acosh(1/x) = ln(sqrt(1/x^2 - 1) + 1/x)`.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.asech(x)
*
* Examples:
*
* math.asech(0.5); // returns 1.3169578969248166
*
* See also:
*
...
asin = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
*
* @param {number | Complex | Array | Matrix} x Function input
* @return {number | Complex | Array | Matrix} The arc cosecant of x
*/
var acsc = typed('acsc', {
'number': function (x) {
if (x <= -1 || x >= 1 || config.predictable) {
return Math.asin(1 / x);
}
return new type.Complex(x, 0).acsc();
},
'Complex': function (x) {
return x.acsc();
},
...
asinh = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
},
'Complex': function (x) {
return x.acsch();
},
'BigNumber': function (x) {
return new type.BigNumber(1).div(x).asinh();
},
'Array | Matrix': function (x) {
return deepMap(x, acsch);
}
});
...
atan = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
* cot, atan
*
* @param {number | Complex | Array | Matrix} x Function input
* @return {number | Complex | Array | Matrix} The arc cotangent of x
*/
var acot = typed('acot', {
'number': function (x) {
return Math.atan(1 / x);
},
'Complex': function (x) {
return x.acot();
},
'BigNumber': function (x) {
...
atan2 = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
```js
// load math.js
var math = require('mathjs');
// functions and constants
math.round(math.e, 3); // 2.718
math.atan2(3, -3) / math.pi; // 0.75
math.log(1000, 10); // 3
math.sqrt(-4); // 2i
math.pow([[-1, 2], [3, 1]], 2); // [[7, 0], [0, 7]]
math.derivative('x^2 + x', 'x'); // 2 * x + 1
// expressions
math.eval('12 / (2.3 + 0.7)'); // 4
...
atanh = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
},
'Complex': function (x) {
return x.acoth();
},
'BigNumber': function (x) {
return new type.BigNumber(1).div(x).atanh();
},
'Array | Matrix': function (x) {
return deepMap(x, acoth);
}
});
...
bellNumbers = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
/**
* The Bell Numbers count the number of partitions of a set. A partition is a pairwise disjoint subset of S whose union is S.
* bellNumbers only takes integer arguments.
* The following condition must be enforced: n >= 0
*
* Syntax:
*
* math.bellNumbers(n)
*
* Examples:
*
* math.bellNumbers(3); // returns 5;
* math.bellNumbers(8); // returns 4140;
*
* See also:
...
bignumber = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
*/
ConstantNode.prototype._compile = function (defs, args) {
switch (this.valueType) {
case 'number':
// TODO: replace this with using config.number
var numConfig = defs.math.config().number;
if (numConfig === 'BigNumber') {
return 'math.bignumber("' + this.value + '")';
}
else if (numConfig === 'Fraction') {
return 'math.fraction("' + this.value + '")';
}
else {
// remove leading zeros like '003.2' which are not allowed by JavaScript
return this.value.replace(/^(0*)[0-9]/, function (match, zeros) {
...
bitAnd = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
/**
* Bitwise AND two values, `x & y`.
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.bitAnd(x, y)
*
* Examples:
*
* math.bitAnd(53, 131); // returns number 1
*
* math.bitAnd([1, 12, 31], 42); // returns Array [0, 8, 10]
*
...
bitNot = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
/**
* Bitwise NOT value, `~x`.
* For matrices, the function is evaluated element wise.
* For units, the function is evaluated on the best prefix base.
*
* Syntax:
*
* math.bitNot(x)
*
* Examples:
*
* math.bitNot(1); // returns number -2
*
* math.bitNot([2, -3, 4]); // returns Array [-3, 2, 5]
*
...
bitOr = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
/**
* Bitwise OR two values, `x | y`.
* For matrices, the function is evaluated element wise.
* For units, the function is evaluated on the lowest print base.
*
* Syntax:
*
* math.bitOr(x, y)
*
* Examples:
*
* math.bitOr(1, 2); // returns number 3
*
* math.bitOr([1, 2, 3], 4); // returns Array [5, 6, 7]
*
...
bitXor = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
/**
* Bitwise XOR two values, `x ^ y`.
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.bitXor(x, y)
*
* Examples:
*
* math.bitXor(1, 2); // returns number 3
*
* math.bitXor([2, 3, 4], 4); // returns Array [6, 7, 0]
*
...
boolean = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
* In case of a number, `true` is returned for non-zero numbers, and `false` in
* case of zero.
* Strings can be `'true'` or `'false'`, or can contain a number.
* When value is a matrix, all elements will be converted to boolean.
*
* Syntax:
*
* math.boolean(x)
*
* Examples:
*
* math.boolean(0); // returns false
* math.boolean(1); // returns true
* math.boolean(-3); // returns true
* math.boolean('true'); // returns true
...
catalan = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
/**
* The Catalan Numbers enumerate combinatorial structures of many different types.
* catalan only takes integer arguments.
* The following condition must be enforced: n >= 0
*
* Syntax:
*
* math.catalan(n)
*
* Examples:
*
* math.catalan(3); // returns 5;
* math.catalan(8); // returns 1430;
*
* See also:
...
cbrt = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
/**
* Calculate the cubic root of a value.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.cbrt(x)
* math.cbrt(x, allRoots)
*
* Examples:
*
* math.cbrt(27); // returns 3
* math.cube(3); // returns 27
* math.cbrt(-64); // returns -4
...
ceil = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
/**
* Round a value towards plus infinity
* If `x` is complex, both real and imaginary part are rounded towards plus infinity.
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.ceil(x)
*
* Examples:
*
* math.ceil(3.2); // returns number 4
* math.ceil(3.8); // returns number 4
* math.ceil(-4.2); // returns number -4
* math.ceil(-4.7); // returns number -4
...
chain = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
math.eval('12 / (2.3 + 0.7)'); // 4
math.eval('5.08 cm to inch'); // 2 inch
math.eval('sin(45 deg) ^ 2'); // 0.5
math.eval('9 / 3 + 2i'); // 3 + 2i
math.eval('det([-1, 2; 3, 1])'); // -7
// chaining
math.chain(3)
.add(4)
.multiply(2)
.done(); // 14
```
## Browser support
...
clone = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
return desc;
};
/**
* Export the help object to JSON
*/
Help.prototype.toJSON = function () {
var obj = object.clone(this.doc);
obj.mathjs = 'Help';
return obj;
};
/**
* Instantiate a Help object from a JSON object
* @param {Object} json
...
combinations = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
* possibilities.
*
* Combinations only takes integer arguments.
* The following condition must be enforced: k <= n.
*
* Syntax:
*
* math.combinations(n, k)
*
* Examples:
*
* math.combinations(7, 5); // returns 21
*
* See also:
*
...
compare = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
* is smaller than the configured epsilon. The function cannot be used to
* compare values smaller than approximately 2.22e-16.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.compare(x, y)
*
* Examples:
*
* math.compare(6, 1); // returns 1
* math.compare(2, 3); // returns -1
* math.compare(7, 7); // returns 0
*
...
compile = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
* parse(expr, options)
* parse([expr1, expr2, expr3, ...])
* parse([expr1, expr2, expr3, ...], options)
*
* Example:
*
* var node = parse('sqrt(3^2 + 4^2)');
* node.compile(math).eval(); // 5
*
* var scope = {a:3, b:4}
* var node = parse('a * b'); // 12
* var code = node.compile(math);
* code.eval(scope); // 12
* scope.a = 5;
* code.eval(scope); // 20
...
complex = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
* Syntax:
*
* math.string(value)
*
* Examples:
*
* math.string(4.2); // returns string '4.2'
* math.string(math.complex(3, 2); // returns string '3 + 2i'
*
* var u = math.unit(5, 'km');
* math.string(u.to('m')); // returns string '5000 m'
*
* math.string([true, false]); // returns ['true', 'false']
*
* See also:
...
composition = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
* The composition counts of n into k parts.
*
* composition only takes integer arguments.
* The following condition must be enforced: k <= n.
*
* Syntax:
*
* math.composition(n, k)
*
* Examples:
*
* math.composition(5, 3); // returns 6
*
* See also:
*
...
concat = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
// figure out what number of arguments the callback function expects
var args = maxArgumentCount(callback);
var recurse = function (value, index) {
if (Array.isArray(value)) {
value.forEach(function (child, i) {
// we create a copy of the index array and append the new index value
recurse(child, index.concat(i + 1)); // one based index, hence i+1
});
}
else {
// invoke the callback function with the right number of arguments
if (args === 1) {
callback(value);
}
...
config = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
/**
* Set configuration options for math.js, and get current options.
* Will emit a 'config' event, with arguments (curr, prev, changes).
*
* Syntax:
*
* math.config(config: Object): Object
*
* Examples:
*
* math.config().number; // outputs 'number'
* math.eval('0.4'); // outputs number 0.4
* math.config({number: 'Fraction'});
* math.eval('0.4'); // outputs Fraction 2/5
...
conj = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
* Compute the complex conjugate of a complex value.
* If `x = a+bi`, the complex conjugate of `x` is `a - bi`.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.conj(x)
*
* Examples:
*
* math.conj(math.complex('2 + 3i')); // returns Complex 2 - 3i
* math.conj(math.complex('2 - 3i')); // returns Complex 2 + 3i
* math.conj(math.complex('-5.2i')); // returns Complex 5.2i
*
...
cos = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
var u1, u2,
picked = -1;
// We reject values outside of the interval [0, 1]
// TODO: check if it is ok to do that?
while (picked < 0 || picked > 1) {
u1 = rng();
u2 = rng();
picked = 1/6 * Math.pow(-2 * Math.log(u1), 0.5) * Math.cos(2 * Math.PI * u2) +
0.5;
}
return picked;
}
}
};
distribution.toTex = undefined; // use default template
...
cosh = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
* Calculate the hyperbolic cosine of a value,
* defined as `cosh(x) = 1/2 * (exp(x) + exp(-x))`.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.cosh(x)
*
* Examples:
*
* math.cosh(0.5); // returns number 1.1276259652063807
*
* See also:
*
...
cot = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
* Syntax:
*
* math.acot(x)
*
* Examples:
*
* math.acot(0.5); // returns number 0.4636476090008061
* math.acot(math.cot(1.5)); // returns number 1.5
*
* math.acot(2); // returns Complex 1.5707963267948966 -1.3169578969248166 i
*
* See also:
*
* cot, atan
*
...
coth = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
* Calculate the hyperbolic cotangent of a value,
* defined as `coth(x) = 1 / tanh(x)`.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.coth(x)
*
* Examples:
*
* // coth(x) = 1 / tanh(x)
* math.coth(2); // returns 1.0373147207275482
* 1 / math.tanh(2); // returns 1.0373147207275482
*
...
create = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
* false (default), output type can vary depending
* on input values. For example `math.sqrt(-4)`
* returns `complex('2i')` when predictable is false, and
* returns `NaN` when true.
*/
function create (config) {
// create a new math.js instance
var math = core.create(config);
math.create = create;
// import data types, functions, constants, expression parser, etc.
math['import'](require('./lib'));
return math;
}
...
createUnit = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
n/a
cross = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
* ]
*
* If one of the input vectors has a dimension greater than 1, the output
* vector will be a 1x3 (2-dimensional) matrix.
*
* Syntax:
*
* math.cross(x, y)
*
* Examples:
*
* math.cross([1, 1, 0], [0, 1, 1]); // Returns [1, -1, 1]
* math.cross([3, -3, 1], [4, 9, 2]); // Returns [-15, -2, 39]
* math.cross([2, 3, 4], [5, 6, 7]); // Returns [-3, 6, -3]
* math.cross([[1, 2, 3]], [[4], [5], [6]]); // Returns [[-3, 6, -3]]
...
csc = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
* Syntax:
*
* math.acsc(x)
*
* Examples:
*
* math.acsc(0.5); // returns number 0.5235987755982989
* math.acsc(math.csc(1.5)); // returns number ~1.5
*
* math.acsc(2); // returns Complex 1.5707963267948966 -1.3169578969248166 i
*
* See also:
*
* csc, asin, asec
*
...
csch = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
* Calculate the hyperbolic cosecant of a value,
* defined as `csch(x) = 1 / sinh(x)`.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.csch(x)
*
* Examples:
*
* // csch(x) = 1/ sinh(x)
* math.csch(0.5); // returns 1.9190347513349437
* 1 / math.sinh(0.5); // returns 1.9190347513349437
*
...
cube = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
*
* math.cbrt(x)
* math.cbrt(x, allRoots)
*
* Examples:
*
* math.cbrt(27); // returns 3
* math.cube(3); // returns 27
* math.cbrt(-64); // returns -4
* math.cbrt(math.unit('27 m^3')); // returns Unit 3 m
* math.cbrt([27, 64, 125]); // returns [3, 4, 5]
*
* var x = math.complex('8i');
* math.cbrt(x); // returns Complex 1.7320508075689 + i
* math.cbrt(x, true); // returns Matrix [
...
deepEqual = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
}
if (a.length != b.length) {
return false;
}
for (i = 0, len = a.length; i < len; i++) {
if (!exports.deepEqual(a[i], b[i])) {
return false;
}
}
return true;
}
else if (a instanceof Object) {
if (Array.isArray(b) || !(b instanceof Object)) {
...
derivative = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
// functions and constants
math.round(math.e, 3); // 2.718
math.atan2(3, -3) / math.pi; // 0.75
math.log(1000, 10); // 3
math.sqrt(-4); // 2i
math.pow([[-1, 2], [3, 1]], 2); // [[7, 0], [0, 7]]
math.derivative('x^2 + x', 'x'); // 2 * x + 1
// expressions
math.eval('12 / (2.3 + 0.7)'); // 4
math.eval('5.08 cm to inch'); // 2 inch
math.eval('sin(45 deg) ^ 2'); // 0.5
math.eval('9 / 3 + 2i'); // 3 + 2i
math.eval('det([-1, 2; 3, 1])'); // -7
...
det = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
var unaryMinus = load(require('../arithmetic/unaryMinus'));
/**
* Calculate the determinant of a matrix.
*
* Syntax:
*
* math.det(x)
*
* Examples:
*
* math.det([[1, 2], [3, 4]]); // returns -2
*
* var A = [
* [-2, 2, 3],
...
diag = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
* When `x` is a vector, a matrix with vector `x` on the diagonal will be returned.
* When `x` is a two dimensional matrix, the matrixes `k`th diagonal will be returned as vector.
* When k is positive, the values are placed on the super diagonal.
* When k is negative, the values are placed on the sub diagonal.
*
* Syntax:
*
* math.diag(X)
* math.diag(X, format)
* math.diag(X, k)
* math.diag(X, k, format)
*
* Examples:
*
* // create a diagonal matrix
...
distance = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
* Distance between point and a line in 2 and 3 dimensional spaces.
* Pairwise distance between a set of 2D or 3D points
* NOTE:
* When substituting coefficients of a line(a, b and c), use ax + by + c = 0 instead of ax + by = c
* For parametric equation of a 3D line, x0, y0, z0, a, b, c are from: (x−x0, y−y0, z−z0) = t(a, b, c)
*
* Syntax:
* math.distance([x1, y1], [x2, y2])
*- math.distance({pointOneX: 4, pointOneY: 5}, {pointTwoX: 2, pointTwoY: 7})
* math.distance([x1, y1, z1], [x2, y2, z2])
* math.distance({pointOneX: 4, pointOneY: 5, pointOneZ: 8}, {pointTwoX: 2, pointTwoY: 7, pointTwoZ: 9})
* math.distance([[A], [B], [C]...])
* math.distance([x1, y1], [LinePtX1, LinePtY1], [LinePtX2, LinePtY2])
* math.distance({pointX: 1, pointY: 4}, {lineOnePtX: 6, lineOnePtY: 3}, {lineTwoPtX: 2, lineTwoPtY: 8})
* math.distance([x1, y1, z1], [LinePtX1, LinePtY1, LinePtZ1], [LinePtX2, LinePtY2, LinePtZ2])
...
divide = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
/**
* Divide two values, `x / y`.
* To divide matrices, `x` is multiplied with the inverse of `y`: `x * inv(y)`.
*
* Syntax:
*
* math.divide(x, y)
*
* Examples:
*
* math.divide(2, 3); // returns number 0.6666666666666666
*
* var a = math.complex(5, 14);
* var b = math.complex(4, 1);
...
done = function () { return this.value; }
...
math.eval('9 / 3 + 2i'); // 3 + 2i
math.eval('det([-1, 2; 3, 1])'); // -7
// chaining
math.chain(3)
.add(4)
.multiply(2)
.done(); // 14
```
## Browser support
Math.js works on any ES5 compatible JavaScript engine: node.js 0.10, and Internet Explorer 9 and newer, and all other browsers (
Chrome, Firefox, Safari). If support for old browsers like Internet Explorer 8 is required, the [es5-shim](https://github.com/kriskowal
/es5-shim) library has to be loaded.
...
dot = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
* Calculate the dot product of two vectors. The dot product of
* `A = [a1, a2, a3, ..., an]` and `B = [b1, b2, b3, ..., bn]` is defined as:
*
* dot(A, B) = a1 * b1 + a2 * b2 + a3 * b3 + ... + an * bn
*
* Syntax:
*
* math.dot(x, y)
*
* Examples:
*
* math.dot([2, 4, 1], [2, 2, 3]); // returns number 15
* math.multiply([2, 4, 1], [2, 2, 3]); // returns number 15
*
* See also:
...
dotDivide = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
/**
* Divide two matrices element wise. The function accepts both matrices and
* scalar values.
*
* Syntax:
*
* math.dotDivide(x, y)
*
* Examples:
*
* math.dotDivide(2, 4); // returns 0.5
*
* a = [[9, 5], [6, 1]];
* b = [[3, 2], [5, 2]];
...
dotMultiply = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
/**
* Multiply two matrices element wise. The function accepts both matrices and
* scalar values.
*
* Syntax:
*
* math.dotMultiply(x, y)
*
* Examples:
*
* math.dotMultiply(2, 4); // returns 8
*
* a = [[9, 5], [6, 1]];
* b = [[3, 2], [5, 2]];
...
dotPow = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
var algorithm14 = load(require('../../type/matrix/utils/algorithm14'));
/**
* Calculates the power of x to y element wise.
*
* Syntax:
*
* math.dotPow(x, y)
*
* Examples:
*
* math.dotPow(2, 3); // returns number 8
*
* var a = [[1, 2], [4, 3]];
* math.dotPow(a, 2); // returns Array [[1, 4], [16, 9]]
...
emit = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
object.deepExtend(config, options);
var curr = object.clone(config);
var changes = object.clone(options);
// emit 'config' event
math.emit('config', curr, prev, changes);
return curr;
}
else {
return object.clone(config);
}
}
...
equal = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
*
* math.deepEqual(2, 4); // returns false
*
* a = [2, 5, 1];
* b = [2, 7, 1];
*
* math.deepEqual(a, b); // returns false
* math.equal(a, b); // returns [true, false, true]
*
* See also:
*
* equal, unequal
*
* @param {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} x First matrix to compare
* @param {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} y Second matrix to compare
...
erf = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
* "Rational Chebyshev Approximations for the Error Function" by W. J. Cody
* for an explanation of this process.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.erf(x)
*
* Examples:
*
* math.erf(0.2); // returns 0.22270258921047847
* math.erf(-0.5); // returns -0.5204998778130465
* math.erf(4); // returns 0.9999999845827421
*
...
eval = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
math.atan2(3, -3) / math.pi; // 0.75
math.log(1000, 10); // 3
math.sqrt(-4); // 2i
math.pow([[-1, 2], [3, 1]], 2); // [[7, 0], [0, 7]]
math.derivative('x^2 + x', 'x'); // 2 * x + 1
// expressions
math.eval('12 / (2.3 + 0.7)'); // 4
math.eval('5.08 cm to inch'); // 2 inch
math.eval('sin(45 deg) ^ 2'); // 0.5
math.eval('9 / 3 + 2i'); // 3 + 2i
math.eval('det([-1, 2; 3, 1])'); // -7
// chaining
math.chain(3)
...
exp = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
// https://www.wikiwand.com/en/Cube_root#/Complex_numbers
var arg_3 = x.arg() / 3;
var abs = x.abs();
// principal root:
var principal = new type.Complex(_cbrtNumber(abs), 0).mul(
new type.Complex(0, arg_3).exp());
if (allRoots) {
var all = [
principal,
new type.Complex(_cbrtNumber(abs), 0).mul(
new type.Complex(0, arg_3 + Math.PI * 2 / 3).exp()),
new type.Complex(_cbrtNumber(abs), 0).mul(
...
eye = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
/**
* Create a 2-dimensional identity matrix with size m x n or n x n.
* The matrix has ones on the diagonal and zeros elsewhere.
*
* Syntax:
*
* math.eye(n)
* math.eye(n, format)
* math.eye(m, n)
* math.eye(m, n, format)
* math.eye([m, n])
* math.eye([m, n], format)
*
* Examples:
...
factorial = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
* Compute the factorial of a value
*
* Factorial only supports an integer value as argument.
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.factorial(n)
*
* Examples:
*
* math.factorial(5); // returns 120
* math.factorial(3); // returns 6
*
* See also:
...
filter = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
}
}
}
}
}
// remove duplicates
matches = matches.filter(function(elem, pos, arr) {
return arr.indexOf(elem) == pos;
});
}
return [matches, keyword];
}
...
fix = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
function factory (type, config, load, typed) {
/**
* Round a value towards zero.
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.fix(x)
*
* Examples:
*
* math.fix(3.2); // returns number 3
* math.fix(3.8); // returns number 3
* math.fix(-4.2); // returns number -4
* math.fix(-4.7); // returns number -4
...
flatten = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
* @returns {Array} Array whose data has been formatted to fit the
* specified dimensions
*
* @throws {DimensionError} If the product of the new dimension sizes does
* not equal that of the old ones
*/
exports.reshape = function(array, sizes) {
var flatArray = exports.flatten(array);
var newArray;
var product = function (arr) {
return arr.reduce(function (prev, curr) {
return prev * curr;
});
};
...
floor = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
* ceil, floor, round
*
* @param {number | BigNumber | Fraction | Complex | Array | Matrix} x Number to be rounded
* @return {number | BigNumber | Fraction | Complex | Array | Matrix} Rounded value
*/
var fix = typed('fix', {
'number': function (x) {
return (x > 0) ? Math.floor(x) : Math.ceil(x);
},
'Complex': function (x) {
return new type.Complex(
(x.re > 0) ? Math.floor(x.re) : Math.ceil(x.re),
(x.im > 0) ? Math.floor(x.im) : Math.ceil(x.im)
);
...
forEach = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
if (def.indexOf(keyword) == 0) {
matches.push(def);
}
}
}
// commandline keywords
['exit', 'quit', 'clear'].forEach(function (cmd) {
if (cmd.indexOf(keyword) == 0) {
matches.push(cmd);
}
});
// math functions and constants
var ignore = ['expr', 'type'];
...
format = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
* Helper function to format a value. Regular numbers will be rounded
* to 14 digits to prevent round-off errors from showing up.
* @param {*} value
*/
function format(value) {
var math = getMath();
return math.format(value, {
fn: function (value) {
if (typeof value === 'number') {
// round numbers
return math.format(value, PRECISION);
}
else {
return math.format(value);
...
fraction = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
case 'number':
// TODO: replace this with using config.number
var numConfig = defs.math.config().number;
if (numConfig === 'BigNumber') {
return 'math.bignumber("' + this.value + '")';
}
else if (numConfig === 'Fraction') {
return 'math.fraction("' + this.value + '")';
}
else {
// remove leading zeros like '003.2' which are not allowed by JavaScript
return this.value.replace(/^(0*)[0-9]/, function (match, zeros) {
return match.substring(zeros.length);
});
}
...
gamma = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
* Compute the gamma function of a value using Lanczos approximation for
* small values, and an extended Stirling approximation for large values.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.gamma(n)
*
* Examples:
*
* math.gamma(5); // returns 24
* math.gamma(-0.5); // returns -3.5449077018110335
* math.gamma(math.i); // returns -0.15494982830180973 - 0.49801566811835596i
*
...
gcd = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
/**
* Calculate the greatest common divisor for two or more values or arrays.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.gcd(a, b)
* math.gcd(a, b, c, ...)
*
* Examples:
*
* math.gcd(8, 12); // returns 4
* math.gcd(-4, 6); // returns 2
* math.gcd(25, 15, -10); // returns 5
...
help = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
* Object | `'Object'` | `math.typeof ({a: 2, b: 3})`
* RegExp | `'RegExp'` | `math.typeof (/a regexp/)`
* undefined | `'undefined'` | `math.typeof(undefined)`
* math.type.BigNumber | `'BigNumber'` | `math.typeof (math.bignumber('2.3e500'))`
* math.type.Chain | `'Chain'` | `math.typeof (math.chain(2))`
* math.type.Complex | `'Complex'` | `math.typeof (math.complex(2, 3))`
* math.type.Fraction | `'Fraction'` | `math.typeof (math.fraction(1, 3))`
* math.type.Help | `'Help'` | `math.typeof (math.help('sqrt
'))`
* math.type.Index | `'Index'` | `math.typeof (math.index(1, 3))`
* math.type.Matrix | `'Matrix'` | `math.typeof (math.matrix([[1,2], [3, 4]]))`
* math.type.Range | `'Range'` | `math.typeof (math.range(0, 10))`
* math.type.Unit | `'Unit'` | `math.typeof (math.unit('45 deg'))`
*
* Syntax:
*
...
hypot = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
*
* hypot(a, b, c, ...) = sqrt(a^2 + b^2 + c^2 + ...)
*
* For matrix input, the hypotenusa is calculated for all values in the matrix.
*
* Syntax:
*
* math.hypot(a, b, ...)
* math.hypot([a, b, c, ...])
*
* Examples:
*
* math.hypot(3, 4); // 5
* math.hypot(3, 4, 5); // 7.0710678118654755
* math.hypot([3, 4, 5]); // 7.0710678118654755
...
im = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
* Get the imaginary part of a complex number.
* For a complex number `a + bi`, the function returns `b`.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.im(x)
*
* Examples:
*
* var a = math.complex(2, 3);
* math.re(a); // returns number 2
* math.im(a); // returns number 3
*
...
import = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
function factory (type, config, load, typed, math) {
/**
* Import functions from an object or a module
*
* Syntax:
*
* math.import(object)
* math.import(object, options)
*
* Where:
*
* - `object: Object`
* An object with functions to be imported.
* - `options: Object` An object with import options. Available options:
...
index = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
'})()'
}
else { // ConstantNode
return range._compile(defs, childArgs);
}
});
return 'math.index(' + dimensions.join(', ') + ')';
};
/**
* Execute a callback for each of the child nodes of this node
* @param {function(child: Node, path: string, parent: Node)} callback
*/
IndexNode.prototype.forEach = function (callback) {
...
intersect = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
* arrays or 1 dimensional matrices. The line intersection functions return null
* if the lines do not meet.
*
* Note: Fill the plane coefficients as `x + y + z = c` and not as `x + y + z + c = 0`.
*
* Syntax:
*
* math.intersect(endPoint1Line1, endPoint2Line1, endPoint1Line2, endPoint2Line2)
* math.intersect(endPoint1, endPoint2, planeCoefficients)
*
* Examples:
*
* math.intersect([0, 0], [10, 10], [10, 0], [0, 10]); // Returns [5, 5]
* math.intersect([0, 0, 0], [10, 10, 0], [10, 0, 0], [0, 10, 0]); // Returns [5, 5, 0]
* math.intersect([1, 0, 1], [4, -2, 2], [1, 1, 1, 6]); // Returns [7, -4, 3]
...
inv = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
var eye = load(require('./eye'));
/**
* Calculate the inverse of a square matrix.
*
* Syntax:
*
* math.inv(x)
*
* Examples:
*
* math.inv([[1, 2], [3, 4]]); // returns [[-2, 1], [1.5, -0.5]]
* math.inv(4); // returns 0.25
* 1 / 4; // returns 0.25
*
...
isInteger = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
/**
* Test whether index is an integer number with index >= 0 and index < length
* when length is provided
* @param {number} index Zero-based index
* @param {number} [length] Length of the array
*/
exports.validateIndex = function(index, length) {
if (!number.isNumber(index) || !number.isInteger(index)) {
throw new TypeError('Index must be an integer (value: ' + index + ')');
}
if (index < 0 || (typeof length === 'number' && index >= length)) {
throw new IndexError(index, length);
}
};
...
isNaN = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
},
'Complex, Complex': function (x, y) {
return (x.re !== 0 || x.im !== 0) && (y.re !== 0 || y.im !== 0);
},
'BigNumber, BigNumber': function (x, y) {
return !x.isZero() && !y.isZero() && !x.isNaN() && !y
.isNaN();
},
'Unit, Unit': function (x, y) {
return and(x.value, y.value);
},
'Matrix, Matrix': function (x, y) {
...
isNegative = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
return new type.Complex(
(x.re > 0) ? Math.floor(x.re) : Math.ceil(x.re),
(x.im > 0) ? Math.floor(x.im) : Math.ceil(x.im)
);
},
'BigNumber': function (x) {
return x.isNegative() ? x.ceil() : x.floor();
},
'Fraction': function (x) {
return x.s < 0 ? x.ceil() : x.floor();
},
'Array | Matrix': function (x) {
...
isNumeric = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
/**
* Test whether a value is an numeric value.
*
* The function is evaluated element-wise in case of Array or Matrix input.
*
* Syntax:
*
* math.isNumeric(x)
*
* Examples:
*
* math.isNumeric(2); // returns true
* math.isNumeric(0); // returns true
* math.isNumeric(math.bignumber(500)); // returns true
* math.isNumeric(math.fraction(4)); // returns true
...
isPositive = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
* Test whether a value is positive: larger than zero.
* The function supports types `number`, `BigNumber`, `Fraction`, and `Unit`.
*
* The function is evaluated element-wise in case of Array or Matrix input.
*
* Syntax:
*
* math.isPositive(x)
*
* Examples:
*
* math.isPositive(3); // returns true
* math.isPositive(-2); // returns false
* math.isPositive(0); // returns false
* math.isPositive(-0); // returns false
...
isPrime = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
* Test whether a value is prime: has no divisors other than itself and one.
* The function supports type `number`, `bignumber`.
*
* The function is evaluated element-wise in case of Array or Matrix input.
*
* Syntax:
*
* math.isPrime(x)
*
* Examples:
*
* math.isPrime(3); // returns true
* math.isPrime(-2); // returns false
* math.isPrime(0); // returns false
* math.isPrime(-0); // returns false
...
isZero = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
},
'number': function (x) {
return !!x;
},
'BigNumber': function (x) {
return !x.isZero();
},
'string': function (x) {
// try case insensitive
var lcase = x.toLowerCase();
if (lcase === 'true') {
return true;
...
kldivergence = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
var isNumeric = load(require('../utils/isNumeric'));
/**
* Calculate the Kullback-Leibler (KL) divergence between two distributions
*
* Syntax:
*
* math.kldivergence(x, y)
*
* Examples:
*
* math.kldivergence([0.7,0.5,0.4], [0.2,0.9,0.5]); //returns 0.24376698773121153
*
*
* @param {Array | Matrix} q First vector
...
kron = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
*
* NOTE: If a one dimensional vector / matrix is given, it will be
* wrapped so its two dimensions.
* See the examples.
*
* Syntax:
*
* math.kron(x, y)
*
* Examples:
*
* math.kron([[1, 0], [0, 1]], [[1, 2], [3, 4]]);
* // returns [ [ 1, 2, 0, 0 ], [ 3, 4, 0, 0 ], [ 0, 0, 1, 2 ], [ 0, 0, 3, 4 ] ]
*
* math.kron([1,1], [2,3,4]);
...
larger = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
*
* Syntax:
*
* math.largerEq(x, y)
*
* Examples:
*
* math.larger(2, 1 + 1); // returns false
* math.largerEq(2, 1 + 1); // returns true
*
* See also:
*
* equal, unequal, smaller, smallerEq, larger, compare
*
* @param {number | BigNumber | Fraction | boolean | Unit | string | Array | Matrix} x First value to compare
...
largerEq = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
* difference between x and y is smaller than the configured epsilon. The
* function cannot be used to compare values smaller than approximately 2.22e-16.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.largerEq(x, y)
*
* Examples:
*
* math.larger(2, 1 + 1); // returns false
* math.largerEq(2, 1 + 1); // returns true
*
* See also:
...
lcm = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
*
* lcm(a, b) = abs(a * b) / gcd(a, b)
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.lcm(a, b)
* math.lcm(a, b, c, ...)
*
* Examples:
*
* math.lcm(4, 6); // returns 12
* math.lcm(6, 21); // returns 42
* math.lcm(6, 21, 5); // returns 210
...
leftShift = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
/**
* Bitwise left logical shift of a value x by y number of bits, `x << y`.
* For matrices, the function is evaluated element wise.
* For units, the function is evaluated on the best prefix base.
*
* Syntax:
*
* math.leftShift(x, y)
*
* Examples:
*
* math.leftShift(1, 2); // returns number 4
*
* math.leftShift([1, 2, 3], 4); // returns Array [16, 32, 64]
*
...
log = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
```js
// load math.js
var math = require('mathjs');
// functions and constants
math.round(math.e, 3); // 2.718
math.atan2(3, -3) / math.pi; // 0.75
math.log(1000, 10); // 3
math.sqrt(-4); // 2i
math.pow([[-1, 2], [3, 1]], 2); // [[7, 0], [0, 7]]
math.derivative('x^2 + x', 'x'); // 2 * x + 1
// expressions
math.eval('12 / (2.3 + 0.7)'); // 4
math.eval('5.08 cm to inch'); // 2 inch
...
log10 = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
/**
* Calculate the 10-base logarithm of a value. This is the same as calculating `log(x, 10)`.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.log10(x)
*
* Examples:
*
* math.log10(0.00001); // returns -5
* math.log10(10000); // returns 4
* math.log(10000) / math.log(10); // returns 4
* math.pow(10, 4); // returns 10000
...
lsolve = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
n/a
lup = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
n/a
lusolve = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
n/a
mad = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
/**
* Compute the median absolute deviation of a matrix or a list with values.
* The median absolute deviation is defined as the median of the absolute
* deviations from the median.
*
* Syntax:
*
* math.mad(a, b, c, ...)
* math.mad(A)
*
* Examples:
*
* math.mad(10, 20, 30); // returns 10
* math.mad([1, 2, 3]); // returns 1
* math.mad([[1, 2, 3], [4, 5, 6]]); // returns 1.5
...
map = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
if (res && res.isResultSet) {
// we can have 0 or 1 results in the ResultSet, as the CLI
// does not allow multiple expressions separated by a return
res = res.entries[0];
node = node.blocks
.filter(function (entry) { return entry.visible; })
.map(function (entry) { return entry.node })[0];
}
if (node) {
if (node.isAssignmentNode) {
var name = findSymbolName(node);
if (name != null) {
scope.ans = scope[name];
...
matrix = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
ArrayNode.prototype._compile = function (defs, args) {
var asMatrix = (defs.math.config().matrix !== 'Array');
var items = this.items.map(function (node) {
return node._compile(defs, args);
});
return (asMatrix ? 'math.matrix([' : '[') +
items.join(',') +
(asMatrix ? '])' : ']');
};
/**
* Execute a callback for each of the child nodes of this node
* @param {function(child: Node, path: string, parent: Node)} callback
...
max = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
* @return {number} Returns the maximum number of expected arguments.
* Returns -1 when no signatures where found on the function.
*/
exports.maxArgumentCount = function (fn) {
return Object.keys(fn.signatures || {})
.reduce(function (args, signature) {
var count = (signature.match(/,/g) || []).length + 1;
return Math.max(args, count);
}, -1);
};
...
mean = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
* Compute the mean value of matrix or a list with values.
* In case of a multi dimensional array, the mean of the flattened array
* will be calculated. When `dim` is provided, the maximum over the selected
* dimension will be calculated. Parameter `dim` is zero-based.
*
* Syntax:
*
* math.mean(a, b, c, ...)
* math.mean(A)
* math.mean(A, dim)
*
* Examples:
*
* math.mean(2, 1, 4, 3); // returns 2.5
* math.mean([1, 2.7, 3.2, 4]); // returns 2.725
...
median = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
* Supported types of values are: Number, BigNumber, Unit
*
* In case of a (multi dimensional) array or matrix, the median of all
* elements will be calculated.
*
* Syntax:
*
* math.median(a, b, c, ...)
* math.median(A)
*
* Examples:
*
* math.median(5, 2, 7); // returns 5
* math.median([3, -1, 5, 7]); // returns 4
*
...
min = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
* @private
*/
function _resize (array, size, dim, defaultValue) {
var i;
var elem;
var oldLen = array.length;
var newLen = size[dim];
var minLen = Math.min(oldLen, newLen);
// apply new length
array.length = newLen;
if (dim < size.length - 1) {
// non-last dimension
var dimNext = dim + 1;
...
mod = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
if (!a.isInt() || !b.isInt()) {
throw new Error('Parameters in function gcd must be integer numbers');
}
// http://en.wikipedia.org/wiki/Euclidean_algorithm
var zero = new type.BigNumber(0);
while (!b.isZero()) {
var r = a.mod(b);
a = b;
b = r;
}
return a.lt(zero) ? a.neg() : a;
}
}
...
mode = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
/**
* Computes the mode of a set of numbers or a list with values(numbers or characters).
* If there are more than one modes, it returns a list of those values.
*
* Syntax:
*
* math.mode(a, b, c, ...)
* math.mode(A)
*
* Examples:
*
* math.mode(2, 1, 4, 3, 1); // returns [1]
* math.mode([1, 2.7, 3.2, 4, 2.7]); // returns [2.7]
* math.mode(1, 4, 6, 1, 6) // returns [1, 6]
...
multinomial = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
* Multinomial Coefficients compute the number of ways of picking a1, a2, ..., ai unordered outcomes from `n` possibilities.
*
* multinomial takes one array of integers as an argument.
* The following condition must be enforced: every ai <= 0
*
* Syntax:
*
* math.multinomial(a) // a is an array type
*
* Examples:
*
* math.multinomial([1,2,1]); // returns 12
*
* See also:
*
...
multiply = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
math.eval('sin(45 deg) ^ 2'); // 0.5
math.eval('9 / 3 + 2i'); // 3 + 2i
math.eval('det([-1, 2; 3, 1])'); // -7
// chaining
math.chain(3)
.add(4)
.multiply(2)
.done(); // 14
```
## Browser support
Math.js works on any ES5 compatible JavaScript engine: node.js 0.10, and Internet Explorer 9 and newer, and all other browsers (
Chrome, Firefox, Safari). If support for old browsers like Internet Explorer 8 is required, the [es5-shim](https://github.com/kriskowal
/es5-shim) library has to be loaded.
...
norm = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
/**
* Calculate the norm of a number, vector or matrix.
*
* The second parameter p is optional. If not provided, it defaults to 2.
*
* Syntax:
*
* math.norm(x)
* math.norm(x, p)
*
* Examples:
*
* math.abs(-3.5); // returns 3.5
* math.norm(-3.5); // returns 3.5
*
...
not = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
/**
* Logical `not`. Flips boolean value of a given parameter.
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.not(x)
*
* Examples:
*
* math.not(2); // returns false
* math.not(0); // returns true
* math.not(true); // returns false
*
...
nthRoot = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
*
* x^root = A
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.nthRoot(a)
* math.nthRoot(a, root)
*
* Examples:
*
* math.nthRoot(9, 2); // returns 3, as 3^2 == 9
* math.sqrt(9); // returns 3, as 3^2 == 9
* math.nthRoot(64, 3); // returns 4, as 4^3 == 64
...
number = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
function factory (type, config, load, typed) {
/**
* Create a number or convert a string, boolean, or unit to a number.
* When value is a matrix, all elements will be converted to number.
*
* Syntax:
*
* math.number(value)
* math.number(unit, valuelessUnit)
*
* Examples:
*
* math.number(2); // returns number 2
* math.number('7.2'); // returns number 7.2
* math.number(true); // returns number 1
...
off = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
n/a
on = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
}
// load math.js now, right *after* loading the prompt.
var math = getMath();
// TODO: automatic insertion of 'ans' before operators like +, -, *, /
rl.on('line', function(line) {
var expr = line.trim();
switch (expr.toLowerCase()) {
case 'quit':
case 'exit':
// exit application
rl.close();
...
once = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
n/a
ones = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
/**
* Create a matrix filled with ones. The created matrix can have one or
* multiple dimensions.
*
* Syntax:
*
* math.ones(m)
* math.ones(m, format)
* math.ones(m, n)
* math.ones(m, n, format)
* math.ones([m, n])
* math.ones([m, n], format)
* math.ones([m, n, p, ...])
* math.ones([m, n, p, ...], format)
...
or = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
/**
* Logical `or`. Test if at least one value is defined with a nonzero/nonempty value.
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.or(x, y)
*
* Examples:
*
* math.or(2, 4); // returns true
*
* a = [2, 5, 0];
* b = [0, 22, 0];
...
parse = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
if (!expr) {
break;
}
switch (mode) {
case 'eval':
// evaluate expression
try {
var node = math.parse(expr);
var res = node.eval(scope);
if (res && res.isResultSet) {
// we can have 0 or 1 results in the ResultSet, as the CLI
// does not allow multiple expressions separated by a return
res = res.entries[0];
node = node.blocks
...
parser = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
* parser.remove(name); // clear a variable from the
* // parsers scope
* parser.clear(); // clear the parsers scope
*
* Example usage:
* var parser = new Parser();
* // Note: there is a convenience method which can be used instead:
* // var parser = new math.parser();
*
* // evaluate expressions
* parser.eval('sqrt(3^2 + 4^2)'); // 5
* parser.eval('sqrt(-4)'); // 2i
* parser.eval('2 inch in cm'); // 5.08 cm
* parser.eval('cos(45 deg)'); // 0.7071067811865476
*
...
partitionSelect = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
/**
* Partition-based selection of an array or 1D matrix.
* Will find the kth smallest value, and mutates the input array.
* Uses Quickselect.
*
* Syntax:
*
* math.partitionSelect(x, k)
* math.partitionSelect(x, k, compare)
*
* Examples:
*
* math.partitionSelect([5, 10, 1], 2); // returns 10
* math.partitionSelect(['C', 'B', 'A', 'D'], 1); // returns 'B'
*
...
permutations = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
* from a set of `n` elements.
*
* Permutations only takes integer arguments.
* The following condition must be enforced: k <= n.
*
* Syntax:
*
* math.permutations(n)
* math.permutations(n, k)
*
* Examples:
*
* math.permutations(5); // 120
* math.permutations(5, 3); // 60
*
...
pow = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
var math = require('mathjs');
// functions and constants
math.round(math.e, 3); // 2.718
math.atan2(3, -3) / math.pi; // 0.75
math.log(1000, 10); // 3
math.sqrt(-4); // 2i
math.pow([[-1, 2], [3, 1]], 2); // [[7, 0], [0, 7]]
math.derivative('x^2 + x', 'x'); // 2 * x + 1
// expressions
math.eval('12 / (2.3 + 0.7)'); // 4
math.eval('5.08 cm to inch'); // 2 inch
math.eval('sin(45 deg) ^ 2'); // 0.5
math.eval('9 / 3 + 2i'); // 3 + 2i
...
print = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
function factory (type, config, load, typed) {
/**
* Interpolate values into a string template.
*
* Syntax:
*
* math.print(template, values)
* math.print(template, values, precision)
* math.print(template, values, options)
*
* Example usage:
*
* // the following outputs: 'Lucy is 5 years old'
* math.print('Lucy is $age years old', {age: 5});
...
prod = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
/**
* Compute the product of a matrix or a list with values.
* In case of a (multi dimensional) array or matrix, the sum of all
* elements will be calculated.
*
* Syntax:
*
* math.prod(a, b, c, ...)
* math.prod(A)
*
* Examples:
*
* math.multiply(2, 3); // returns 6
* math.prod(2, 3); // returns 6
* math.prod(2, 3, 4); // returns 24
...
qr = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
n/a
quantileSeq = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
* Supported types of probability are: Number, BigNumber
*
* In case of a (multi dimensional) array or matrix, the prob order quantile
* of all elements will be calculated.
*
* Syntax:
*
* math.quantileSeq(A, prob[, sorted])
* math.quantileSeq(A, [prob1, prob2, ...][, sorted])
* math.quantileSeq(A, N[, sorted])
*
* Examples:
*
* math.quantileSeq([3, -1, 5, 7], 0.5); // returns 4
* math.quantileSeq([3, -1, 5, 7], [1/3, 2/3]); // returns [3, 5]
...
range = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
* the name of the argument, and the value is `true`.
* The object may not be mutated, but must be
* extended instead.
* @return {string} js
* @private
*/
RangeNode.prototype._compile = function (defs, args) {
return 'math.range(' +
this.start._compile(defs, args) + ', ' +
this.end._compile(defs, args) +
(this.step ? (', ' + this.step._compile(defs, args)) : '') +
')';
};
/**
...
re = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
* Syntax:
*
* math.im(x)
*
* Examples:
*
* var a = math.complex(2, 3);
* math.re(a); // returns number 2
* math.im(a); // returns number 3
*
* math.re(math.complex('-5.2i')); // returns number -5.2
* math.re(math.complex(2.4)); // returns number 0
*
* See also:
*
...
reshape = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
var matrix = load(require('../../type/matrix/function/matrix'));
/**
* Reshape a multi dimensional array to fit the specified dimensions
*
* Syntax:
*
* math.reshape(x, sizes)
*
* Examples:
*
* math.reshape([1, 2, 3, 4, 5, 6], [2, 3]);
* // returns Array [[1, 2, 3], [4, 5, 6]]
*
* math.reshape([[1, 2], [3, 4]], [1, 4]);
...
resize = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
// get matrix storage constructor
var F = type.Matrix.storage(format);
// create diagonal matrix (use optimized implementation for storage format)
return F.diagonal(size, one, 0, defaultValue);
}
// create and resize array
var res = array.resize([], size, defaultValue);
// fill in ones on the diagonal
var minimum = rows < cols ? rows : cols;
// fill diagonal
for (var d = 0; d < minimum; d++) {
res[d][d] = one;
}
return res;
...
rightArithShift = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
/**
* Bitwise right arithmetic shift of a value x by y number of bits, `x >> y`.
* For matrices, the function is evaluated element wise.
* For units, the function is evaluated on the best prefix base.
*
* Syntax:
*
* math.rightArithShift(x, y)
*
* Examples:
*
* math.rightArithShift(4, 2); // returns number 1
*
* math.rightArithShift([16, -32, 64], 4); // returns Array [1, -2, 3]
*
...
rightLogShift = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
/**
* Bitwise right logical shift of value x by y number of bits, `x >>> y`.
* For matrices, the function is evaluated element wise.
* For units, the function is evaluated on the best prefix base.
*
* Syntax:
*
* math.rightLogShift(x, y)
*
* Examples:
*
* math.rightLogShift(4, 2); // returns number 1
*
* math.rightLogShift([16, -32, 64], 4); // returns Array [1, 2, 3]
*
...
round = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
[chained operations](http://mathjs.org/docs/chained_operations.html).
```js
// load math.js
var math = require('mathjs');
// functions and constants
math.round(math.e, 3); // 2.718
math.atan2(3, -3) / math.pi; // 0.75
math.log(1000, 10); // 3
math.sqrt(-4); // 2i
math.pow([[-1, 2], [3, 1]], 2); // [[7, 0], [0, 7]]
math.derivative('x^2 + x', 'x'); // 2 * x + 1
// expressions
...
sec = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
* Syntax:
*
* math.asec(x)
*
* Examples:
*
* math.asec(0.5); // returns 1.0471975511965979
* math.asec(math.sec(1.5)); // returns 1.5
*
* math.asec(2); // returns 0 + 1.3169578969248166 i
*
* See also:
*
* acos, acot, acsc
*
...
sech = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
* Calculate the hyperbolic secant of a value,
* defined as `sech(x) = 1 / cosh(x)`.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.sech(x)
*
* Examples:
*
* // sech(x) = 1/ cosh(x)
* math.sech(0.5); // returns 0.886818883970074
* 1 / math.cosh(0.5); // returns 0.886818883970074
*
...
sign = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
* - -1 when x < 0
* - 0 when x == 0
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.sign(x)
*
* Examples:
*
* math.sign(3.5); // returns 1
* math.sign(-4.2); // returns -1
* math.sign(0); // returns 0
*
...
simplify = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
* Syntax:
*
* simplify(expr)
* simplify(expr, rules)
*
* Examples:
*
* math.simplify('2 * 1 * x ^ (2 - 1)'); // Node {2 * x}
* var f = math.parse('2 * 1 * x ^ (2 - 1)');
* math.simplify(f); // Node {2 * x}
*
* See also:
*
* derivative, parse, eval
*
...
sin = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
res = 1; // 0! is per definition 1
}
return res;
}
if (n < 0.5) {
return Math.PI / (Math.sin(Math.PI * n) * gamma(1-n));
}
if (n >= 171.35) {
return Infinity; // will overflow
}
if (n > 85.0) { // Extended Stirling Approx
...
sinh = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
*
* math.csch(x)
*
* Examples:
*
* // csch(x) = 1/ sinh(x)
* math.csch(0.5); // returns 1.9190347513349437
* 1 / math.sinh(0.5); // returns 1.9190347513349437
*
* See also:
*
* sinh, sech, coth
*
* @param {number | Complex | Unit | Array | Matrix} x Function input
* @return {number | Complex | Array | Matrix} Hyperbolic cosecant of x
...
size = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
};
if (!Array.isArray(array) || !Array.isArray(sizes)) {
throw new TypeError('Array expected');
}
if (sizes.length === 0) {
throw new DimensionError(0, product(exports.size(array)), '!=');
}
try {
newArray = _reshape(flatArray, sizes);
} catch (e) {
if (e instanceof DimensionError) {
throw new DimensionError(
...
slu = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
n/a
smaller = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
*
* Syntax:
*
* math.smallerEq(x, y)
*
* Examples:
*
* math.smaller(1 + 2, 3); // returns false
* math.smallerEq(1 + 2, 3); // returns true
*
* See also:
*
* equal, unequal, smaller, larger, largerEq, compare
*
* @param {number | BigNumber | Fraction | boolean | Unit | string | Array | Matrix} x First value to compare
...
smallerEq = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
* The function returns true when x is smaller than y or the relative
* difference between x and y is smaller than the configured epsilon. The
* function cannot be used to compare values smaller than approximately 2.22e-16.
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.smallerEq(x, y)
*
* Examples:
*
* math.smaller(1 + 2, 3); // returns false
* math.smallerEq(1 + 2, 3); // returns true
*
* See also:
...
sort = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
};
/**
* Sort the items in a matrix.
*
* Syntax:
*
* math.sort(x)
* math.sort(x, compare)
*
* Examples:
*
* math.sort([5, 10, 1]); // returns [1, 5, 10]
* math.sort(['C', 'B', 'A', 'D']); // returns ['A', 'B', 'C
', 'D']
*
...
sparse = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
n/a
splitUnit = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
* Returns an array of units whose sum is equal to this unit
* @memberof Unit
* @param {Array} [parts] An array of strings or valueless units.
*
* Example:
*
* var u = new Unit(1, 'm');
* u.splitUnit(['feet', 'inch']);
* [ 3 feet, 3.3700787401575 inch ]
*
* @return {Array} An array of units.
*/
Unit.prototype.splitUnit = function(parts) {
var x = this.clone();
...
sqrt = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
// load math.js
var math = require('mathjs');
// functions and constants
math.round(math.e, 3); // 2.718
math.atan2(3, -3) / math.pi; // 0.75
math.log(1000, 10); // 3
math.sqrt(-4); // 2i
math.pow([[-1, 2], [3, 1]], 2); // [[7, 0], [0, 7]]
math.derivative('x^2 + x', 'x'); // 2 * x + 1
// expressions
math.eval('12 / (2.3 + 0.7)'); // 4
math.eval('5.08 cm to inch'); // 2 inch
math.eval('sin(45 deg) ^ 2'); // 0.5
...
square = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
* Syntax:
*
* math.sqrt(x)
*
* Examples:
*
* math.sqrt(25); // returns 5
* math.square(5); // returns 25
* math.sqrt(-4); // returns Complex 2i
*
* See also:
*
* square, multiply, cube, cbrt
*
* @param {number | BigNumber | Complex | Array | Matrix | Unit} x
...
squeeze = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
* @param {Array} y Second vector
* @returns {Array} Returns the cross product of x and y
* @private
*/
function _cross(x, y) {
var highestDimension = Math.max(array.size(x).length, array.size(y).length);
x = array.squeeze(x);
y = array.squeeze(y);
var xSize = array.size(x);
var ySize = array.size(y);
if (xSize.length != 1 || ySize.length != 1 || xSize[0] != 3 || ySize[0] != 3) {
throw new RangeError('Vectors with length 3 expected ' +
...
std = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
*
* - 'unbiased' (default) The sum of squared errors is divided by (n - 1)
* - 'uncorrected' The sum of squared errors is divided by n
* - 'biased' The sum of squared errors is divided by (n + 1)
*
* Syntax:
*
* math.std(a, b, c, ...)
* math.std(A)
* math.std(A, normalization)
*
* Examples:
*
* math.std(2, 4, 6); // returns 2
* math.std([2, 4, 6, 8]); // returns 2.581988897471611
...
stirlingS2 = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
* stirlingS2 only takes integer arguments.
* The following condition must be enforced: k <= n.
*
* If n = k or k = 1, then s(n,k) = 1
*
* Syntax:
*
* math.stirlingS2(n, k)
*
* Examples:
*
* math.stirlingS2(5, 3); //returns 25
*
* See also:
*
...
string = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
function factory (type, config, load, typed) {
/**
* Create a string or convert any object into a string.
* Elements of Arrays and Matrices are processed element wise.
*
* Syntax:
*
* math.string(value)
*
* Examples:
*
* math.string(4.2); // returns string '4.2'
* math.string(math.complex(3, 2); // returns string '3 + 2i'
*
* var u = math.unit(5, 'km');
...
subset = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
function factory (type, config, load, typed) {
var matrix = load(require('../../type/matrix/function/matrix'));
/**
* Get or set a subset of a matrix or string.
*
* Syntax:
* math.subset(value, index) // retrieve a subset
* math.subset(value, index, replacement [, defaultValue]) // replace a subset
*
* Examples:
*
* // get a subset
* var d = [[1, 2], [3, 4]];
* math.subset(d, math.index(1, 0)); // returns 3
...
subtract = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
/**
* Subtract two values, `x - y`.
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.subtract(x, y)
*
* Examples:
*
* math.subtract(5.3, 2); // returns number 3.3
*
* var a = math.complex(2, 3);
* var b = math.complex(4, 1);
...
sum = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
/**
* Compute the sum of a matrix or a list with values.
* In case of a (multi dimensional) array or matrix, the sum of all
* elements will be calculated.
*
* Syntax:
*
* math.sum(a, b, c, ...)
* math.sum(A)
*
* Examples:
*
* math.sum(2, 1, 4, 3); // returns 10
* math.sum([2, 1, 4, 3]); // returns 10
* math.sum([[2, 5], [4, 3], [1, 7]]); // returns 22
...
tan = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
* Syntax:
*
* math.atan(x)
*
* Examples:
*
* math.atan(0.5); // returns number 0.4636476090008061
* math.atan(math.tan(1.5)); // returns number 1.5
*
* math.atan(2); // returns Complex 1.5707963267948966 -1.3169578969248166 i
*
* See also:
*
* tan, asin, acos
*
...
tanh = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
*
* math.coth(x)
*
* Examples:
*
* // coth(x) = 1 / tanh(x)
* math.coth(2); // returns 1.0373147207275482
* 1 / math.tanh(2); // returns 1.0373147207275482
*
* See also:
*
* sinh, tanh, cosh
*
* @param {number | Complex | Unit | Array | Matrix} x Function input
* @return {number | Complex | Array | Matrix} Hyperbolic cotangent of x
...
to = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
*
* Examples:
*
* math.string(4.2); // returns string '4.2'
* math.string(math.complex(3, 2); // returns string '3 + 2i'
*
* var u = math.unit(5, 'km');
* math.string(u.to('m')); // returns string '5000 m'
*
* math.string([true, false]); // returns ['true', 'false']
*
* See also:
*
* bignumber, boolean, complex, index, matrix, number, unit
*
...
toString = function () { return format(this.value); }
...
}
else {
scope.ans = res;
console.log(format(res));
}
}
else if (res instanceof math.type.Help) {
console.log(res.toString());
}
else {
scope.ans = res;
console.log(format(res));
}
}
}
...
trace = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
/**
* Calculate the trace of a matrix: the sum of the elements on the main
* diagonal of a square matrix.
*
* Syntax:
*
* math.trace(x)
*
* Examples:
*
* math.trace([[1, 2], [3, 4]]); // returns 5
*
* var A = [
* [1, 2, 3],
...
transpose = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
* Transpose a matrix. All values of the matrix are reflected over its
* main diagonal. Only applicable to two dimensional matrices containing
* a vector (i.e. having size `[1,n]` or `[n,1]`). One dimensional
* vectors and scalars return the input unchanged.
*
* Syntax:
*
* math.transpose(x)
*
* Examples:
*
* var A = [[1, 2, 3], [4, 5, 6]];
* math.transpose(A); // returns [[1, 4], [2, 5], [3, 6]]
*
* See also:
...
typed = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
n/a
typeof = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
/**
* Determine the type of a variable.
*
* Function `typeof` recognizes the following types of objects:
*
* Object | Returns | Example
* ---------------------- | ------------- | ------------------------------------------
* null | `'null'` | `math.typeof(null)`
* number | `'number'` | `math.typeof(3.5)`
* boolean | `'boolean'` | `math.typeof (true)`
* string | `'string'` | `math.typeof ('hello world')`
* Array | `'Array'` | `math.typeof ([1, 2, 3])`
* Date | `'Date'` | `math.typeof (new Date())`
* Function | `'Function'` | `math.typeof (function () {})`
* Object | `'Object'` | `math.typeof ({a: 2, b: 3})`
...
unaryMinus = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
*
* For matrices, the function is evaluated element wise. Boolean values and
* strings will be converted to a number. For complex numbers, both real and
* complex value are inverted.
*
* Syntax:
*
* math.unaryMinus(x)
*
* Examples:
*
* math.unaryMinus(3.5); // returns -3.5
* math.unaryMinus(-4.2); // returns 4.2
*
* See also:
...
unaryPlus = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
* Unary plus operation.
* Boolean values and strings will be converted to a number, numeric values will be returned as is.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.unaryPlus(x)
*
* Examples:
*
* math.unaryPlus(3.5); // returns 3.5
* math.unaryPlus(1); // returns 1
*
* See also:
...
unequal = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
*
* Values `null` and `undefined` are compared strictly, thus `null` is unequal
* with everything except `null`, and `undefined` is unequal with everying
* except. `undefined`.
*
* Syntax:
*
* math.unequal(x, y)
*
* Examples:
*
* math.unequal(2 + 2, 3); // returns true
* math.unequal(2 + 2, 4); // returns false
*
* var a = math.unit('50 cm');
...
unit = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
*
* Examples:
*
* math.number(2); // returns number 2
* math.number('7.2'); // returns number 7.2
* math.number(true); // returns number 1
* math.number([true, false, true, true]); // returns [1, 0, 1, 1]
* math.number(math.unit('52cm'), 'm'); // returns 0.52
*
* See also:
*
* bignumber, boolean, complex, index, matrix, string, unit
*
* @param {string | number | BigNumber | Fraction | boolean | Array | Matrix | Unit | null} [value] Value to be converted
* @param {Unit | string} [valuelessUnit] A valueless unit, used to convert a unit to a number
...
usolve = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
n/a
valueOf = function () { return this.value; }
...
throw new TypeError('Cannot implicitly convert a Fraction to BigNumber or vice versa. ' +
'Use function bignumber(x) to convert to BigNumber or fraction(x) to convert to Fraction.');
}
}, {
from: 'Fraction',
to: 'Complex',
convert: function (x) {
return new type.Complex(x.valueOf(), 0);
}
}, {
from: 'number',
to: 'Fraction',
convert: function (x) {
if (digits(x) > 15) {
throw new TypeError('Cannot implicitly convert a number with >15 significant digits to Fraction ' +
...
var = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
*
* - 'unbiased' (default) The sum of squared errors is divided by (n - 1)
* - 'uncorrected' The sum of squared errors is divided by n
* - 'biased' The sum of squared errors is divided by (n + 1)
*
* Note that older browser may not like the variable name `var`. In that
* case, the function can be called as `math['var'](...)` instead of
* `math.var(...)`.
*
* Syntax:
*
* math.var(a, b, c, ...)
* math.var(A)
* math.var(A, normalization)
*
...
xgcd = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
/**
* Calculate the extended greatest common divisor for two values.
* See http://en.wikipedia.org/wiki/Extended_Euclidean_algorithm.
*
* Syntax:
*
* math.xgcd(a, b)
*
* Examples:
*
* math.xgcd(8, 12); // returns [4, -1, 1]
* math.gcd(8, 12); // returns 4
* math.xgcd(36163, 21199); // returns [1247, -7, 12]
*
...
xor = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
/**
* Logical `xor`. Test whether one and only one value is defined with a nonzero/nonempty value.
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.xor(x, y)
*
* Examples:
*
* math.xor(2, 4); // returns false
*
* a = [2, 0, 0];
* b = [2, 7, 0];
...
zeros = function () { var args = [this.value]; // `this` will be the context of a Chain instance for (var i = 0; i < arguments.length; i++) { args[i + 1] = arguments[i]; } return new Chain(fn.apply(fn, args)); }
...
* math.squeeze(x)
*
* Examples:
*
* math.squeeze([3]); // returns 3
* math.squeeze([[3]]); // returns 3
*
* var A = math.zeros(3, 1); // returns [[0], [0], [0]] (size 3x1)
* math.squeeze(A); // returns [0, 0, 0] (size 3)
*
* var B = math.zeros(1, 3); // returns [[0, 0, 0]] (size 1x3)
* math.squeeze(B); // returns [0, 0, 0] (size 3)
*
* // only inner and outer dimensions are removed
* var C = math.zeros(2, 1, 3); // returns [[[0, 0, 0]], [[0, 0, 0]]] (size 2x1x3)
...
function Complex(a, b) { if (!(this instanceof Complex)) { return new Complex(a, b); } parse(a, b); // mutates P this["re"] = P["re"]; this["im"] = P["im"]; }
...
}
return new type.BigNumber(x);
}
}, {
from: 'number',
to: 'Complex',
convert: function (x) {
return new type.Complex(x, 0);
}
}, {
from: 'number',
to: 'string',
convert: function (x) {
return x + '';
}
...
fromJSON = function (json) { return new Complex(json); }
...
* @param {string} key
* @param {*} value
* @returns {*} Returns the revived object
*/
return function reviver(key, value) {
var constructor = type[value && value.mathjs];
if (constructor && typeof constructor.fromJSON === 'function') {
return constructor.fromJSON(value);
}
return value;
}
}
exports.name = 'reviver';
...
fromPolar = function (args) { switch (arguments.length) { case 1: var arg = arguments[0]; if (typeof arg === 'object') { return Complex(arg); } throw new TypeError('Input has to be an object with r and phi keys.'); case 2: var r = arguments[0], phi = arguments[1]; if (isNumber(r)) { if (phi && phi.isUnit && phi.hasBase('ANGLE')) { // convert unit to a number in radians phi = phi.toNumber('rad'); } if (isNumber(phi)) { return new Complex({r: r, phi: phi}); } throw new TypeError('Phi is not a number nor an angle unit.'); } else { throw new TypeError('Radius r is not a number.'); } default: throw new SyntaxError('Wrong number of arguments in function fromPolar'); } }
...
};
/**
* Create a complex number from polar coordinates
*
* Usage:
*
* Complex.fromPolar(r: number, phi: number) : Complex
* Complex.fromPolar({r: number, phi: number}) : Complex
*
* @param {*} args...
* @return {Complex}
*/
Complex.fromPolar = function (args) {
switch (arguments.length) {
...
abs = function () { var a = Math.abs(this["re"]); var b = Math.abs(this["im"]); if (a < 3000 && b < 3000) { return Math.sqrt(a * a + b * b); } if (a < b) { a = b; b = this["re"] / this["im"]; } else { b = this["im"] / this["re"]; } return a * Math.sqrt(1 + b * b); }
...
function factory (type, config, load, typed) {
/**
* Calculate the absolute value of a number. For matrices, the function is
* evaluated element wise.
*
* Syntax:
*
* math.abs(x)
*
* Examples:
*
* math.abs(3.5); // returns number 3.5
* math.abs(-4.2); // returns number 4.2
*
* math.abs([3, -5, -1, 0, 2]); // returns Array [3, 5, 1, 0, 2]
...
acos = function () { var a = this["re"]; var b = this["im"]; var t1 = new Complex( b * b - a * a + 1, -2 * a * b)['sqrt'](); var t2 = new Complex( t1["re"] - b, t1["im"] + a)['log'](); return new Complex(Math.PI / 2 - t2["im"], t2["re"]); }
...
/**
* Calculate the inverse cosine of a value.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.acos(x)
*
* Examples:
*
* math.acos(0.5); // returns number 1.0471975511965979
* math.acos(math.cos(1.5)); // returns number 1.5
*
* math.acos(2); // returns Complex 0 + 1.3169578969248166 i
...
acosh = function () { var tmp; var res = this["acos"](); if (res["im"] <= 0) { tmp = res["re"]; res["re"] = -res["im"]; res["im"] = tmp; } else { tmp = res["im"]; res["im"] = -res["re"]; res["re"] = tmp; } return res; }
...
* Calculate the hyperbolic arccos of a value,
* defined as `acosh(x) = ln(sqrt(x^2 - 1) + x)`.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.acosh(x)
*
* Examples:
*
* math.acosh(1.5); // returns 0.9624236501192069
*
* See also:
*
...
acot = function () { var a = this["re"]; var b = this["im"]; if (b === 0) { return new Complex(Math.atan2(1, a), 0); } var d = a * a + b * b; return (d !== 0) ? new Complex( a / d, -b / d).atan() : new Complex( (a !== 0) ? a / 0 : 0, (b !== 0) ?-b / 0 : 0).atan(); }
...
/**
* Calculate the inverse cotangent of a value, defined as `acot(x) = atan(1/x)`.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.acot(x)
*
* Examples:
*
* math.acot(0.5); // returns number 0.4636476090008061
* math.acot(math.cot(1.5)); // returns number 1.5
*
* math.acot(2); // returns Complex 1.5707963267948966 -1.3169578969248166 i
...
acoth = function () { var a = this["re"]; var b = this["im"]; if (a === 0 && b === 0) { return new Complex(0, Math.PI / 2); } var d = a * a + b * b; return (d !== 0) ? new Complex( a / d, -b / d).atanh() : new Complex( (a !== 0) ? a / 0 : 0, (b !== 0) ?-b / 0 : 0).atanh(); }
...
* Calculate the hyperbolic arccotangent of a value,
* defined as `acoth(x) = atanh(1/x) = (ln((x+1)/x) + ln(x/(x-1))) / 2`.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.acoth(x)
*
* Examples:
*
* math.acoth(0.5); // returns 0.8047189562170503
*
* See also:
*
...
acsc = function () { var a = this["re"]; var b = this["im"]; if (a === 0 && b === 0) { return new Complex(Math.PI / 2, Infinity); } var d = a * a + b * b; return (d !== 0) ? new Complex( a / d, -b / d).asin() : new Complex( (a !== 0) ? a / 0 : 0, (b !== 0) ?-b / 0 : 0).asin(); }
...
/**
* Calculate the inverse cosecant of a value, defined as `acsc(x) = asin(1/x)`.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.acsc(x)
*
* Examples:
*
* math.acsc(0.5); // returns number 0.5235987755982989
* math.acsc(math.csc(1.5)); // returns number ~1.5
*
* math.acsc(2); // returns Complex 1.5707963267948966 -1.3169578969248166 i
...
acsch = function () { var a = this["re"]; var b = this["im"]; if (b === 0) { return new Complex( (a !== 0) ? Math.log(a + Math.sqrt(a * a + 1)) : Infinity, 0); } var d = a * a + b * b; return (d !== 0) ? new Complex( a / d, -b / d).asinh() : new Complex( (a !== 0) ? a / 0 : 0, (b !== 0) ?-b / 0 : 0).asinh(); }
...
* Calculate the hyperbolic arccosecant of a value,
* defined as `acsch(x) = asinh(1/x) = ln(1/x + sqrt(1/x^2 + 1))`.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.acsch(x)
*
* Examples:
*
* math.acsch(0.5); // returns 1.4436354751788103
*
* See also:
*
...
add = function (a, b) { parse(a, b); // mutates P return new Complex( this["re"] + P["re"], this["im"] + P["im"]); }
...
math.eval('5.08 cm to inch'); // 2 inch
math.eval('sin(45 deg) ^ 2'); // 0.5
math.eval('9 / 3 + 2i'); // 3 + 2i
math.eval('det([-1, 2; 3, 1])'); // -7
// chaining
math.chain(3)
.add(4)
.multiply(2)
.done(); // 14
```
## Browser support
Math.js works on any ES5 compatible JavaScript engine: node.js 0.10, and Internet Explorer 9 and newer, and all other browsers (
Chrome, Firefox, Safari). If support for old browsers like Internet Explorer 8 is required, the [es5-shim](https://github.com/kriskowal
/es5-shim) library has to be loaded.
...
arg = function () { return Math.atan2(this["im"], this["re"]); }
...
* the principal root is returned.
* @returns {Complex | Array.<Complex> | Matrix.<Complex>} Returns the cubic root(s) of x
* @private
*/
function _cbrtComplex(x, allRoots) {
// https://www.wikiwand.com/en/Cube_root#/Complex_numbers
var arg_3 = x.arg() / 3;
var abs = x.abs();
// principal root:
var principal = new type.Complex(_cbrtNumber(abs), 0).mul(
new type.Complex(0, arg_3).exp());
if (allRoots) {
...
asec = function () { var a = this["re"]; var b = this["im"]; if (a === 0 && b === 0) { return new Complex(0, Infinity); } var d = a * a + b * b; return (d !== 0) ? new Complex( a / d, -b / d).acos() : new Complex( (a !== 0) ? a / 0 : 0, (b !== 0) ?-b / 0 : 0).acos(); }
...
/**
* Calculate the inverse secant of a value. Defined as `asec(x) = acos(1/x)`.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.asec(x)
*
* Examples:
*
* math.asec(0.5); // returns 1.0471975511965979
* math.asec(math.sec(1.5)); // returns 1.5
*
* math.asec(2); // returns 0 + 1.3169578969248166 i
...
asech = function () { var a = this["re"]; var b = this["im"]; if (a === 0 && b === 0) { return new Complex(Infinity, 0); } var d = a * a + b * b; return (d !== 0) ? new Complex( a / d, -b / d).acosh() : new Complex( (a !== 0) ? a / 0 : 0, (b !== 0) ?-b / 0 : 0).acosh(); }
...
* Calculate the hyperbolic arcsecant of a value,
* defined as `asech(x) = acosh(1/x) = ln(sqrt(1/x^2 - 1) + 1/x)`.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.asech(x)
*
* Examples:
*
* math.asech(0.5); // returns 1.3169578969248166
*
* See also:
*
...
asin = function () { var a = this["re"]; var b = this["im"]; var t1 = new Complex( b * b - a * a + 1, -2 * a * b)['sqrt'](); var t2 = new Complex( t1['re'] - b, t1['im'] + a)['log'](); return new Complex(t2['im'], -t2['re']); }
...
*
* @param {number | Complex | Array | Matrix} x Function input
* @return {number | Complex | Array | Matrix} The arc cosecant of x
*/
var acsc = typed('acsc', {
'number': function (x) {
if (x <= -1 || x >= 1 || config.predictable) {
return Math.asin(1 / x);
}
return new type.Complex(x, 0).acsc();
},
'Complex': function (x) {
return x.acsc();
},
...
asinh = function () { var tmp = this["im"]; this["im"] = -this["re"]; this["re"] = tmp; var res = this["asin"](); this["re"] = -this["im"]; this["im"] = tmp; tmp = res["re"]; res["re"] = -res["im"]; res["im"] = tmp; return res; }
...
},
'Complex': function (x) {
return x.acsch();
},
'BigNumber': function (x) {
return new type.BigNumber(1).div(x).asinh();
},
'Array | Matrix': function (x) {
return deepMap(x, acsch);
}
});
...
atan = function () { var a = this["re"]; var b = this["im"]; if (a === 0) { if (b === 1) { return new Complex(0, Infinity); } if (b === -1) { return new Complex(0, -Infinity); } } var d = a * a + (1.0 - b) * (1.0 - b); var t1 = new Complex( (1 - b * b - a * a) / d, -2 * a / d).log(); return new Complex(-0.5 * t1["im"], 0.5 * t1["re"]); }
...
* cot, atan
*
* @param {number | Complex | Array | Matrix} x Function input
* @return {number | Complex | Array | Matrix} The arc cotangent of x
*/
var acot = typed('acot', {
'number': function (x) {
return Math.atan(1 / x);
},
'Complex': function (x) {
return x.acot();
},
'BigNumber': function (x) {
...
atanh = function () { var a = this["re"]; var b = this["im"]; var noIM = a > 1 && b === 0; var oneMinus = 1 - a; var onePlus = 1 + a; var d = oneMinus * oneMinus + b * b; var x = (d !== 0) ? new Complex( (onePlus * oneMinus - b * b) / d, (b * oneMinus + onePlus * b) / d) : new Complex( (a !== -1) ? (a / 0) : 0, (b !== 0) ? (b / 0) : 0); var temp = x["re"]; x["re"] = logHypot(x["re"], x["im"]) / 2; x["im"] = Math.atan2(x["im"], temp) / 2; if (noIM) { x["im"] = -x["im"]; } return x; }
...
},
'Complex': function (x) {
return x.acoth();
},
'BigNumber': function (x) {
return new type.BigNumber(1).div(x).atanh();
},
'Array | Matrix': function (x) {
return deepMap(x, acoth);
}
});
...
ceil = function (places) { places = Math.pow(10, places || 0); return new Complex( Math.ceil(this["re"] * places) / places, Math.ceil(this["im"] * places) / places); }
...
/**
* Round a value towards plus infinity
* If `x` is complex, both real and imaginary part are rounded towards plus infinity.
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.ceil(x)
*
* Examples:
*
* math.ceil(3.2); // returns number 4
* math.ceil(3.8); // returns number 4
* math.ceil(-4.2); // returns number -4
* math.ceil(-4.7); // returns number -4
...
clone = function () { return new Complex(this["re"], this["im"]); }
...
return desc;
};
/**
* Export the help object to JSON
*/
Help.prototype.toJSON = function () {
var obj = object.clone(this.doc);
obj.mathjs = 'Help';
return obj;
};
/**
* Instantiate a Help object from a JSON object
* @param {Object} json
...
conjugate = function () { return new Complex(this["re"], -this["im"]); }
...
},
'BigNumber': function (x) {
return x;
},
'Complex': function (x) {
return x.conjugate();
},
'Array | Matrix': function (x) {
return deepMap(x, conj);
}
});
...
cos = function () { var a = this["re"]; var b = this["im"]; return new Complex( Math.cos(a) * Math.cosh(b), -Math.sin(a) * Math.sinh(b)); }
...
var u1, u2,
picked = -1;
// We reject values outside of the interval [0, 1]
// TODO: check if it is ok to do that?
while (picked < 0 || picked > 1) {
u1 = rng();
u2 = rng();
picked = 1/6 * Math.pow(-2 * Math.log(u1), 0.5) * Math.cos(2 * Math.PI * u2) +
0.5;
}
return picked;
}
}
};
distribution.toTex = undefined; // use default template
...
cosh = function () { var a = this["re"]; var b = this["im"]; return new Complex( Math.cosh(a) * Math.cos(b), Math.sinh(a) * Math.sin(b)); }
...
* Calculate the hyperbolic cosine of a value,
* defined as `cosh(x) = 1/2 * (exp(x) + exp(-x))`.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.cosh(x)
*
* Examples:
*
* math.cosh(0.5); // returns number 1.1276259652063807
*
* See also:
*
...
cot = function () { var a = 2 * this["re"]; var b = 2 * this["im"]; var d = Math.cos(a) - Math.cosh(b); return new Complex( -Math.sin(a) / d, Math.sinh(b) / d); }
...
* Syntax:
*
* math.acot(x)
*
* Examples:
*
* math.acot(0.5); // returns number 0.4636476090008061
* math.acot(math.cot(1.5)); // returns number 1.5
*
* math.acot(2); // returns Complex 1.5707963267948966 -1.3169578969248166 i
*
* See also:
*
* cot, atan
*
...
coth = function () { var a = 2 * this["re"]; var b = 2 * this["im"]; var d = Math.cosh(a) - Math.cos(b); return new Complex( Math.sinh(a) / d, -Math.sin(b) / d); }
...
* Calculate the hyperbolic cotangent of a value,
* defined as `coth(x) = 1 / tanh(x)`.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.coth(x)
*
* Examples:
*
* // coth(x) = 1 / tanh(x)
* math.coth(2); // returns 1.0373147207275482
* 1 / math.tanh(2); // returns 1.0373147207275482
*
...
csc = function () { var a = this["re"]; var b = this["im"]; var d = 0.5 * Math.cosh(2 * b) - 0.5 * Math.cos(2 * a); return new Complex( Math.sin(a) * Math.cosh(b) / d, -Math.cos(a) * Math.sinh(b) / d); }
...
* Syntax:
*
* math.acsc(x)
*
* Examples:
*
* math.acsc(0.5); // returns number 0.5235987755982989
* math.acsc(math.csc(1.5)); // returns number ~1.5
*
* math.acsc(2); // returns Complex 1.5707963267948966 -1.3169578969248166 i
*
* See also:
*
* csc, asin, asec
*
...
csch = function () { var a = this["re"]; var b = this["im"]; var d = Math.cos(2 * b) - Math.cosh(2 * a); return new Complex( -2 * Math.sinh(a) * Math.cos(b) / d, 2 * Math.cosh(a) * Math.sin(b) / d); }
...
* Calculate the hyperbolic cosecant of a value,
* defined as `csch(x) = 1 / sinh(x)`.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.csch(x)
*
* Examples:
*
* // csch(x) = 1/ sinh(x)
* math.csch(0.5); // returns 1.9190347513349437
* 1 / math.sinh(0.5); // returns 1.9190347513349437
*
...
div = function (a, b) { parse(a, b); // mutates P a = this["re"]; b = this["im"]; var c = P["re"]; var d = P["im"]; var t, x; // Divisor is zero if (0 === c && 0 === d) { return new Complex( (a !== 0) ? (a / 0) : 0, (b !== 0) ? (b / 0) : 0); } // Divisor is rational if (0 === d) { return new Complex(a / c, b / c); } if (Math.abs(c) < Math.abs(d)) { x = c / d; t = c * x + d; return new Complex( (a * x + b) / t, (b * x - a) / t); } else { x = d / c; t = d * x + c; return new Complex( (a + b * x) / t, (b - a * x) / t); } }
...
setLazyConstant(math, 'e', function () {return bigConstants.e(type.BigNumber)});
setLazyConstant(math, 'phi', function () {return bigConstants.phi(type.BigNumber)}); // golden ratio, (1+sqrt(5))/2
// uppercase constants (for compatibility with built-in Math)
setLazyConstant(math, 'E', function () {return math.e;});
setLazyConstant(math, 'LN2', function () {return new type.BigNumber(2).ln();});
setLazyConstant(math, 'LN10', function () {return new type.BigNumber(10).ln()});
setLazyConstant(math, 'LOG2E', function () {return new type.BigNumber(1).div
span>(new type.BigNumber(2).ln());});
setLazyConstant(math, 'LOG10E', function () {return new type.BigNumber(1).div(new type.BigNumber(10).ln())});
setLazyConstant(math, 'PI', function () {return math.pi});
setLazyConstant(math, 'SQRT1_2', function () {return new type.BigNumber('0.5').sqrt()});
setLazyConstant(math, 'SQRT2', function () {return new type.BigNumber(2).sqrt()});
}
else {
setConstant(math, 'Infinity', Infinity);
...
equals = function (a, b) { parse(a, b); // mutates P return Math.abs(P["re"] - this["re"]) <= Complex["EPSILON"] && Math.abs(P["im"] - this["im"]) <= Complex["EPSILON"]; }
...
if (inv) {
root = root.neg();
}
if (root.isZero()) {
throw new Error('Root must be non-zero');
}
if (a.isNegative() && !root.abs().mod(2).equals(1)) {
throw new Error('Root must be odd when a is negative.');
}
// edge cases zero and infinity
if (a.isZero()) {
return inv ? new Big(Infinity) : 0;
}
...
exp = function () { var tmp = Math.exp(this["re"]); if (this["im"] === 0) { //return new Complex(tmp, 0); } return new Complex( tmp * Math.cos(this["im"]), tmp * Math.sin(this["im"])); }
...
// https://www.wikiwand.com/en/Cube_root#/Complex_numbers
var arg_3 = x.arg() / 3;
var abs = x.abs();
// principal root:
var principal = new type.Complex(_cbrtNumber(abs), 0).mul(
new type.Complex(0, arg_3).exp());
if (allRoots) {
var all = [
principal,
new type.Complex(_cbrtNumber(abs), 0).mul(
new type.Complex(0, arg_3 + Math.PI * 2 / 3).exp()),
new type.Complex(_cbrtNumber(abs), 0).mul(
...
floor = function (places) { places = Math.pow(10, places || 0); return new Complex( Math.floor(this["re"] * places) / places, Math.floor(this["im"] * places) / places); }
...
* ceil, floor, round
*
* @param {number | BigNumber | Fraction | Complex | Array | Matrix} x Number to be rounded
* @return {number | BigNumber | Fraction | Complex | Array | Matrix} Rounded value
*/
var fix = typed('fix', {
'number': function (x) {
return (x > 0) ? Math.floor(x) : Math.ceil(x);
},
'Complex': function (x) {
return new type.Complex(
(x.re > 0) ? Math.floor(x.re) : Math.ceil(x.re),
(x.im > 0) ? Math.floor(x.im) : Math.ceil(x.im)
);
...
format = function (options) { var str = ''; var im = this.im; var re = this.re; var strRe = format(this.re, options); var strIm = format(this.im, options); // round either re or im when smaller than the configured precision var precision = isNumber(options) ? options : options ? options.precision : null; if (precision !== null) { var epsilon = Math.pow(10, -precision); if (Math.abs(re / im) < epsilon) { re = 0; } if (Math.abs(im / re) < epsilon) { im = 0; } } if (im == 0) { // real value str = strRe; } else if (re == 0) { // purely complex value if (im == 1) { str = 'i'; } else if (im == -1) { str = '-i'; } else { str = strIm + 'i'; } } else { // complex value if (im > 0) { if (im == 1) { str = strRe + ' + i'; } else { str = strRe + ' + ' + strIm + 'i'; } } else { if (im == -1) { str = strRe + ' - i'; } else { str = strRe + ' - ' + strIm.substring(1) + 'i'; } } } return str; }
...
* Helper function to format a value. Regular numbers will be rounded
* to 14 digits to prevent round-off errors from showing up.
* @param {*} value
*/
function format(value) {
var math = getMath();
return math.format(value, {
fn: function (value) {
if (typeof value === 'number') {
// round numbers
return math.format(value, PRECISION);
}
else {
return math.format(value);
...
inverse = function () { var a = this["re"]; var b = this["im"]; var d = a * a + b * b; return new Complex( a !== 0 ? a / d : 0, b !== 0 ?-b / d : 0); }
n/a
isNaN = function () { return isNaN(this['re']) || isNaN(this['im']); }
...
},
'Complex, Complex': function (x, y) {
return (x.re !== 0 || x.im !== 0) && (y.re !== 0 || y.im !== 0);
},
'BigNumber, BigNumber': function (x, y) {
return !x.isZero() && !y.isZero() && !x.isNaN() && !y
.isNaN();
},
'Unit, Unit': function (x, y) {
return and(x.value, y.value);
},
'Matrix, Matrix': function (x, y) {
...
log = function () { var a = this["re"]; var b = this["im"]; if (b === 0 && a > 0) { //return new Complex(Math.log(a), 0); } return new Complex( logHypot(a, b), Math.atan2(b, a)); }
...
```js
// load math.js
var math = require('mathjs');
// functions and constants
math.round(math.e, 3); // 2.718
math.atan2(3, -3) / math.pi; // 0.75
math.log(1000, 10); // 3
math.sqrt(-4); // 2i
math.pow([[-1, 2], [3, 1]], 2); // [[7, 0], [0, 7]]
math.derivative('x^2 + x', 'x'); // 2 * x + 1
// expressions
math.eval('12 / (2.3 + 0.7)'); // 4
math.eval('5.08 cm to inch'); // 2 inch
...
mul = function (a, b) { parse(a, b); // mutates P // Besides the addition/subtraction, this helps having a solution for rational Infinity if (P['im'] === 0 && this['im'] === 0) { return new Complex(this['re'] * P['re'], 0); } return new Complex( this["re"] * P["re"] - this["im"] * P["im"], this["re"] * P["im"] + this["im"] * P["re"]); }
...
function _cbrtComplex(x, allRoots) {
// https://www.wikiwand.com/en/Cube_root#/Complex_numbers
var arg_3 = x.arg() / 3;
var abs = x.abs();
// principal root:
var principal = new type.Complex(_cbrtNumber(abs), 0).mul(
new type.Complex(0, arg_3).exp());
if (allRoots) {
var all = [
principal,
new type.Complex(_cbrtNumber(abs), 0).mul(
new type.Complex(0, arg_3 + Math.PI * 2 / 3).exp()),
...
neg = function () { return new Complex(-this["re"], -this["im"]); }
...
// http://en.wikipedia.org/wiki/Euclidean_algorithm
var zero = new type.BigNumber(0);
while (!b.isZero()) {
var r = a.mod(b);
a = b;
b = r;
}
return a.lt(zero) ? a.neg() : a;
}
}
/**
* Calculate gcd for numbers
* @param {number} a
* @param {number} b
...
pow = function (a, b) {
parse(a, b); // mutates P
a = this["re"];
b = this["im"];
if (a === 0 && b === 0) {
return new Complex(0, 0);
}
var arg = Math.atan2(b, a);
var loh = logHypot(a, b);
if (P["im"] === 0) {
if (b === 0 && a >= 0) {
return new Complex(Math.pow(a, P["re"]), 0);
} else if (a === 0) {
switch (P["re"] % 4) {
case 0:
return new Complex(Math.pow(b, P["re"]), 0);
case 1:
return new Complex(0, Math.pow(b, P["re"]));
case 2:
return new Complex(-Math.pow(b, P["re"]), 0);
case 3:
return new Complex(0, -Math.pow(b, P["re"]));
}
}
}
/* I couldn"t find a good formula, so here is a derivation and optimization
*
* z_1^z_2 = (a + bi)^(c + di)
* = exp((c + di) * log(a + bi)
* = pow(a^2 + b^2, (c + di) / 2) * exp(i(c + di)atan2(b, a))
* =>...
* Re = (pow(a^2 + b^2, c / 2) * exp(-d * atan2(b, a))) * cos(d * log(a^2 + b^2) / 2 + c * atan2(b, a))
* Im = (pow(a^2 + b^2, c / 2) * exp(-d * atan2(b, a))) * sin(d * log(a^2 + b^2) / 2 + c * atan2(b, a))
*
* =>...
* Re = exp(c * log(sqrt(a^2 + b^2)) - d * atan2(b, a)) * cos(d * log(sqrt(a^2 + b^2)) + c * atan2(b, a))
* Im = exp(c * log(sqrt(a^2 + b^2)) - d * atan2(b, a)) * sin(d * log(sqrt(a^2 + b^2)) + c * atan2(b, a))
*
* =>
* Re = exp(c * logsq2 - d * arg(z_1)) * cos(d * logsq2 + c * arg(z_1))
* Im = exp(c * logsq2 - d * arg(z_1)) * sin(d * logsq2 + c * arg(z_1))
*
*/
a = Math.exp(P["re"] * loh - P["im"] * arg);
b = P["im"] * loh + P["re"] * arg;
return new Complex(
a * Math.cos(b),
a * Math.sin(b));
}
...
var math = require('mathjs');
// functions and constants
math.round(math.e, 3); // 2.718
math.atan2(3, -3) / math.pi; // 0.75
math.log(1000, 10); // 3
math.sqrt(-4); // 2i
math.pow([[-1, 2], [3, 1]], 2); // [[7, 0], [0, 7]]
math.derivative('x^2 + x', 'x'); // 2 * x + 1
// expressions
math.eval('12 / (2.3 + 0.7)'); // 4
math.eval('5.08 cm to inch'); // 2 inch
math.eval('sin(45 deg) ^ 2'); // 0.5
math.eval('9 / 3 + 2i'); // 3 + 2i
...
round = function (places) { places = Math.pow(10, places || 0); return new Complex( Math.round(this["re"] * places) / places, Math.round(this["im"] * places) / places); }
...
[chained operations](http://mathjs.org/docs/chained_operations.html).
```js
// load math.js
var math = require('mathjs');
// functions and constants
math.round(math.e, 3); // 2.718
math.atan2(3, -3) / math.pi; // 0.75
math.log(1000, 10); // 3
math.sqrt(-4); // 2i
math.pow([[-1, 2], [3, 1]], 2); // [[7, 0], [0, 7]]
math.derivative('x^2 + x', 'x'); // 2 * x + 1
// expressions
...
sec = function () { var a = this["re"]; var b = this["im"]; var d = 0.5 * Math.cosh(2 * b) + 0.5 * Math.cos(2 * a); return new Complex( Math.cos(a) * Math.cosh(b) / d, Math.sin(a) * Math.sinh(b) / d); }
...
* Syntax:
*
* math.asec(x)
*
* Examples:
*
* math.asec(0.5); // returns 1.0471975511965979
* math.asec(math.sec(1.5)); // returns 1.5
*
* math.asec(2); // returns 0 + 1.3169578969248166 i
*
* See also:
*
* acos, acot, acsc
*
...
sech = function () { var a = this["re"]; var b = this["im"]; var d = Math.cos(2 * b) + Math.cosh(2 * a); return new Complex( 2 * Math.cosh(a) * Math.cos(b) / d, -2 * Math.sinh(a) * Math.sin(b) / d); }
...
* Calculate the hyperbolic secant of a value,
* defined as `sech(x) = 1 / cosh(x)`.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.sech(x)
*
* Examples:
*
* // sech(x) = 1/ cosh(x)
* math.sech(0.5); // returns 0.886818883970074
* 1 / math.cosh(0.5); // returns 0.886818883970074
*
...
sign = function () { var abs = this["abs"](); return new Complex( this["re"] / abs, this["im"] / abs); }
...
* - -1 when x < 0
* - 0 when x == 0
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.sign(x)
*
* Examples:
*
* math.sign(3.5); // returns 1
* math.sign(-4.2); // returns -1
* math.sign(0); // returns 0
*
...
sin = function () { var a = this["re"]; var b = this["im"]; return new Complex( Math.sin(a) * Math.cosh(b), Math.cos(a) * Math.sinh(b)); }
...
res = 1; // 0! is per definition 1
}
return res;
}
if (n < 0.5) {
return Math.PI / (Math.sin(Math.PI * n) * gamma(1-n));
}
if (n >= 171.35) {
return Infinity; // will overflow
}
if (n > 85.0) { // Extended Stirling Approx
...
sinh = function () { var a = this["re"]; var b = this["im"]; return new Complex( Math.sinh(a) * Math.cos(b), Math.cosh(a) * Math.sin(b)); }
...
*
* math.csch(x)
*
* Examples:
*
* // csch(x) = 1/ sinh(x)
* math.csch(0.5); // returns 1.9190347513349437
* 1 / math.sinh(0.5); // returns 1.9190347513349437
*
* See also:
*
* sinh, sech, coth
*
* @param {number | Complex | Unit | Array | Matrix} x Function input
* @return {number | Complex | Array | Matrix} Hyperbolic cosecant of x
...
sqrt = function () { var a = this["re"]; var b = this["im"]; var r = this["abs"](); var re, im; if (a >= 0 && b === 0) { return new Complex(Math.sqrt(a), 0); } if (a >= 0) { re = 0.5 * Math.sqrt(2.0 * (r + a)); } else { re = Math.abs(b) / Math.sqrt(2 * (r - a)); } if (a <= 0) { im = 0.5 * Math.sqrt(2.0 * (r - a)); } else { im = Math.abs(b) / Math.sqrt(2 * (r + a)); } return new Complex(re, b >= 0 ? im : -im); }
...
// load math.js
var math = require('mathjs');
// functions and constants
math.round(math.e, 3); // 2.718
math.atan2(3, -3) / math.pi; // 0.75
math.log(1000, 10); // 3
math.sqrt(-4); // 2i
math.pow([[-1, 2], [3, 1]], 2); // [[7, 0], [0, 7]]
math.derivative('x^2 + x', 'x'); // 2 * x + 1
// expressions
math.eval('12 / (2.3 + 0.7)'); // 4
math.eval('5.08 cm to inch'); // 2 inch
math.eval('sin(45 deg) ^ 2'); // 0.5
...
sub = function (a, b) { parse(a, b); // mutates P return new Complex( this["re"] - P["re"], this["im"] - P["im"]); }
...
var subtract = typed('subtract', {
'number, number': function (x, y) {
return x - y;
},
'Complex, Complex': function (x, y) {
return x.sub(y);
},
'BigNumber, BigNumber': function (x, y) {
return x.minus(y);
},
'Fraction, Fraction': function (x, y) {
...
tan = function () { var a = 2 * this["re"]; var b = 2 * this["im"]; var d = Math.cos(a) + Math.cosh(b); return new Complex( Math.sin(a) / d, Math.sinh(b) / d); }
...
* Syntax:
*
* math.atan(x)
*
* Examples:
*
* math.atan(0.5); // returns number 0.4636476090008061
* math.atan(math.tan(1.5)); // returns number 1.5
*
* math.atan(2); // returns Complex 1.5707963267948966 -1.3169578969248166 i
*
* See also:
*
* tan, asin, acos
*
...
tanh = function () { var a = 2 * this["re"]; var b = 2 * this["im"]; var d = Math.cosh(a) + Math.cos(b); return new Complex( Math.sinh(a) / d, Math.sin(b) / d); }
...
*
* math.coth(x)
*
* Examples:
*
* // coth(x) = 1 / tanh(x)
* math.coth(2); // returns 1.0373147207275482
* 1 / math.tanh(2); // returns 1.0373147207275482
*
* See also:
*
* sinh, tanh, cosh
*
* @param {number | Complex | Unit | Array | Matrix} x Function input
* @return {number | Complex | Array | Matrix} Hyperbolic cotangent of x
...
toJSON = function () { return { mathjs: 'Complex', re: this.re, im: this.im }; }
n/a
toPolar = function () { return { r: this.abs(), phi: this.arg() }; }
n/a
toString = function () { var a = this["re"]; var b = this["im"]; var ret = ""; if (isNaN(a) || isNaN(b)) { return "NaN"; } if (a !== 0) { ret+= a; } if (b !== 0) { if (a !== 0) { ret+= b < 0 ? " - " : " + "; } else if (b < 0) { ret+= "-"; } b = Math.abs(b); if (1 !== b) { ret+= b; } ret+= "i"; } if (!ret) return "0"; return ret; }
...
}
else {
scope.ans = res;
console.log(format(res));
}
}
else if (res instanceof math.type.Help) {
console.log(res.toString());
}
else {
scope.ans = res;
console.log(format(res));
}
}
}
...
toVector = function () { return [this["re"], this["im"]]; }
n/a
valueOf = function () { var a = this["re"]; var b = this["im"]; var ret = ""; if (isNaN(a) || isNaN(b)) { return "NaN"; } if (a !== 0) { ret+= a; } if (b !== 0) { if (a !== 0) { ret+= b < 0 ? " - " : " + "; } else if (b < 0) { ret+= "-"; } b = Math.abs(b); if (1 !== b) { ret+= b; } ret+= "i"; } if (!ret) return "0"; return ret; }
...
throw new TypeError('Cannot implicitly convert a Fraction to BigNumber or vice versa. ' +
'Use function bignumber(x) to convert to BigNumber or fraction(x) to convert to Fraction.');
}
}, {
from: 'Fraction',
to: 'Complex',
convert: function (x) {
return new type.Complex(x.valueOf(), 0);
}
}, {
from: 'number',
to: 'Fraction',
convert: function (x) {
if (digits(x) > 15) {
throw new TypeError('Cannot implicitly convert a number with >15 significant digits to Fraction ' +
...
function DenseMatrix(data, datatype) { if (!(this instanceof DenseMatrix)) throw new SyntaxError('Constructor must be called with the new operator'); if (datatype && !isString(datatype)) throw new Error('Invalid datatype: ' + datatype); if (data && data.isMatrix === true) { // check data is a DenseMatrix if (data.type === 'DenseMatrix') { // clone data & size this._data = object.clone(data._data); this._size = object.clone(data._size); this._datatype = datatype || data._datatype; } else { // build data from existing matrix this._data = data.toArray(); this._size = data.size(); this._datatype = datatype || data._datatype; } } else if (data && isArray(data.data) && isArray(data.size)) { // initialize fields from JSON representation this._data = data.data; this._size = data.size; this._datatype = datatype || data.datatype; } else if (isArray(data)) { // replace nested Matrices with Arrays this._data = preprocess(data); // get the dimensions of the array this._size = array.size(this._data); // verify the dimensions of the array, TODO: compute size while processing array array.validate(this._data, this._size); // data type unknown this._datatype = datatype; } else if (data) { // unsupported type throw new TypeError('Unsupported type of data (' + util.types.type(data) + ')'); } else { // nothing provided this._data = []; this._size = [0]; this._datatype = datatype; } }
...
return new type.Fraction(0);
}
}, {
from: 'Array',
to: 'Matrix',
convert: function (array) {
// TODO: how to decide on the right type of matrix to create?
return new type.DenseMatrix(array);
}
}, {
from: 'Matrix',
to: 'Array',
convert: function (matrix) {
return matrix.valueOf();
}
...
_swapRows = function (i, j, data) { // swap values i <-> j var vi = data[i]; data[i] = data[j]; data[j] = vi; }
...
throw new Error('Only two dimensional matrix is supported');
}
// validate index
validateIndex(i, this._size[0]);
validateIndex(j, this._size[0]);
// swap rows
DenseMatrix._swapRows(i, j, this._data);
// return current instance
return this;
};
/**
* Swap rows i and j in Dense Matrix data structure.
*
...
diagonal = function (size, value, k, defaultValue, datatype) { if (!isArray(size)) throw new TypeError('Array expected, size parameter'); if (size.length !== 2) throw new Error('Only two dimensions matrix are supported'); // map size & validate size = size.map(function (s) { // check it is a big number if (s && s.isBigNumber === true) { // convert it s = s.toNumber(); } // validate arguments if (!isNumber(s) || !isInteger(s) || s < 1) { throw new Error('Size values must be positive integers'); } return s; }); // validate k if any if (k) { // convert BigNumber to a number if (k && k.isBigNumber === true) k = k.toNumber(); // is must be an integer if (!isNumber(k) || !isInteger(k)) { throw new TypeError ('The parameter k must be an integer number'); } } else { // default value k = 0; } if (defaultValue && isString(datatype)) { // convert defaultValue to the same datatype defaultValue = typed.convert(defaultValue, datatype); } var kSuper = k > 0 ? k : 0; var kSub = k < 0 ? -k : 0; // rows and columns var rows = size[0]; var columns = size[1]; // number of non-zero items var n = Math.min(rows - kSub, columns - kSuper); // value extraction function var _value; // check value if (isArray(value)) { // validate array if (value.length !== n) { // number of values in array must be n throw new Error('Invalid value array length'); } // define function _value = function (i) { // return value @ i return value[i]; }; } else if (value && value.isMatrix === true) { // matrix size var ms = value.size(); // validate matrix if (ms.length !== 1 || ms[0] !== n) { // number of values in array must be n throw new Error('Invalid matrix length'); } // define function _value = function (i) { // return value @ i return value.get([i]); }; } else { // define function _value = function () { // return value return value; }; } // discover default value if needed if (!defaultValue) { // check first value in array defaultValue = (_value(0) && _value(0).isBigNumber === true) ? new type.BigNumber(0) : 0; } // empty array var data = []; // check we need to resize array if (size.length > 0) { // resize array data = array.resize(data, size, defaultValue); // fill diagonal for (var d = 0; d < n; d++) { data[d + kSub][d + kSuper] = _value(d); } } // create DenseMatrix return new DenseMatrix({ data: data, size: [rows, columns] }); }
...
function _createDiagonalMatrix(x, k, format, l, kSub, kSuper) {
// matrix size
var ms = [l + kSub, l + kSuper];
// get matrix constructor
var F = type.Matrix.storage(format || 'dense');
// create diagonal matrix
var m = F.diagonal(ms, x, k);
// check we need to return a matrix
return format !== null ? m : m.valueOf();
}
function _getDiagonal(x, k, format, s, kSub, kSuper) {
// check x is a Matrix
if (x && x.isMatrix === true) {
...
fromJSON = function (json) { return new DenseMatrix(json); }
...
* @param {string} key
* @param {*} value
* @returns {*} Returns the revived object
*/
return function reviver(key, value) {
var constructor = type[value && value.mathjs];
if (constructor && typeof constructor.fromJSON === 'function') {
return constructor.fromJSON(value);
}
return value;
}
}
exports.name = 'reviver';
...
clone = function () { var m = new DenseMatrix({ data: object.clone(this._data), size: object.clone(this._size), datatype: this._datatype }); return m; }
...
return desc;
};
/**
* Export the help object to JSON
*/
Help.prototype.toJSON = function () {
var obj = object.clone(this.doc);
obj.mathjs = 'Help';
return obj;
};
/**
* Instantiate a Help object from a JSON object
* @param {Object} json
...
create = function (data, datatype) { return new DenseMatrix(data, datatype); }
...
* false (default), output type can vary depending
* on input values. For example `math.sqrt(-4)`
* returns `complex('2i')` when predictable is false, and
* returns `NaN` when true.
*/
function create (config) {
// create a new math.js instance
var math = core.create(config);
math.create = create;
// import data types, functions, constants, expression parser, etc.
math['import'](require('./lib'));
return math;
}
...
datatype = function () { return this._datatype; }
...
return 'dense';
};
/**
* Get the datatype of the data stored in the matrix.
*
* Usage:
* var format = matrix.datatype() // retrieve matrix datatype
*
* @memberof DenseMatrix
* @return {string} The datatype.
*/
DenseMatrix.prototype.datatype = function () {
return this._datatype;
};
...
diagonal = function (k) { // validate k if any if (k) { // convert BigNumber to a number if (k.isBigNumber === true) k = k.toNumber(); // is must be an integer if (!isNumber(k) || !isInteger(k)) { throw new TypeError ('The parameter k must be an integer number'); } } else { // default value k = 0; } var kSuper = k > 0 ? k : 0; var kSub = k < 0 ? -k : 0; // rows & columns var rows = this._size[0]; var columns = this._size[1]; // number diagonal values var n = Math.min(rows - kSub, columns - kSuper); // x is a matrix get diagonal from matrix var data = []; // loop rows for (var i = 0; i < n; i++) { data[i] = this._data[i + kSub][i + kSuper]; } // create DenseMatrix return new DenseMatrix({ data: data, size: [n], datatype: this._datatype }); }
...
function _createDiagonalMatrix(x, k, format, l, kSub, kSuper) {
// matrix size
var ms = [l + kSub, l + kSuper];
// get matrix constructor
var F = type.Matrix.storage(format || 'dense');
// create diagonal matrix
var m = F.diagonal(ms, x, k);
// check we need to return a matrix
return format !== null ? m : m.valueOf();
}
function _getDiagonal(x, k, format, s, kSub, kSuper) {
// check x is a Matrix
if (x && x.isMatrix === true) {
...
forEach = function (callback) { // matrix instance var me = this; var recurse = function (value, index) { if (isArray(value)) { value.forEach(function (child, i) { recurse(child, index.concat(i)); }); } else { callback(value, index, me); } }; recurse(this._data, []); }
...
if (def.indexOf(keyword) == 0) {
matches.push(def);
}
}
}
// commandline keywords
['exit', 'quit', 'clear'].forEach(function (cmd) {
if (cmd.indexOf(keyword) == 0) {
matches.push(cmd);
}
});
// math functions and constants
var ignore = ['expr', 'type'];
...
format = function (options) { return string.format(this._data, options); }
...
* Helper function to format a value. Regular numbers will be rounded
* to 14 digits to prevent round-off errors from showing up.
* @param {*} value
*/
function format(value) {
var math = getMath();
return math.format(value, {
fn: function (value) {
if (typeof value === 'number') {
// round numbers
return math.format(value, PRECISION);
}
else {
return math.format(value);
...
get = function (index) { if (!isArray(index)) throw new TypeError('Array expected'); if (index.length != this._size.length) throw new DimensionError(index.length, this._size.length); // check index for (var x = 0; x < index.length; x++) validateIndex(index[x], this._size[x]); var data = this._data; for (var i = 0, ii = index.length; i < ii; i++) { var index_i = index[i]; validateIndex(index_i, data.length); data = data[index_i]; } return data; }
...
* Parser contains methods to evaluate or parse expressions, and has a number
* of convenience methods to get, set, and remove variables from memory. Parser
* keeps a scope containing variables in memory, which is used for all
* evaluations.
*
* Methods:
* var result = parser.eval(expr); // evaluate an expression
* var value = parser.get(name); // retrieve a variable from the parser
* var values = parser.getAll(); // retrieve all defined variables
* parser.set(name, value); // set a variable in the parser
* parser.remove(name); // clear a variable from the
* // parsers scope
* parser.clear(); // clear the parsers scope
*
* Example usage:
...
map = function (callback) { // matrix instance var me = this; var recurse = function (value, index) { if (isArray(value)) { return value.map(function (child, i) { return recurse(child, index.concat(i)); }); } else { return callback(value, index, me); } }; // return dense format return new DenseMatrix({ data: recurse(this._data, []), size: object.clone(this._size), datatype: this._datatype }); }
...
if (res && res.isResultSet) {
// we can have 0 or 1 results in the ResultSet, as the CLI
// does not allow multiple expressions separated by a return
res = res.entries[0];
node = node.blocks
.filter(function (entry) { return entry.visible; })
.map(function (entry) { return entry.node })[0];
}
if (node) {
if (node.isAssignmentNode) {
var name = findSymbolName(node);
if (name != null) {
scope.ans = scope[name];
...
reshape = function (size, copy) { var m = copy ? this.clone() : this; m._data = array.reshape(m._data, size); m._size = size.slice(0); return m; }
...
var matrix = load(require('../../type/matrix/function/matrix'));
/**
* Reshape a multi dimensional array to fit the specified dimensions
*
* Syntax:
*
* math.reshape(x, sizes)
*
* Examples:
*
* math.reshape([1, 2, 3, 4, 5, 6], [2, 3]);
* // returns Array [[1, 2, 3], [4, 5, 6]]
*
* math.reshape([[1, 2], [3, 4]], [1, 4]);
...
resize = function (size, defaultValue, copy) { // validate arguments if (!isArray(size)) throw new TypeError('Array expected'); // matrix to resize var m = copy ? this.clone() : this; // resize matrix return _resize(m, size, defaultValue); }
...
// get matrix storage constructor
var F = type.Matrix.storage(format);
// create diagonal matrix (use optimized implementation for storage format)
return F.diagonal(size, one, 0, defaultValue);
}
// create and resize array
var res = array.resize([], size, defaultValue);
// fill in ones on the diagonal
var minimum = rows < cols ? rows : cols;
// fill diagonal
for (var d = 0; d < minimum; d++) {
res[d][d] = one;
}
return res;
...
set = function (index, value, defaultValue) { if (!isArray(index)) throw new TypeError('Array expected'); if (index.length < this._size.length) throw new DimensionError(index.length, this._size.length, '<'); var i, ii, index_i; // enlarge matrix when needed var size = index.map(function (i) { return i + 1; }); _fit(this, size, defaultValue); // traverse over the dimensions var data = this._data; for (i = 0, ii = index.length - 1; i < ii; i++) { index_i = index[i]; validateIndex(index_i, data.length); data = data[index_i]; } // set new value index_i = index[index.length - 1]; validateIndex(index_i, data.length); data[index_i] = value; return this; }
...
* keeps a scope containing variables in memory, which is used for all
* evaluations.
*
* Methods:
* var result = parser.eval(expr); // evaluate an expression
* var value = parser.get(name); // retrieve a variable from the parser
* var values = parser.getAll(); // retrieve all defined variables
* parser.set(name, value); // set a variable in the parser
* parser.remove(name); // clear a variable from the
* // parsers scope
* parser.clear(); // clear the parsers scope
*
* Example usage:
* var parser = new Parser();
* // Note: there is a convenience method which can be used instead:
...
size = function () { return this._size.slice(0); // return a clone of _size }
...
};
if (!Array.isArray(array) || !Array.isArray(sizes)) {
throw new TypeError('Array expected');
}
if (sizes.length === 0) {
throw new DimensionError(0, product(exports.size(array)), '!=');
}
try {
newArray = _reshape(flatArray, sizes);
} catch (e) {
if (e instanceof DimensionError) {
throw new DimensionError(
...
storage = function () { return 'dense'; }
...
// we extend the signatures of addScalar with signatures dealing with matrices
'Matrix, Matrix': function (x, y) {
// result
var c;
// process matrix storage
switch (x.storage()) {
case 'sparse':
switch (y.storage()) {
case 'sparse':
// sparse + sparse
c = algorithm04(x, y, addScalar);
break;
default:
...
subset = function (index, replacement, defaultValue) { switch (arguments.length) { case 1: return _get(this, index); // intentional fall through case 2: case 3: return _set(this, index, replacement, defaultValue); default: throw new SyntaxError('Wrong number of arguments'); } }
...
function factory (type, config, load, typed) {
var matrix = load(require('../../type/matrix/function/matrix'));
/**
* Get or set a subset of a matrix or string.
*
* Syntax:
* math.subset(value, index) // retrieve a subset
* math.subset(value, index, replacement [, defaultValue]) // replace a subset
*
* Examples:
*
* // get a subset
* var d = [[1, 2], [3, 4]];
* math.subset(d, math.index(1, 0)); // returns 3
...
swapRows = function (i, j) { // check index if (!isNumber(i) || !isInteger(i) || !isNumber(j) || !isInteger(j)) { throw new Error('Row index must be positive integers'); } // check dimensions if (this._size.length !== 2) { throw new Error('Only two dimensional matrix is supported'); } // validate index validateIndex(i, this._size[0]); validateIndex(j, this._size[0]); // swap rows DenseMatrix._swapRows(i, j, this._data); // return current instance return this; }
n/a
toArray = function () { return object.clone(this._data); }
...
'... number | BigNumber': _hypot,
'Array': function (x) {
return hypot.apply(hypot, flatten(x));
},
'Matrix': function (x) {
return hypot.apply(hypot, flatten(x.toArray()));
}
});
/**
* Calculate the hypotenusa for an Array with values
* @param {Array.<number | BigNumber>} args
* @return {number | BigNumber} Returns the result
...
toJSON = function () { return { mathjs: 'DenseMatrix', data: this._data, size: this._size, datatype: this._datatype }; }
n/a
toString = function () { return string.format(this._data); }
...
}
else {
scope.ans = res;
console.log(format(res));
}
}
else if (res instanceof math.type.Help) {
console.log(res.toString());
}
else {
scope.ans = res;
console.log(format(res));
}
}
}
...
valueOf = function () { return this._data; }
...
throw new TypeError('Cannot implicitly convert a Fraction to BigNumber or vice versa. ' +
'Use function bignumber(x) to convert to BigNumber or fraction(x) to convert to Fraction.');
}
}, {
from: 'Fraction',
to: 'Complex',
convert: function (x) {
return new type.Complex(x.valueOf(), 0);
}
}, {
from: 'number',
to: 'Fraction',
convert: function (x) {
if (digits(x) > 15) {
throw new TypeError('Cannot implicitly convert a number with >15 significant digits to Fraction ' +
...
function FibonacciHeap() { if (!(this instanceof FibonacciHeap)) throw new SyntaxError('Constructor must be called with the new operator'); // initialize fields this._minimum = null; this._size = 0; }
...
*/
function Spa() {
if (!(this instanceof Spa))
throw new SyntaxError('Constructor must be called with the new operator');
// allocate vector, TODO use typed arrays
this._values = [];
this._heap = new type.FibonacciHeap();
}
/**
* Attach type information
*/
Spa.prototype.type = 'Spa';
Spa.prototype.isSpa = true;
...
clear = function () { this._minimum = null; this._size = 0; }
...
* Methods:
* var result = parser.eval(expr); // evaluate an expression
* var value = parser.get(name); // retrieve a variable from the parser
* var values = parser.getAll(); // retrieve all defined variables
* parser.set(name, value); // set a variable in the parser
* parser.remove(name); // clear a variable from the
* // parsers scope
* parser.clear(); // clear the parsers scope
*
* Example usage:
* var parser = new Parser();
* // Note: there is a convenience method which can be used instead:
* // var parser = new math.parser();
*
* // evaluate expressions
...
extractMinimum = function () { // node to remove var node = this._minimum; // check we have a minimum if (node === null) return node; // current minimum var minimum = this._minimum; // get number of children var numberOfChildren = node.degree; // pointer to the first child var x = node.child; // for each child of node do... while (numberOfChildren > 0) { // store node in right side var tempRight = x.right; // remove x from child list x.left.right = x.right; x.right.left = x.left; // add x to root list of heap x.left = minimum; x.right = minimum.right; minimum.right = x; x.right.left = x; // set Parent[x] to null x.parent = null; x = tempRight; numberOfChildren--; } // remove node from root list of heap node.left.right = node.right; node.right.left = node.left; // update minimum if (node == node.right) { // empty minimum = null; } else { // update minimum minimum = node.right; // we need to update the pointer to the root with minimum key minimum = _findMinimumNode(minimum, this._size); } // decrement size of heap this._size--; // update minimum this._minimum = minimum; // return node return node; }
...
* Running time: O(log n) amortized.
* @memberof FibonacciHeap
*/
FibonacciHeap.prototype.remove = function (node) {
// decrease key value
this._minimum = _decreaseKey(this._minimum, node, -1);
// remove the smallest
this.extractMinimum();
};
/**
* Decreases the key value for a heap node, given the new value to take on.
* The structure of the heap may be changed and will not be consolidated.
* Running time: O(1) amortized.
* @memberof FibonacciHeap
...
insert = function (key, value) { // create node var node = { key: key, value: value, degree: 0 }; // check we have a node in the minimum if (this._minimum) { // minimum node var minimum = this._minimum; // update left & right of node node.left = minimum; node.right = minimum.right; minimum.right = node; node.right.left = node; // update minimum node in heap if needed if (smaller(key, minimum.key)) { // node has a smaller key, use it as minimum this._minimum = node; } } else { // set left & right node.left = node; node.right = node; // this is the first node this._minimum = node; } // increment number of nodes in heap this._size++; // return node return node; }
...
* @param {number} i The index
* @param {number | BigNumber | Complex} The value at index i
*/
Spa.prototype.set = function (i, v) {
// check we have a value @ i
if (!this._values[i]) {
// insert in heap
var node = this._heap.insert(i, v);
// set the value @ i
this._values[i] = node;
}
else {
// update the value @ i
this._values[i].value = v;
}
...
isEmpty = function () { return !!this._minimum; }
n/a
remove = function (node) { // decrease key value this._minimum = _decreaseKey(this._minimum, node, -1); // remove the smallest this.extractMinimum(); }
...
* evaluations.
*
* Methods:
* var result = parser.eval(expr); // evaluate an expression
* var value = parser.get(name); // retrieve a variable from the parser
* var values = parser.getAll(); // retrieve all defined variables
* parser.set(name, value); // set a variable in the parser
* parser.remove(name); // clear a variable from the
* // parsers scope
* parser.clear(); // clear the parsers scope
*
* Example usage:
* var parser = new Parser();
* // Note: there is a convenience method which can be used instead:
* // var parser = new math.parser();
...
size = function () { return this._size; }
...
};
if (!Array.isArray(array) || !Array.isArray(sizes)) {
throw new TypeError('Array expected');
}
if (sizes.length === 0) {
throw new DimensionError(0, product(exports.size(array)), '!=');
}
try {
newArray = _reshape(flatArray, sizes);
} catch (e) {
if (e instanceof DimensionError) {
throw new DimensionError(
...
function Fraction(a, b) { if (!(this instanceof Fraction)) { return new Fraction(a, b); } parse(a, b); if (Fraction['REDUCE']) { a = gcd(P["d"], P["n"]); // Abuse a } else { a = 1; } this["s"] = P["s"]; this["n"] = P["n"] / a; this["d"] = P["d"] / a; }
...
to: 'Fraction',
convert: function (x) {
if (digits(x) > 15) {
throw new TypeError('Cannot implicitly convert a number with >15 significant digits to Fraction ' +
'(value: ' + x + '). ' +
'Use function fraction(x) to convert to Fraction.');
}
return new type.Fraction(x);
}
}, {
// FIXME: add conversion from Fraction to number, for example for `sqrt(fraction(1,3))`
// from: 'Fraction',
// to: 'number',
// convert: function (x) {
// return x.valueOf();
...
DivisionByZero = function () { var temp = Error.apply(this, arguments); temp.name = this.name = name; this.stack = temp.stack; this.message = temp.message; }
n/a
InvalidParameter = function () { var temp = Error.apply(this, arguments); temp.name = this.name = name; this.stack = temp.stack; this.message = temp.message; }
n/a
fromJSON = function (json) { return new Fraction(json); }
...
* @param {string} key
* @param {*} value
* @returns {*} Returns the revived object
*/
return function reviver(key, value) {
var constructor = type[value && value.mathjs];
if (constructor && typeof constructor.fromJSON === 'function') {
return constructor.fromJSON(value);
}
return value;
}
}
exports.name = 'reviver';
...
abs = function () { return new Fraction(this["n"], this["d"]); }
...
function factory (type, config, load, typed) {
/**
* Calculate the absolute value of a number. For matrices, the function is
* evaluated element wise.
*
* Syntax:
*
* math.abs(x)
*
* Examples:
*
* math.abs(3.5); // returns number 3.5
* math.abs(-4.2); // returns number 4.2
*
* math.abs([3, -5, -1, 0, 2]); // returns Array [3, 5, 1, 0, 2]
...
add = function (a, b) { parse(a, b); return new Fraction( this["s"] * this["n"] * P["d"] + P["s"] * this["d"] * P["n"], this["d"] * P["d"] ); }
...
math.eval('5.08 cm to inch'); // 2 inch
math.eval('sin(45 deg) ^ 2'); // 0.5
math.eval('9 / 3 + 2i'); // 3 + 2i
math.eval('det([-1, 2; 3, 1])'); // -7
// chaining
math.chain(3)
.add(4)
.multiply(2)
.done(); // 14
```
## Browser support
Math.js works on any ES5 compatible JavaScript engine: node.js 0.10, and Internet Explorer 9 and newer, and all other browsers (
Chrome, Firefox, Safari). If support for old browsers like Internet Explorer 8 is required, the [es5-shim](https://github.com/kriskowal
/es5-shim) library has to be loaded.
...
ceil = function (places) { places = Math.pow(10, places || 0); if (isNaN(this["n"]) || isNaN(this["d"])) { return new Fraction(NaN); } return new Fraction(Math.ceil(places * this["s"] * this["n"] / this["d"]), places); }
...
/**
* Round a value towards plus infinity
* If `x` is complex, both real and imaginary part are rounded towards plus infinity.
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.ceil(x)
*
* Examples:
*
* math.ceil(3.2); // returns number 4
* math.ceil(3.8); // returns number 4
* math.ceil(-4.2); // returns number -4
* math.ceil(-4.7); // returns number -4
...
clone = function () { return new Fraction(this); }
...
return desc;
};
/**
* Export the help object to JSON
*/
Help.prototype.toJSON = function () {
var obj = object.clone(this.doc);
obj.mathjs = 'Help';
return obj;
};
/**
* Instantiate a Help object from a JSON object
* @param {Object} json
...
compare = function (a, b) { parse(a, b); var t = (this["s"] * this["n"] * P["d"] - P["s"] * P["n"] * this["d"]); return (0 < t) - (t < 0); }
...
* is smaller than the configured epsilon. The function cannot be used to
* compare values smaller than approximately 2.22e-16.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.compare(x, y)
*
* Examples:
*
* math.compare(6, 1); // returns 1
* math.compare(2, 3); // returns -1
* math.compare(7, 7); // returns 0
*
...
div = function (a, b) { parse(a, b); return new Fraction( this["s"] * P["s"] * this["n"] * P["d"], this["d"] * P["n"] ); }
...
setLazyConstant(math, 'e', function () {return bigConstants.e(type.BigNumber)});
setLazyConstant(math, 'phi', function () {return bigConstants.phi(type.BigNumber)}); // golden ratio, (1+sqrt(5))/2
// uppercase constants (for compatibility with built-in Math)
setLazyConstant(math, 'E', function () {return math.e;});
setLazyConstant(math, 'LN2', function () {return new type.BigNumber(2).ln();});
setLazyConstant(math, 'LN10', function () {return new type.BigNumber(10).ln()});
setLazyConstant(math, 'LOG2E', function () {return new type.BigNumber(1).div
span>(new type.BigNumber(2).ln());});
setLazyConstant(math, 'LOG10E', function () {return new type.BigNumber(1).div(new type.BigNumber(10).ln())});
setLazyConstant(math, 'PI', function () {return math.pi});
setLazyConstant(math, 'SQRT1_2', function () {return new type.BigNumber('0.5').sqrt()});
setLazyConstant(math, 'SQRT2', function () {return new type.BigNumber(2).sqrt()});
}
else {
setConstant(math, 'Infinity', Infinity);
...
divisible = function (a, b) { parse(a, b); return !(!(P["n"] * this["d"]) || ((this["n"] * P["d"]) % (P["n"] * this["d"]))); }
n/a
equals = function (a, b) { parse(a, b); return this["s"] * this["n"] * P["d"] === P["s"] * P["n"] * this["d"]; // Same as compare() === 0 }
...
if (inv) {
root = root.neg();
}
if (root.isZero()) {
throw new Error('Root must be non-zero');
}
if (a.isNegative() && !root.abs().mod(2).equals(1)) {
throw new Error('Root must be odd when a is negative.');
}
// edge cases zero and infinity
if (a.isZero()) {
return inv ? new Big(Infinity) : 0;
}
...
floor = function (places) { places = Math.pow(10, places || 0); if (isNaN(this["n"]) || isNaN(this["d"])) { return new Fraction(NaN); } return new Fraction(Math.floor(places * this["s"] * this["n"] / this["d"]), places); }
...
* ceil, floor, round
*
* @param {number | BigNumber | Fraction | Complex | Array | Matrix} x Number to be rounded
* @return {number | BigNumber | Fraction | Complex | Array | Matrix} Rounded value
*/
var fix = typed('fix', {
'number': function (x) {
return (x > 0) ? Math.floor(x) : Math.ceil(x);
},
'Complex': function (x) {
return new type.Complex(
(x.re > 0) ? Math.floor(x.re) : Math.ceil(x.re),
(x.im > 0) ? Math.floor(x.im) : Math.ceil(x.im)
);
...
gcd = function (a, b) { parse(a, b); // gcd(a / b, c / d) = gcd(a, c) / lcm(b, d) return new Fraction(gcd(P["n"], this["n"]), P["d"] * this["d"] / gcd(P["d"], this["d"])); }
...
/**
* Calculate the greatest common divisor for two or more values or arrays.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.gcd(a, b)
* math.gcd(a, b, c, ...)
*
* Examples:
*
* math.gcd(8, 12); // returns 4
* math.gcd(-4, 6); // returns 2
* math.gcd(25, 15, -10); // returns 5
...
inverse = function () { return new Fraction(this["s"] * this["d"], this["n"]); }
n/a
lcm = function (a, b) { parse(a, b); // lcm(a / b, c / d) = lcm(a, c) / gcd(b, d) if (P["n"] === 0 && this["n"] === 0) { return new Fraction; } return new Fraction(P["n"] * this["n"] / gcd(P["n"], this["n"]), gcd(P["d"], this["d"])); }
...
*
* lcm(a, b) = abs(a * b) / gcd(a, b)
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.lcm(a, b)
* math.lcm(a, b, c, ...)
*
* Examples:
*
* math.lcm(4, 6); // returns 12
* math.lcm(6, 21); // returns 42
* math.lcm(6, 21, 5); // returns 210
...
mod = function (a, b) {
if (isNaN(this['n']) || isNaN(this['d'])) {
return new Fraction(NaN);
}
if (a === undefined) {
return new Fraction(this["s"] * this["n"] % this["d"], 1);
}
parse(a, b);
if (0 === P["n"] && 0 === this["d"]) {
Fraction(0, 0); // Throw DivisionByZero
}
/*
* First silly attempt, kinda slow
*
return that["sub"]({
"n": num["n"] * Math.floor((this.n / this.d) / (num.n / num.d)),
"d": num["d"],
"s": this["s"]
});*/
/*
* New attempt: a1 / b1 = a2 / b2 * q + r
* => b2 * a1 = a2 * b1 * q + b1 * b2 * r
* => (b2 * a1 % a2 * b1) / (b1 * b2)
*/
return new Fraction(
(this["s"] * P["d"] * this["n"]) % (P["n"] * this["d"]),
P["d"] * this["d"]
);
}
...
if (!a.isInt() || !b.isInt()) {
throw new Error('Parameters in function gcd must be integer numbers');
}
// http://en.wikipedia.org/wiki/Euclidean_algorithm
var zero = new type.BigNumber(0);
while (!b.isZero()) {
var r = a.mod(b);
a = b;
b = r;
}
return a.lt(zero) ? a.neg() : a;
}
}
...
mul = function (a, b) { parse(a, b); return new Fraction( this["s"] * P["s"] * this["n"] * P["n"], this["d"] * P["d"] ); }
...
function _cbrtComplex(x, allRoots) {
// https://www.wikiwand.com/en/Cube_root#/Complex_numbers
var arg_3 = x.arg() / 3;
var abs = x.abs();
// principal root:
var principal = new type.Complex(_cbrtNumber(abs), 0).mul(
new type.Complex(0, arg_3).exp());
if (allRoots) {
var all = [
principal,
new type.Complex(_cbrtNumber(abs), 0).mul(
new type.Complex(0, arg_3 + Math.PI * 2 / 3).exp()),
...
neg = function () { return new Fraction(-this["s"] * this["n"], this["d"]); }
...
// http://en.wikipedia.org/wiki/Euclidean_algorithm
var zero = new type.BigNumber(0);
while (!b.isZero()) {
var r = a.mod(b);
a = b;
b = r;
}
return a.lt(zero) ? a.neg() : a;
}
}
/**
* Calculate gcd for numbers
* @param {number} a
* @param {number} b
...
pow = function (m) { if (m < 0) { return new Fraction(Math.pow(this['s'] * this["d"],-m), Math.pow(this["n"],-m)); } else { return new Fraction(Math.pow(this['s'] * this["n"], m), Math.pow(this["d"], m)); } }
...
var math = require('mathjs');
// functions and constants
math.round(math.e, 3); // 2.718
math.atan2(3, -3) / math.pi; // 0.75
math.log(1000, 10); // 3
math.sqrt(-4); // 2i
math.pow([[-1, 2], [3, 1]], 2); // [[7, 0], [0, 7]]
math.derivative('x^2 + x', 'x'); // 2 * x + 1
// expressions
math.eval('12 / (2.3 + 0.7)'); // 4
math.eval('5.08 cm to inch'); // 2 inch
math.eval('sin(45 deg) ^ 2'); // 0.5
math.eval('9 / 3 + 2i'); // 3 + 2i
...
round = function (places) { places = Math.pow(10, places || 0); if (isNaN(this["n"]) || isNaN(this["d"])) { return new Fraction(NaN); } return new Fraction(Math.round(places * this["s"] * this["n"] / this["d"]), places); }
...
[chained operations](http://mathjs.org/docs/chained_operations.html).
```js
// load math.js
var math = require('mathjs');
// functions and constants
math.round(math.e, 3); // 2.718
math.atan2(3, -3) / math.pi; // 0.75
math.log(1000, 10); // 3
math.sqrt(-4); // 2i
math.pow([[-1, 2], [3, 1]], 2); // [[7, 0], [0, 7]]
math.derivative('x^2 + x', 'x'); // 2 * x + 1
// expressions
...
sub = function (a, b) { parse(a, b); return new Fraction( this["s"] * this["n"] * P["d"] - P["s"] * this["d"] * P["n"], this["d"] * P["d"] ); }
...
var subtract = typed('subtract', {
'number, number': function (x, y) {
return x - y;
},
'Complex, Complex': function (x, y) {
return x.sub(y);
},
'BigNumber, BigNumber': function (x, y) {
return x.minus(y);
},
'Fraction, Fraction': function (x, y) {
...
toContinued = function () { var t; var a = this['n']; var b = this['d']; var res = []; do { res.push(Math.floor(a / b)); t = a % b; a = b; b = t; } while (a !== 1); return res; }
n/a
toFraction = function (excludeWhole) { var whole, str = ""; var n = this["n"]; var d = this["d"]; if (this["s"] < 0) { str+= '-'; } if (d === 1) { str+= n; } else { if (excludeWhole && (whole = Math.floor(n / d)) > 0) { str+= whole; str+= " "; n%= d; } str+= n; str+= '/'; str+= d; } return str; }
n/a
toJSON = function () { return { mathjs: 'Fraction', n: this.s * this.n, d: this.d }; }
n/a
toLatex = function (excludeWhole) { var whole, str = ""; var n = this["n"]; var d = this["d"]; if (this["s"] < 0) { str+= '-'; } if (d === 1) { str+= n; } else { if (excludeWhole && (whole = Math.floor(n / d)) > 0) { str+= whole; n%= d; } str+= "\\frac{"; str+= n; str+= '}{'; str+= d; str+= '}'; } return str; }
n/a
toString = function () { var g; var N = this["n"]; var D = this["d"]; if (isNaN(N) || isNaN(D)) { return "NaN"; } if (!Fraction['REDUCE']) { g = gcd(N, D); N/= g; D/= g; } var p = String(N).split(""); // Numerator chars var t = 0; // Tmp var var ret = [~this["s"] ? "" : "-", "", ""]; // Return array, [0] is zero sign, [1] before comma, [2] after var zeros = ""; // Collection variable for zeros var cycLen = cycleLen(N, D); // Cycle length var cycOff = cycleStart(N, D, cycLen); // Cycle start var j = -1; var n = 1; // str index // rough estimate to fill zeros var length = 15 + cycLen + cycOff + p.length; // 15 = decimal places when no repitation for (var i = 0; i < length; i++, t*= 10) { if (i < p.length) { t+= Number(p[i]); } else { n = 2; j++; // Start now => after comma } if (cycLen > 0) { // If we have a repeating part if (j === cycOff) { ret[n]+= zeros + "("; zeros = ""; } else if (j === cycLen + cycOff) { ret[n]+= zeros + ")"; break; } } if (t >= D) { ret[n]+= zeros + ((t / D) | 0); // Flush zeros, Add current digit zeros = ""; t = t % D; } else if (n > 1) { // Add zeros to the zero buffer zeros+= "0"; } else if (ret[n]) { // If before comma, add zero only if already something was added ret[n]+= "0"; } } // If it's empty, it's a leading zero only ret[0]+= ret[1] || "0"; // If there is something after the comma, add the comma sign if (ret[2]) { return ret[0] + "." + ret[2]; } return ret[0]; }
...
}
else {
scope.ans = res;
console.log(format(res));
}
}
else if (res instanceof math.type.Help) {
console.log(res.toString());
}
else {
scope.ans = res;
console.log(format(res));
}
}
}
...
valueOf = function () { return this["s"] * this["n"] / this["d"]; }
...
throw new TypeError('Cannot implicitly convert a Fraction to BigNumber or vice versa. ' +
'Use function bignumber(x) to convert to BigNumber or fraction(x) to convert to Fraction.');
}
}, {
from: 'Fraction',
to: 'Complex',
convert: function (x) {
return new type.Complex(x.valueOf(), 0);
}
}, {
from: 'number',
to: 'Fraction',
convert: function (x) {
if (digits(x) > 15) {
throw new TypeError('Cannot implicitly convert a number with >15 significant digits to Fraction ' +
...
function Help(doc) { if (!(this instanceof Help)) { throw new SyntaxError('Constructor must be called with the new operator'); } if (!doc) throw new Error('Argument "doc" missing'); this.doc = doc; }
n/a
fromJSON = function (json) { var doc = {}; for (var prop in json) { if (prop !== 'mathjs') { // ignore mathjs field doc[prop] = json[prop]; } } return new Help(doc); }
...
* @param {string} key
* @param {*} value
* @returns {*} Returns the revived object
*/
return function reviver(key, value) {
var constructor = type[value && value.mathjs];
if (constructor && typeof constructor.fromJSON === 'function') {
return constructor.fromJSON(value);
}
return value;
}
}
exports.name = 'reviver';
...
toJSON = function () { var obj = object.clone(this.doc); obj.mathjs = 'Help'; return obj; }
n/a
toString = function () { var doc = this.doc || {}; var desc = '\n'; if (doc.name) { desc += 'Name: ' + doc.name + '\n\n'; } if (doc.category) { desc += 'Category: ' + doc.category + '\n\n'; } if (doc.description) { desc += 'Description:\n ' + doc.description + '\n\n'; } if (doc.syntax) { desc += 'Syntax:\n ' + doc.syntax.join('\n ') + '\n\n'; } if (doc.examples) { desc += 'Examples:\n'; for (var i = 0; i < doc.examples.length; i++) { var expr = doc.examples[i]; desc += ' ' + expr + '\n'; var res; try { res = parser.eval(expr); } catch (e) { res = e; } if (res && !res.isHelp) { desc += ' ' + string.format(res, {precision: 14}) + '\n'; } } desc += '\n'; } if (doc.seealso) { desc += 'See also: ' + doc.seealso.join(', ') + '\n'; } return desc; }
...
}
else {
scope.ans = res;
console.log(format(res));
}
}
else if (res instanceof math.type.Help) {
console.log(res.toString());
}
else {
scope.ans = res;
console.log(format(res));
}
}
}
...
valueOf = function () { var doc = this.doc || {}; var desc = '\n'; if (doc.name) { desc += 'Name: ' + doc.name + '\n\n'; } if (doc.category) { desc += 'Category: ' + doc.category + '\n\n'; } if (doc.description) { desc += 'Description:\n ' + doc.description + '\n\n'; } if (doc.syntax) { desc += 'Syntax:\n ' + doc.syntax.join('\n ') + '\n\n'; } if (doc.examples) { desc += 'Examples:\n'; for (var i = 0; i < doc.examples.length; i++) { var expr = doc.examples[i]; desc += ' ' + expr + '\n'; var res; try { res = parser.eval(expr); } catch (e) { res = e; } if (res && !res.isHelp) { desc += ' ' + string.format(res, {precision: 14}) + '\n'; } } desc += '\n'; } if (doc.seealso) { desc += 'See also: ' + doc.seealso.join(', ') + '\n'; } return desc; }
...
throw new TypeError('Cannot implicitly convert a Fraction to BigNumber or vice versa. ' +
'Use function bignumber(x) to convert to BigNumber or fraction(x) to convert to Fraction.');
}
}, {
from: 'Fraction',
to: 'Complex',
convert: function (x) {
return new type.Complex(x.valueOf(), 0);
}
}, {
from: 'number',
to: 'Fraction',
convert: function (x) {
if (digits(x) > 15) {
throw new TypeError('Cannot implicitly convert a number with >15 significant digits to Fraction ' +
...
function ImmutableDenseMatrix(data, datatype) { if (!(this instanceof ImmutableDenseMatrix)) throw new SyntaxError('Constructor must be called with the new operator'); if (datatype && !isString(datatype)) throw new Error('Invalid datatype: ' + datatype); if ((data && data.isMatrix === true) || isArray(data)) { // use DenseMatrix implementation var matrix = new DenseMatrix(data, datatype); // internal structures this._data = matrix._data; this._size = matrix._size; this._datatype = matrix._datatype; this._min = null; this._max = null; } else if (data && isArray(data.data) && isArray(data.size)) { // initialize fields from JSON representation this._data = data.data; this._size = data.size; this._datatype = data.datatype; this._min = typeof data.min !== 'undefined' ? data.min : null; this._max = typeof data.max !== 'undefined' ? data.max : null; } else if (data) { // unsupported type throw new TypeError('Unsupported type of data (' + util.types.type(data) + ')'); } else { // nothing provided this._data = []; this._size = [0]; this._datatype = datatype; this._min = null; this._max = null; } }
...
// loop array elements
for (var i = 0, l = arg.length; i < l; i++) {
if (typeof arg[i] !== 'number' || !isInteger(arg[i])) {
throw new TypeError('Index parameters must be positive integer numbers');
}
}
// create matrix
return new type.ImmutableDenseMatrix(arg);
}
/**
* Create a clone of the index
* @memberof Index
* @return {Index} clone
*/
...
fromJSON = function (json) { return new ImmutableDenseMatrix(json); }
...
* @param {string} key
* @param {*} value
* @returns {*} Returns the revived object
*/
return function reviver(key, value) {
var constructor = type[value && value.mathjs];
if (constructor && typeof constructor.fromJSON === 'function') {
return constructor.fromJSON(value);
}
return value;
}
}
exports.name = 'reviver';
...
clone = function () { var m = new ImmutableDenseMatrix({ data: object.clone(this._data), size: object.clone(this._size), datatype: this._datatype }); return m; }
...
return desc;
};
/**
* Export the help object to JSON
*/
Help.prototype.toJSON = function () {
var obj = object.clone(this.doc);
obj.mathjs = 'Help';
return obj;
};
/**
* Instantiate a Help object from a JSON object
* @param {Object} json
...
max = function () { // check max has been calculated before if (this._max === null) { // maximum var m = null; // compute max this.forEach(function (v) { if (m === null || smaller(m, v)) m = v; }); this._max = m !== null ? m : undefined; } return this._max; }
...
* @return {number} Returns the maximum number of expected arguments.
* Returns -1 when no signatures where found on the function.
*/
exports.maxArgumentCount = function (fn) {
return Object.keys(fn.signatures || {})
.reduce(function (args, signature) {
var count = (signature.match(/,/g) || []).length + 1;
return Math.max(args, count);
}, -1);
};
...
min = function () { // check min has been calculated before if (this._min === null) { // minimum var m = null; // compute min this.forEach(function (v) { if (m === null || smaller(v, m)) m = v; }); this._min = m !== null ? m : undefined; } return this._min; }
...
* @private
*/
function _resize (array, size, dim, defaultValue) {
var i;
var elem;
var oldLen = array.length;
var newLen = size[dim];
var minLen = Math.min(oldLen, newLen);
// apply new length
array.length = newLen;
if (dim < size.length - 1) {
// non-last dimension
var dimNext = dim + 1;
...
reshape = function () { throw new Error('Cannot invoke reshape on an Immutable Matrix instance'); }
...
var matrix = load(require('../../type/matrix/function/matrix'));
/**
* Reshape a multi dimensional array to fit the specified dimensions
*
* Syntax:
*
* math.reshape(x, sizes)
*
* Examples:
*
* math.reshape([1, 2, 3, 4, 5, 6], [2, 3]);
* // returns Array [[1, 2, 3], [4, 5, 6]]
*
* math.reshape([[1, 2], [3, 4]], [1, 4]);
...
resize = function () { throw new Error('Cannot invoke resize on an Immutable Matrix instance'); }
...
// get matrix storage constructor
var F = type.Matrix.storage(format);
// create diagonal matrix (use optimized implementation for storage format)
return F.diagonal(size, one, 0, defaultValue);
}
// create and resize array
var res = array.resize([], size, defaultValue);
// fill in ones on the diagonal
var minimum = rows < cols ? rows : cols;
// fill diagonal
for (var d = 0; d < minimum; d++) {
res[d][d] = one;
}
return res;
...
set = function () { throw new Error('Cannot invoke set on an Immutable Matrix instance'); }
...
* keeps a scope containing variables in memory, which is used for all
* evaluations.
*
* Methods:
* var result = parser.eval(expr); // evaluate an expression
* var value = parser.get(name); // retrieve a variable from the parser
* var values = parser.getAll(); // retrieve all defined variables
* parser.set(name, value); // set a variable in the parser
* parser.remove(name); // clear a variable from the
* // parsers scope
* parser.clear(); // clear the parsers scope
*
* Example usage:
* var parser = new Parser();
* // Note: there is a convenience method which can be used instead:
...
subset = function (index) { switch (arguments.length) { case 1: // use base implementation var m = DenseMatrix.prototype.subset.call(this, index); // check result is a matrix if (m.isMatrix) { // return immutable matrix return new ImmutableDenseMatrix({ data: m._data, size: m._size, datatype: m._datatype }); } return m; // intentional fall through case 2: case 3: throw new Error('Cannot invoke set subset on an Immutable Matrix instance'); default: throw new SyntaxError('Wrong number of arguments'); } }
...
function factory (type, config, load, typed) {
var matrix = load(require('../../type/matrix/function/matrix'));
/**
* Get or set a subset of a matrix or string.
*
* Syntax:
* math.subset(value, index) // retrieve a subset
* math.subset(value, index, replacement [, defaultValue]) // replace a subset
*
* Examples:
*
* // get a subset
* var d = [[1, 2], [3, 4]];
* math.subset(d, math.index(1, 0)); // returns 3
...
swapRows = function () { throw new Error('Cannot invoke swapRows on an Immutable Matrix instance'); }
n/a
toJSON = function () { return { mathjs: 'ImmutableDenseMatrix', data: this._data, size: this._size, datatype: this._datatype }; }
n/a
function Index(ranges) { if (!(this instanceof Index)) { throw new SyntaxError('Constructor must be called with the new operator'); } this._dimensions = []; this._isScalar = true; for (var i = 0, ii = arguments.length; i < ii; i++) { var arg = arguments[i]; if (arg && (arg.isRange === true)) { this._dimensions.push(arg); this._isScalar = false; } else if (arg && (Array.isArray(arg) || arg.isMatrix === true)) { // create matrix var m = _createImmutableMatrix(arg.valueOf()); this._dimensions.push(m); // size var size = m.size(); // scalar if (size.length !== 1 || size[0] !== 1) { this._isScalar = false; } } else if (typeof arg === 'number') { this._dimensions.push(_createImmutableMatrix([arg])); } else if (typeof arg === 'string') { // object property (arguments.count should be 1) this._dimensions.push(arg); } // TODO: implement support for wildcard '*' else { throw new TypeError('Dimension must be an Array, Matrix, number, string, or Range'); } } }
...
else {
throw new TypeError('Dimension must be an Array, Matrix, number, string, or Range');
}
args[i] = arg;
}
var res = new type.Index();
type.Index.apply(res, args);
return res;
};
}
exports.name = 'index';
exports.path = 'expression.transform';
...
create = function (ranges) { var index = new Index(); Index.apply(index, ranges); return index; }
...
* false (default), output type can vary depending
* on input values. For example `math.sqrt(-4)`
* returns `complex('2i')` when predictable is false, and
* returns `NaN` when true.
*/
function create (config) {
// create a new math.js instance
var math = core.create(config);
math.create = create;
// import data types, functions, constants, expression parser, etc.
math['import'](require('./lib'));
return math;
}
...
fromJSON = function (json) { return Index.create(json.dimensions); }
...
* @param {string} key
* @param {*} value
* @returns {*} Returns the revived object
*/
return function reviver(key, value) {
var constructor = type[value && value.mathjs];
if (constructor && typeof constructor.fromJSON === 'function') {
return constructor.fromJSON(value);
}
return value;
}
}
exports.name = 'reviver';
...
clone = function () { var index = new Index(); index._dimensions = clone(this._dimensions); index._isScalar = this._isScalar; return index; }
...
return desc;
};
/**
* Export the help object to JSON
*/
Help.prototype.toJSON = function () {
var obj = object.clone(this.doc);
obj.mathjs = 'Help';
return obj;
};
/**
* Instantiate a Help object from a JSON object
* @param {Object} json
...
dimension = function (dim) { return this._dimensions[dim] || null; }
...
}
// validate whether the range is out of range
var strLen = str.length;
validateIndex(index.min()[0], strLen);
validateIndex(index.max()[0], strLen);
var range = index.dimension(0);
var substr = '';
range.forEach(function (v) {
substr += str.charAt(v);
});
return substr;
...
forEach = function (callback) { for (var i = 0, ii = this._dimensions.length; i < ii; i++) { callback(this._dimensions[i], i, this); } }
...
if (def.indexOf(keyword) == 0) {
matches.push(def);
}
}
}
// commandline keywords
['exit', 'quit', 'clear'].forEach(function (cmd) {
if (cmd.indexOf(keyword) == 0) {
matches.push(cmd);
}
});
// math functions and constants
var ignore = ['expr', 'type'];
...
getObjectProperty = function () { return this.isObjectProperty() ? this._dimensions[0] : null; }
...
this.index = index;
// readonly property name
Object.defineProperty(this, 'name', {
get: function () {
if (this.index) {
return (this.index.isObjectProperty())
? this.index.getObjectProperty()
: '';
}
else {
return this.object.name || '';
}
}.bind(this),
set: function () {
...
isObjectProperty = function () { return this._dimensions.length === 1 && typeof this._dimensions[0] === 'string'; }
...
this.object = object || null;
this.index = index;
// readonly property name
Object.defineProperty(this, 'name', {
get: function () {
if (this.index) {
return (this.index.isObjectProperty())
? this.index.getObjectProperty()
: '';
}
else {
return this.object.name || '';
}
}.bind(this),
...
isScalar = function () { return this._isScalar; }
...
* @private
*/
function _get (matrix, index) {
if (!index || index.isIndex !== true) {
throw new TypeError('Invalid index');
}
var isScalar = index.isScalar();
if (isScalar) {
// return a scalar
return matrix.get(index.min());
}
else {
// validate dimensions
var size = index.size();
...
max = function () { var values = []; for (var i = 0, ii = this._dimensions.length; i < ii; i++) { var range = this._dimensions[i]; values[i] = (typeof range === 'string') ? range : range.max(); } return values; }
...
* @return {number} Returns the maximum number of expected arguments.
* Returns -1 when no signatures where found on the function.
*/
exports.maxArgumentCount = function (fn) {
return Object.keys(fn.signatures || {})
.reduce(function (args, signature) {
var count = (signature.match(/,/g) || []).length + 1;
return Math.max(args, count);
}, -1);
};
...
min = function () { var values = []; for (var i = 0, ii = this._dimensions.length; i < ii; i++) { var range = this._dimensions[i]; values[i] = (typeof range === 'string') ? range : range.min(); } return values; }
...
* @private
*/
function _resize (array, size, dim, defaultValue) {
var i;
var elem;
var oldLen = array.length;
var newLen = size[dim];
var minLen = Math.min(oldLen, newLen);
// apply new length
array.length = newLen;
if (dim < size.length - 1) {
// non-last dimension
var dimNext = dim + 1;
...
size = function () { var size = []; for (var i = 0, ii = this._dimensions.length; i < ii; i++) { var d = this._dimensions[i]; size[i] = (typeof d === 'string') ? 1 : d.size()[0]; } return size; }
...
};
if (!Array.isArray(array) || !Array.isArray(sizes)) {
throw new TypeError('Array expected');
}
if (sizes.length === 0) {
throw new DimensionError(0, product(exports.size(array)), '!=');
}
try {
newArray = _reshape(flatArray, sizes);
} catch (e) {
if (e instanceof DimensionError) {
throw new DimensionError(
...
toArray = function () { var array = []; for (var i = 0, ii = this._dimensions.length; i < ii; i++) { var dimension = this._dimensions[i]; array.push((typeof dimension === 'string') ? dimension : dimension.toArray()); } return array; }
...
'... number | BigNumber': _hypot,
'Array': function (x) {
return hypot.apply(hypot, flatten(x));
},
'Matrix': function (x) {
return hypot.apply(hypot, flatten(x.toArray()));
}
});
/**
* Calculate the hypotenusa for an Array with values
* @param {Array.<number | BigNumber>} args
* @return {number | BigNumber} Returns the result
...
toJSON = function () { return { mathjs: 'Index', dimensions: this._dimensions }; }
n/a
toString = function () { var strings = []; for (var i = 0, ii = this._dimensions.length; i < ii; i++) { var dimension = this._dimensions[i]; if (typeof dimension === 'string') { strings.push(JSON.stringify(dimension)); } else { strings.push(dimension.toString()); } } return '[' + strings.join(', ') + ']'; }
...
}
else {
scope.ans = res;
console.log(format(res));
}
}
else if (res instanceof math.type.Help) {
console.log(res.toString());
}
else {
scope.ans = res;
console.log(format(res));
}
}
}
...
valueOf = function () { var array = []; for (var i = 0, ii = this._dimensions.length; i < ii; i++) { var dimension = this._dimensions[i]; array.push((typeof dimension === 'string') ? dimension : dimension.toArray()); } return array; }
...
throw new TypeError('Cannot implicitly convert a Fraction to BigNumber or vice versa. ' +
'Use function bignumber(x) to convert to BigNumber or fraction(x) to convert to Fraction.');
}
}, {
from: 'Fraction',
to: 'Complex',
convert: function (x) {
return new type.Complex(x.valueOf(), 0);
}
}, {
from: 'number',
to: 'Fraction',
convert: function (x) {
if (digits(x) > 15) {
throw new TypeError('Cannot implicitly convert a number with >15 significant digits to Fraction ' +
...
function Matrix() { if (!(this instanceof Matrix)) { throw new SyntaxError('Constructor must be called with the new operator'); } }
n/a
storage = function (format) { // check storage format is a string if (!isString(format)) { throw new TypeError('format must be a string value'); } // get storage format constructor var constructor = Matrix._storage[format]; if (!constructor) { throw new SyntaxError('Unsupported matrix storage format: ' + format); } // return storage constructor return constructor; }
...
// we extend the signatures of addScalar with signatures dealing with matrices
'Matrix, Matrix': function (x, y) {
// result
var c;
// process matrix storage
switch (x.storage()) {
case 'sparse':
switch (y.storage()) {
case 'sparse':
// sparse + sparse
c = algorithm04(x, y, addScalar);
break;
default:
...
clone = function () { // must be implemented by each of the Matrix implementations throw new Error('Cannot invoke clone on a Matrix interface'); }
...
return desc;
};
/**
* Export the help object to JSON
*/
Help.prototype.toJSON = function () {
var obj = object.clone(this.doc);
obj.mathjs = 'Help';
return obj;
};
/**
* Instantiate a Help object from a JSON object
* @param {Object} json
...
create = function (data, datatype) { throw new Error('Cannot invoke create on a Matrix interface'); }
...
* false (default), output type can vary depending
* on input values. For example `math.sqrt(-4)`
* returns `complex('2i')` when predictable is false, and
* returns `NaN` when true.
*/
function create (config) {
// create a new math.js instance
var math = core.create(config);
math.create = create;
// import data types, functions, constants, expression parser, etc.
math['import'](require('./lib'));
return math;
}
...
datatype = function () { // must be implemented by each of the Matrix implementations throw new Error('Cannot invoke datatype on a Matrix interface'); }
...
return 'dense';
};
/**
* Get the datatype of the data stored in the matrix.
*
* Usage:
* var format = matrix.datatype() // retrieve matrix datatype
*
* @memberof DenseMatrix
* @return {string} The datatype.
*/
DenseMatrix.prototype.datatype = function () {
return this._datatype;
};
...
forEach = function (callback) { // must be implemented by each of the Matrix implementations throw new Error('Cannot invoke forEach on a Matrix interface'); }
...
if (def.indexOf(keyword) == 0) {
matches.push(def);
}
}
}
// commandline keywords
['exit', 'quit', 'clear'].forEach(function (cmd) {
if (cmd.indexOf(keyword) == 0) {
matches.push(cmd);
}
});
// math functions and constants
var ignore = ['expr', 'type'];
...
format = function (options) { // must be implemented by each of the Matrix implementations throw new Error('Cannot invoke format on a Matrix interface'); }
...
* Helper function to format a value. Regular numbers will be rounded
* to 14 digits to prevent round-off errors from showing up.
* @param {*} value
*/
function format(value) {
var math = getMath();
return math.format(value, {
fn: function (value) {
if (typeof value === 'number') {
// round numbers
return math.format(value, PRECISION);
}
else {
return math.format(value);
...
get = function (index) { // must be implemented by each of the Matrix implementations throw new Error('Cannot invoke get on a Matrix interface'); }
...
* Parser contains methods to evaluate or parse expressions, and has a number
* of convenience methods to get, set, and remove variables from memory. Parser
* keeps a scope containing variables in memory, which is used for all
* evaluations.
*
* Methods:
* var result = parser.eval(expr); // evaluate an expression
* var value = parser.get(name); // retrieve a variable from the parser
* var values = parser.getAll(); // retrieve all defined variables
* parser.set(name, value); // set a variable in the parser
* parser.remove(name); // clear a variable from the
* // parsers scope
* parser.clear(); // clear the parsers scope
*
* Example usage:
...
map = function (callback, skipZeros) { // must be implemented by each of the Matrix implementations throw new Error('Cannot invoke map on a Matrix interface'); }
...
if (res && res.isResultSet) {
// we can have 0 or 1 results in the ResultSet, as the CLI
// does not allow multiple expressions separated by a return
res = res.entries[0];
node = node.blocks
.filter(function (entry) { return entry.visible; })
.map(function (entry) { return entry.node })[0];
}
if (node) {
if (node.isAssignmentNode) {
var name = findSymbolName(node);
if (name != null) {
scope.ans = scope[name];
...
reshape = function (size, defaultValue) { // must be implemented by each of the Matrix implementations throw new Error('Cannot invoke reshape on a Matrix interface'); }
...
var matrix = load(require('../../type/matrix/function/matrix'));
/**
* Reshape a multi dimensional array to fit the specified dimensions
*
* Syntax:
*
* math.reshape(x, sizes)
*
* Examples:
*
* math.reshape([1, 2, 3, 4, 5, 6], [2, 3]);
* // returns Array [[1, 2, 3], [4, 5, 6]]
*
* math.reshape([[1, 2], [3, 4]], [1, 4]);
...
resize = function (size, defaultValue) { // must be implemented by each of the Matrix implementations throw new Error('Cannot invoke resize on a Matrix interface'); }
...
// get matrix storage constructor
var F = type.Matrix.storage(format);
// create diagonal matrix (use optimized implementation for storage format)
return F.diagonal(size, one, 0, defaultValue);
}
// create and resize array
var res = array.resize([], size, defaultValue);
// fill in ones on the diagonal
var minimum = rows < cols ? rows : cols;
// fill diagonal
for (var d = 0; d < minimum; d++) {
res[d][d] = one;
}
return res;
...
set = function (index, value, defaultValue) { // must be implemented by each of the Matrix implementations throw new Error('Cannot invoke set on a Matrix interface'); }
...
* keeps a scope containing variables in memory, which is used for all
* evaluations.
*
* Methods:
* var result = parser.eval(expr); // evaluate an expression
* var value = parser.get(name); // retrieve a variable from the parser
* var values = parser.getAll(); // retrieve all defined variables
* parser.set(name, value); // set a variable in the parser
* parser.remove(name); // clear a variable from the
* // parsers scope
* parser.clear(); // clear the parsers scope
*
* Example usage:
* var parser = new Parser();
* // Note: there is a convenience method which can be used instead:
...
size = function () { // must be implemented by each of the Matrix implementations throw new Error('Cannot invoke size on a Matrix interface'); }
...
};
if (!Array.isArray(array) || !Array.isArray(sizes)) {
throw new TypeError('Array expected');
}
if (sizes.length === 0) {
throw new DimensionError(0, product(exports.size(array)), '!=');
}
try {
newArray = _reshape(flatArray, sizes);
} catch (e) {
if (e instanceof DimensionError) {
throw new DimensionError(
...
storage = function () { // must be implemented by each of the Matrix implementations throw new Error('Cannot invoke storage on a Matrix interface'); }
...
// we extend the signatures of addScalar with signatures dealing with matrices
'Matrix, Matrix': function (x, y) {
// result
var c;
// process matrix storage
switch (x.storage()) {
case 'sparse':
switch (y.storage()) {
case 'sparse':
// sparse + sparse
c = algorithm04(x, y, addScalar);
break;
default:
...
subset = function (index, replacement, defaultValue) { // must be implemented by each of the Matrix implementations throw new Error('Cannot invoke subset on a Matrix interface'); }
...
function factory (type, config, load, typed) {
var matrix = load(require('../../type/matrix/function/matrix'));
/**
* Get or set a subset of a matrix or string.
*
* Syntax:
* math.subset(value, index) // retrieve a subset
* math.subset(value, index, replacement [, defaultValue]) // replace a subset
*
* Examples:
*
* // get a subset
* var d = [[1, 2], [3, 4]];
* math.subset(d, math.index(1, 0)); // returns 3
...
toArray = function () { // must be implemented by each of the Matrix implementations throw new Error('Cannot invoke toArray on a Matrix interface'); }
...
'... number | BigNumber': _hypot,
'Array': function (x) {
return hypot.apply(hypot, flatten(x));
},
'Matrix': function (x) {
return hypot.apply(hypot, flatten(x.toArray()));
}
});
/**
* Calculate the hypotenusa for an Array with values
* @param {Array.<number | BigNumber>} args
* @return {number | BigNumber} Returns the result
...
toString = function () { // must be implemented by each of the Matrix implementations throw new Error('Cannot invoke toString on a Matrix interface'); }
...
}
else {
scope.ans = res;
console.log(format(res));
}
}
else if (res instanceof math.type.Help) {
console.log(res.toString());
}
else {
scope.ans = res;
console.log(format(res));
}
}
}
...
valueOf = function () { // must be implemented by each of the Matrix implementations throw new Error('Cannot invoke valueOf on a Matrix interface'); }
...
throw new TypeError('Cannot implicitly convert a Fraction to BigNumber or vice versa. ' +
'Use function bignumber(x) to convert to BigNumber or fraction(x) to convert to Fraction.');
}
}, {
from: 'Fraction',
to: 'Complex',
convert: function (x) {
return new type.Complex(x.valueOf(), 0);
}
}, {
from: 'number',
to: 'Fraction',
convert: function (x) {
if (digits(x) > 15) {
throw new TypeError('Cannot implicitly convert a number with >15 significant digits to Fraction ' +
...
function Range(start, end, step) { if (!(this instanceof Range)) { throw new SyntaxError('Constructor must be called with the new operator'); } if (start != null) { if (start.isBigNumber === true) start = start.toNumber(); else if (typeof start !== 'number') throw new TypeError('Parameter start must be a number'); } if (end != null) { if (end.isBigNumber === true) end = end.toNumber(); else if (typeof end !== 'number') throw new TypeError('Parameter end must be a number'); } if (step != null) { if (step.isBigNumber === true) step = step.toNumber(); else if (typeof step !== 'number') throw new TypeError('Parameter step must be a number'); } this.start = (start != null) ? parseFloat(start) : 0; this.end = (end != null) ? parseFloat(end) : 0; this.step = (step != null) ? parseFloat(step) : 1; }
n/a
fromJSON = function (json) { return new Range(json.start, json.end, json.step); }
...
* @param {string} key
* @param {*} value
* @returns {*} Returns the revived object
*/
return function reviver(key, value) {
var constructor = type[value && value.mathjs];
if (constructor && typeof constructor.fromJSON === 'function') {
return constructor.fromJSON(value);
}
return value;
}
}
exports.name = 'reviver';
...
parse = function (str) { if (typeof str !== 'string') { return null; } var args = str.split(':'); var nums = args.map(function (arg) { return parseFloat(arg); }); var invalid = nums.some(function (num) { return isNaN(num); }); if (invalid) { return null; } switch (nums.length) { case 2: return new Range(nums[0], nums[1]); case 3: return new Range(nums[0], nums[2], nums[1]); default: return null; } }
...
if (!expr) {
break;
}
switch (mode) {
case 'eval':
// evaluate expression
try {
var node = math.parse(expr);
var res = node.eval(scope);
if (res && res.isResultSet) {
// we can have 0 or 1 results in the ResultSet, as the CLI
// does not allow multiple expressions separated by a return
res = res.entries[0];
node = node.blocks
...
clone = function () { return new Range(this.start, this.end, this.step); }
...
return desc;
};
/**
* Export the help object to JSON
*/
Help.prototype.toJSON = function () {
var obj = object.clone(this.doc);
obj.mathjs = 'Help';
return obj;
};
/**
* Instantiate a Help object from a JSON object
* @param {Object} json
...
forEach = function (callback) { var x = this.start; var step = this.step; var end = this.end; var i = 0; if (step > 0) { while (x < end) { callback(x, [i], this); x += step; i++; } } else if (step < 0) { while (x > end) { callback(x, [i], this); x += step; i++; } } }
...
if (def.indexOf(keyword) == 0) {
matches.push(def);
}
}
}
// commandline keywords
['exit', 'quit', 'clear'].forEach(function (cmd) {
if (cmd.indexOf(keyword) == 0) {
matches.push(cmd);
}
});
// math functions and constants
var ignore = ['expr', 'type'];
...
format = function (options) { var str = number.format(this.start, options); if (this.step != 1) { str += ':' + number.format(this.step, options); } str += ':' + number.format(this.end, options); return str; }
...
* Helper function to format a value. Regular numbers will be rounded
* to 14 digits to prevent round-off errors from showing up.
* @param {*} value
*/
function format(value) {
var math = getMath();
return math.format(value, {
fn: function (value) {
if (typeof value === 'number') {
// round numbers
return math.format(value, PRECISION);
}
else {
return math.format(value);
...
map = function (callback) { var array = []; this.forEach(function (value, index, obj) { array[index[0]] = callback(value, index, obj); }); return array; }
...
if (res && res.isResultSet) {
// we can have 0 or 1 results in the ResultSet, as the CLI
// does not allow multiple expressions separated by a return
res = res.entries[0];
node = node.blocks
.filter(function (entry) { return entry.visible; })
.map(function (entry) { return entry.node })[0];
}
if (node) {
if (node.isAssignmentNode) {
var name = findSymbolName(node);
if (name != null) {
scope.ans = scope[name];
...
max = function () { var size = this.size()[0]; if (size > 0) { if (this.step > 0) { // positive step return this.start + (size - 1) * this.step; } else { // negative step return this.start; } } else { return undefined; } }
...
* @return {number} Returns the maximum number of expected arguments.
* Returns -1 when no signatures where found on the function.
*/
exports.maxArgumentCount = function (fn) {
return Object.keys(fn.signatures || {})
.reduce(function (args, signature) {
var count = (signature.match(/,/g) || []).length + 1;
return Math.max(args, count);
}, -1);
};
...
min = function () { var size = this.size()[0]; if (size > 0) { if (this.step > 0) { // positive step return this.start; } else { // negative step return this.start + (size - 1) * this.step; } } else { return undefined; } }
...
* @private
*/
function _resize (array, size, dim, defaultValue) {
var i;
var elem;
var oldLen = array.length;
var newLen = size[dim];
var minLen = Math.min(oldLen, newLen);
// apply new length
array.length = newLen;
if (dim < size.length - 1) {
// non-last dimension
var dimNext = dim + 1;
...
size = function () { var len = 0, start = this.start, step = this.step, end = this.end, diff = end - start; if (number.sign(step) == number.sign(diff)) { len = Math.ceil((diff) / step); } else if (diff == 0) { len = 0; } if (isNaN(len)) { len = 0; } return [len]; }
...
};
if (!Array.isArray(array) || !Array.isArray(sizes)) {
throw new TypeError('Array expected');
}
if (sizes.length === 0) {
throw new DimensionError(0, product(exports.size(array)), '!=');
}
try {
newArray = _reshape(flatArray, sizes);
} catch (e) {
if (e instanceof DimensionError) {
throw new DimensionError(
...
toArray = function () { var array = []; this.forEach(function (value, index) { array[index[0]] = value; }); return array; }
...
'... number | BigNumber': _hypot,
'Array': function (x) {
return hypot.apply(hypot, flatten(x));
},
'Matrix': function (x) {
return hypot.apply(hypot, flatten(x.toArray()));
}
});
/**
* Calculate the hypotenusa for an Array with values
* @param {Array.<number | BigNumber>} args
* @return {number | BigNumber} Returns the result
...
toJSON = function () { return { mathjs: 'Range', start: this.start, end: this.end, step: this.step }; }
n/a
toString = function () { return this.format(); }
...
}
else {
scope.ans = res;
console.log(format(res));
}
}
else if (res instanceof math.type.Help) {
console.log(res.toString());
}
else {
scope.ans = res;
console.log(format(res));
}
}
}
...
valueOf = function () { // TODO: implement a caching mechanism for range.valueOf() return this.toArray(); }
...
throw new TypeError('Cannot implicitly convert a Fraction to BigNumber or vice versa. ' +
'Use function bignumber(x) to convert to BigNumber or fraction(x) to convert to Fraction.');
}
}, {
from: 'Fraction',
to: 'Complex',
convert: function (x) {
return new type.Complex(x.valueOf(), 0);
}
}, {
from: 'number',
to: 'Fraction',
convert: function (x) {
if (digits(x) > 15) {
throw new TypeError('Cannot implicitly convert a number with >15 significant digits to Fraction ' +
...
function ResultSet(entries) { if (!(this instanceof ResultSet)) { throw new SyntaxError('Constructor must be called with the new operator'); } this.entries = entries || []; }
n/a
fromJSON = function (json) { return new ResultSet(json.entries); }
...
* @param {string} key
* @param {*} value
* @returns {*} Returns the revived object
*/
return function reviver(key, value) {
var constructor = type[value && value.mathjs];
if (constructor && typeof constructor.fromJSON === 'function') {
return constructor.fromJSON(value);
}
return value;
}
}
exports.name = 'reviver';
...
toJSON = function () { return { mathjs: 'ResultSet', entries: this.entries }; }
n/a
toString = function () { return '[' + this.entries.join(', ') + ']'; }
...
}
else {
scope.ans = res;
console.log(format(res));
}
}
else if (res instanceof math.type.Help) {
console.log(res.toString());
}
else {
scope.ans = res;
console.log(format(res));
}
}
}
...
valueOf = function () { return this.entries; }
...
throw new TypeError('Cannot implicitly convert a Fraction to BigNumber or vice versa. ' +
'Use function bignumber(x) to convert to BigNumber or fraction(x) to convert to Fraction.');
}
}, {
from: 'Fraction',
to: 'Complex',
convert: function (x) {
return new type.Complex(x.valueOf(), 0);
}
}, {
from: 'number',
to: 'Fraction',
convert: function (x) {
if (digits(x) > 15) {
throw new TypeError('Cannot implicitly convert a number with >15 significant digits to Fraction ' +
...
function Spa() { if (!(this instanceof Spa)) throw new SyntaxError('Constructor must be called with the new operator'); // allocate vector, TODO use typed arrays this._values = []; this._heap = new type.FibonacciHeap(); }
n/a
accumulate = function (i, v) { // node @ i var node = this._values[i]; if (!node) { // insert in heap node = this._heap.insert(i, v); // initialize value this._values[i] = node; } else { // accumulate value node.value = add(node.value, v); } }
n/a
forEach = function (from, to, callback) { // references var heap = this._heap; var values = this._values; // nodes var nodes = []; // node with minimum key, save it var node = heap.extractMinimum(); if (node) nodes.push(node); // extract nodes from heap (ordered) while (node && node.key <= to) { // check it is in range if (node.key >= from) { // check value is not zero if (!equalScalar(node.value, 0)) { // invoke callback callback(node.key, node.value, this); } } // extract next node, save it node = heap.extractMinimum(); if (node) nodes.push(node); } // reinsert all nodes in heap for (var i = 0; i < nodes.length; i++) { // current node var n = nodes[i]; // insert node in heap node = heap.insert(n.key, n.value); // update values values[node.key] = node; } }
...
if (def.indexOf(keyword) == 0) {
matches.push(def);
}
}
}
// commandline keywords
['exit', 'quit', 'clear'].forEach(function (cmd) {
if (cmd.indexOf(keyword) == 0) {
matches.push(cmd);
}
});
// math functions and constants
var ignore = ['expr', 'type'];
...
get = function (i) { var node = this._values[i]; if (node) return node.value; return 0; }
...
* Parser contains methods to evaluate or parse expressions, and has a number
* of convenience methods to get, set, and remove variables from memory. Parser
* keeps a scope containing variables in memory, which is used for all
* evaluations.
*
* Methods:
* var result = parser.eval(expr); // evaluate an expression
* var value = parser.get(name); // retrieve a variable from the parser
* var values = parser.getAll(); // retrieve all defined variables
* parser.set(name, value); // set a variable in the parser
* parser.remove(name); // clear a variable from the
* // parsers scope
* parser.clear(); // clear the parsers scope
*
* Example usage:
...
set = function (i, v) { // check we have a value @ i if (!this._values[i]) { // insert in heap var node = this._heap.insert(i, v); // set the value @ i this._values[i] = node; } else { // update the value @ i this._values[i].value = v; } }
...
* keeps a scope containing variables in memory, which is used for all
* evaluations.
*
* Methods:
* var result = parser.eval(expr); // evaluate an expression
* var value = parser.get(name); // retrieve a variable from the parser
* var values = parser.getAll(); // retrieve all defined variables
* parser.set(name, value); // set a variable in the parser
* parser.remove(name); // clear a variable from the
* // parsers scope
* parser.clear(); // clear the parsers scope
*
* Example usage:
* var parser = new Parser();
* // Note: there is a convenience method which can be used instead:
...
swap = function (i, j) { // node @ i and j var nodei = this._values[i]; var nodej = this._values[j]; // check we need to insert indeces if (!nodei && nodej) { // insert in heap nodei = this._heap.insert(i, nodej.value); // remove from heap this._heap.remove(nodej); // set values this._values[i] = nodei; this._values[j] = undefined; } else if (nodei && !nodej) { // insert in heap nodej = this._heap.insert(j, nodei.value); // remove from heap this._heap.remove(nodei); // set values this._values[j] = nodej; this._values[i] = undefined; } else if (nodei && nodej) { // swap values var v = nodei.value; nodei.value = nodej.value; nodej.value = v; } }
n/a
function SparseMatrix(data, datatype) { if (!(this instanceof SparseMatrix)) throw new SyntaxError('Constructor must be called with the new operator'); if (datatype && !isString(datatype)) throw new Error('Invalid datatype: ' + datatype); if (data && data.isMatrix === true) { // create from matrix _createFromMatrix(this, data, datatype); } else if (data && isArray(data.index) && isArray(data.ptr) && isArray(data.size)) { // initialize fields this._values = data.values; this._index = data.index; this._ptr = data.ptr; this._size = data.size; this._datatype = datatype || data.datatype; } else if (isArray(data)) { // create from array _createFromArray(this, data, datatype); } else if (data) { // unsupported type throw new TypeError('Unsupported type of data (' + util.types.type(data) + ')'); } else { // nothing provided this._values = []; this._index = []; this._ptr = [0]; this._size = [0, 0]; this._datatype = datatype; } }
n/a
_forEachRow = function (j, values, index, ptr, callback) { // indeces for column j var k0 = ptr[j]; var k1 = ptr[j + 1]; // loop for (var k = k0; k < k1; k++) { // invoke callback callback(index[k], values[k]); } }
n/a
_swapRows = function (x, y, columns, values, index, ptr) { // loop columns for (var j = 0; j < columns; j++) { // k0 <= k < k1 where k0 = _ptr[j] && k1 = _ptr[j+1] var k0 = ptr[j]; var k1 = ptr[j + 1]; // find value index @ x var kx = _getValueIndex(x, k0, k1, index); // find value index @ x var ky = _getValueIndex(y, k0, k1, index); // check both rows exist in matrix if (kx < k1 && ky < k1 && index[kx] === x && index[ky] === y) { // swap values (check for pattern matrix) if (values) { var v = values[kx]; values[kx] = values[ky]; values[ky] = v; } // next column continue; } // check x row exist & no y row if (kx < k1 && index[kx] === x && (ky >= k1 || index[ky] !== y)) { // value @ x (check for pattern matrix) var vx = values ? values[kx] : undefined; // insert value @ y index.splice(ky, 0, y); if (values) values.splice(ky, 0, vx); // remove value @ x (adjust array index if needed) index.splice(ky <= kx ? kx + 1 : kx, 1); if (values) values.splice(ky <= kx ? kx + 1 : kx, 1); // next column continue; } // check y row exist & no x row if (ky < k1 && index[ky] === y && (kx >= k1 || index[kx] !== x)) { // value @ y (check for pattern matrix) var vy = values ? values[ky] : undefined; // insert value @ x index.splice(kx, 0, x); if (values) values.splice(kx, 0, vy); // remove value @ y (adjust array index if needed) index.splice(kx <= ky ? ky + 1 : ky, 1); if (values) values.splice(kx <= ky ? ky + 1 : ky, 1); } } }
...
throw new Error('Only two dimensional matrix is supported');
}
// validate index
validateIndex(i, this._size[0]);
validateIndex(j, this._size[0]);
// swap rows
DenseMatrix._swapRows(i, j, this._data);
// return current instance
return this;
};
/**
* Swap rows i and j in Dense Matrix data structure.
*
...
diagonal = function (size, value, k, defaultValue, datatype) { if (!isArray(size)) throw new TypeError('Array expected, size parameter'); if (size.length !== 2) throw new Error('Only two dimensions matrix are supported'); // map size & validate size = size.map(function (s) { // check it is a big number if (s && s.isBigNumber === true) { // convert it s = s.toNumber(); } // validate arguments if (!isNumber(s) || !isInteger(s) || s < 1) { throw new Error('Size values must be positive integers'); } return s; }); // validate k if any if (k) { // convert BigNumber to a number if (k.isBigNumber === true) k = k.toNumber(); // is must be an integer if (!isNumber(k) || !isInteger(k)) { throw new TypeError ('The parameter k must be an integer number'); } } else { // default value k = 0; } // equal signature to use var eq = equalScalar; // zero value var zero = 0; if (isString(datatype)) { // find signature that matches (datatype, datatype) eq = typed.find(equalScalar, [datatype, datatype]) || equalScalar; // convert 0 to the same datatype zero = typed.convert(0, datatype); } var kSuper = k > 0 ? k : 0; var kSub = k < 0 ? -k : 0; // rows and columns var rows = size[0]; var columns = size[1]; // number of non-zero items var n = Math.min(rows - kSub, columns - kSuper); // value extraction function var _value; // check value if (isArray(value)) { // validate array if (value.length !== n) { // number of values in array must be n throw new Error('Invalid value array length'); } // define function _value = function (i) { // return value @ i return value[i]; }; } else if (value && value.isMatrix === true) { // matrix size var ms = value.size(); // validate matrix if (ms.length !== 1 || ms[0] !== n) { // number of values in array must be n throw new Error('Invalid matrix length'); } // define function _value = function (i) { // return value @ i return value.get([i]); }; } else { // define function _value = function () { // return value return value; }; } // create arrays var values = []; var index = []; var ptr = []; // loop items for (var j = 0; j < columns; j++) { // number of rows with value ptr.push(values.length); // diagonal index var i = j - kSuper; // check we need to set diagonal value if (i >= 0 && i < n) { // get value @ i var v = _value(i); // check for zero if (!eq(v, zero)) { // column index.push(i + kSub); // add value values.push(v); } } } // last value should be number of values ptr.push(values.length); // create SparseMatrix return new SparseMatrix({ values: values, index: index, ptr: ptr, size: [rows, columns] }); }
...
function _createDiagonalMatrix(x, k, format, l, kSub, kSuper) {
// matrix size
var ms = [l + kSub, l + kSuper];
// get matrix constructor
var F = type.Matrix.storage(format || 'dense');
// create diagonal matrix
var m = F.diagonal(ms, x, k);
// check we need to return a matrix
return format !== null ? m : m.valueOf();
}
function _getDiagonal(x, k, format, s, kSub, kSuper) {
// check x is a Matrix
if (x && x.isMatrix === true) {
...
fromJSON = function (json) { return new SparseMatrix(json); }
...
* @param {string} key
* @param {*} value
* @returns {*} Returns the revived object
*/
return function reviver(key, value) {
var constructor = type[value && value.mathjs];
if (constructor && typeof constructor.fromJSON === 'function') {
return constructor.fromJSON(value);
}
return value;
}
}
exports.name = 'reviver';
...
clone = function () { var m = new SparseMatrix({ values: this._values ? object.clone(this._values) : undefined, index: object.clone(this._index), ptr: object.clone(this._ptr), size: object.clone(this._size), datatype: this._datatype }); return m; }
...
return desc;
};
/**
* Export the help object to JSON
*/
Help.prototype.toJSON = function () {
var obj = object.clone(this.doc);
obj.mathjs = 'Help';
return obj;
};
/**
* Instantiate a Help object from a JSON object
* @param {Object} json
...
create = function (data, datatype) { return new SparseMatrix(data, datatype); }
...
* false (default), output type can vary depending
* on input values. For example `math.sqrt(-4)`
* returns `complex('2i')` when predictable is false, and
* returns `NaN` when true.
*/
function create (config) {
// create a new math.js instance
var math = core.create(config);
math.create = create;
// import data types, functions, constants, expression parser, etc.
math['import'](require('./lib'));
return math;
}
...
datatype = function () { return this._datatype; }
...
return 'dense';
};
/**
* Get the datatype of the data stored in the matrix.
*
* Usage:
* var format = matrix.datatype() // retrieve matrix datatype
*
* @memberof DenseMatrix
* @return {string} The datatype.
*/
DenseMatrix.prototype.datatype = function () {
return this._datatype;
};
...
density = function () { // rows & columns var rows = this._size[0]; var columns = this._size[1]; // calculate density return rows !== 0 && columns !== 0 ? (this._index.length / (rows * columns)) : 0; }
...
// process matrix storage
switch (x.storage()) {
case 'sparse':
switch (y.storage()) {
case 'sparse':
// density must be one (no zeros in matrix)
if (y.density() === 1) {
// sparse + sparse
c = algorithm06(x, y, nthRoot);
}
else {
// throw exception
throw new Error('Root must be non-zero');
}
...
diagonal = function (k) { // validate k if any if (k) { // convert BigNumber to a number if (k.isBigNumber === true) k = k.toNumber(); // is must be an integer if (!isNumber(k) || !isInteger(k)) { throw new TypeError ('The parameter k must be an integer number'); } } else { // default value k = 0; } var kSuper = k > 0 ? k : 0; var kSub = k < 0 ? -k : 0; // rows & columns var rows = this._size[0]; var columns = this._size[1]; // number diagonal values var n = Math.min(rows - kSub, columns - kSuper); // diagonal arrays var values = []; var index = []; var ptr = []; // initial ptr value ptr[0] = 0; // loop columns for (var j = kSuper; j < columns && values.length < n; j++) { // k0 <= k < k1 where k0 = _ptr[j] && k1 = _ptr[j+1] var k0 = this._ptr[j]; var k1 = this._ptr[j + 1]; // loop x within [k0, k1[ for (var x = k0; x < k1; x++) { // row index var i = this._index[x]; // check row if (i === j - kSuper + kSub) { // value on this column values.push(this._values[x]); // store row index[values.length - 1] = i - kSub; // exit loop break; } } } // close ptr ptr.push(values.length); // return matrix return new SparseMatrix({ values: values, index: index, ptr: ptr, size: [n, 1] }); }
...
function _createDiagonalMatrix(x, k, format, l, kSub, kSuper) {
// matrix size
var ms = [l + kSub, l + kSuper];
// get matrix constructor
var F = type.Matrix.storage(format || 'dense');
// create diagonal matrix
var m = F.diagonal(ms, x, k);
// check we need to return a matrix
return format !== null ? m : m.valueOf();
}
function _getDiagonal(x, k, format, s, kSub, kSuper) {
// check x is a Matrix
if (x && x.isMatrix === true) {
...
forEach = function (callback, skipZeros) { // check it is a pattern matrix if (!this._values) throw new Error('Cannot invoke forEach on a Pattern only matrix'); // matrix instance var me = this; // rows and columns var rows = this._size[0]; var columns = this._size[1]; // loop columns for (var j = 0; j < columns; j++) { // k0 <= k < k1 where k0 = _ptr[j] && k1 = _ptr[j+1] var k0 = this._ptr[j]; var k1 = this._ptr[j + 1]; // column pointer var p = 0; // loop k within [k0, k1[ for (var k = k0; k < k1; k++) { // row index var i = this._index[k]; // check we need to process zeros if (!skipZeros) { // zero values for (var x = p; x < i; x++) callback(0, [x, j], me); } // value @ k callback(this._values[k], [i, j], me); // update pointer p = i + 1; } // check we need to process zeros if (!skipZeros) { // zero values for (var y = p; y < rows; y++) callback(0, [y, j], me); } } }
...
if (def.indexOf(keyword) == 0) {
matches.push(def);
}
}
}
// commandline keywords
['exit', 'quit', 'clear'].forEach(function (cmd) {
if (cmd.indexOf(keyword) == 0) {
matches.push(cmd);
}
});
// math functions and constants
var ignore = ['expr', 'type'];
...
format = function (options) { // rows and columns var rows = this._size[0]; var columns = this._size[1]; // density var density = this.density(); // rows & columns var str = 'Sparse Matrix [' + string.format(rows, options) + ' x ' + string.format(columns, options) + '] density: ' + string. format(density, options) + '\n'; // loop columns for (var j = 0; j < columns; j++) { // k0 <= k < k1 where k0 = _ptr[j] && k1 = _ptr[j+1] var k0 = this._ptr[j]; var k1 = this._ptr[j + 1]; // loop k within [k0, k1[ for (var k = k0; k < k1; k++) { // row index var i = this._index[k]; // append value str += '\n (' + string.format(i, options) + ', ' + string.format(j, options) + ') ==> ' + (this._values ? string.format (this._values[k], options) : 'X'); } } return str; }
...
* Helper function to format a value. Regular numbers will be rounded
* to 14 digits to prevent round-off errors from showing up.
* @param {*} value
*/
function format(value) {
var math = getMath();
return math.format(value, {
fn: function (value) {
if (typeof value === 'number') {
// round numbers
return math.format(value, PRECISION);
}
else {
return math.format(value);
...
get = function (index) { if (!isArray(index)) throw new TypeError('Array expected'); if (index.length != this._size.length) throw new DimensionError(index.length, this._size.length); // check it is a pattern matrix if (!this._values) throw new Error('Cannot invoke get on a Pattern only matrix'); // row and column var i = index[0]; var j = index[1]; // check i, j are valid validateIndex(i, this._size[0]); validateIndex(j, this._size[1]); // find value index var k = _getValueIndex(i, this._ptr[j], this._ptr[j + 1], this._index); // check k is prior to next column k and it is in the correct row if (k < this._ptr[j + 1] && this._index[k] === i) return this._values[k]; return 0; }
...
* Parser contains methods to evaluate or parse expressions, and has a number
* of convenience methods to get, set, and remove variables from memory. Parser
* keeps a scope containing variables in memory, which is used for all
* evaluations.
*
* Methods:
* var result = parser.eval(expr); // evaluate an expression
* var value = parser.get(name); // retrieve a variable from the parser
* var values = parser.getAll(); // retrieve all defined variables
* parser.set(name, value); // set a variable in the parser
* parser.remove(name); // clear a variable from the
* // parsers scope
* parser.clear(); // clear the parsers scope
*
* Example usage:
...
map = function (callback, skipZeros) { // check it is a pattern matrix if (!this._values) throw new Error('Cannot invoke map on a Pattern only matrix'); // matrix instance var me = this; // rows and columns var rows = this._size[0]; var columns = this._size[1]; // invoke callback var invoke = function (v, i, j) { // invoke callback return callback(v, [i, j], me); }; // invoke _map return _map(this, 0, rows - 1, 0, columns - 1, invoke, skipZeros); }
...
if (res && res.isResultSet) {
// we can have 0 or 1 results in the ResultSet, as the CLI
// does not allow multiple expressions separated by a return
res = res.entries[0];
node = node.blocks
.filter(function (entry) { return entry.visible; })
.map(function (entry) { return entry.node })[0];
}
if (node) {
if (node.isAssignmentNode) {
var name = findSymbolName(node);
if (name != null) {
scope.ans = scope[name];
...
reshape = function (size, copy) { // validate arguments if (!isArray(size)) throw new TypeError('Array expected'); if (size.length !== 2) throw new Error('Sparse matrices can only be reshaped in two dimensions'); // check sizes size.forEach(function (value) { if (!number.isNumber(value) || !number.isInteger(value) || value < 0) { throw new TypeError('Invalid size, must contain positive integers ' + '(size: ' + string.format(size) + ')'); } }); // m * n must not change if(this._size[0] * this._size[1] !== size[0] * size[1]) { throw new Error('Reshaping sparse matrix will result in the wrong number of elements'); } // matrix to reshape var m = copy ? this.clone() : this; // return unchanged if the same shape if(this._size[0] === size[0] && this._size[1] === size[1]) { return m; } // Convert to COO format (generate a column index) var colIndex = []; for(var i=0; i<m._ptr.length; i++) { for(var j=0; j<m._ptr[i+1]-m._ptr[i]; j++) { colIndex.push(i); } } // Clone the values array var values = m._values.slice(); // Clone the row index array var rowIndex = m._index.slice(); // Transform the (row, column) indices for(var i=0; i<m._index.length; i++) { var r1 = rowIndex[i]; var c1 = colIndex[i]; var flat = r1 * m._size[1] + c1; colIndex[i] = flat % size[1]; rowIndex[i] = Math.floor(flat / size[1]); } // Now reshaping is supposed to preserve the row-major order, BUT these sparse matrices are stored // in column-major order, so we have to reorder the value array now. One option is to use a multisort, // sorting several arrays based on some other array. // OR, we could easily just: // 1. Remove all values from the matrix m._values.length = 0; m._index.length = 0; m._ptr.length = size[1] + 1; m._size = size.slice(); for(var i=0; i<m._ptr.length; i++) { m._ptr[i] = 0; } // 2. Re-insert all elements in the proper order (simplified code from SparseMatrix.prototype.set) // This step is probably the most time-consuming for(var h=0; h<values.length; h++) { var i = rowIndex[h]; var j = colIndex[h]; var v = values[h]; var k = _getValueIndex(i, m._ptr[j], m._ptr[j + 1], m._index); _insert(k, i, j, v, m._values, m._index, m._ptr); } // The value indices are inserted out of order, but apparently that's... still OK? return m; }
...
var matrix = load(require('../../type/matrix/function/matrix'));
/**
* Reshape a multi dimensional array to fit the specified dimensions
*
* Syntax:
*
* math.reshape(x, sizes)
*
* Examples:
*
* math.reshape([1, 2, 3, 4, 5, 6], [2, 3]);
* // returns Array [[1, 2, 3], [4, 5, 6]]
*
* math.reshape([[1, 2], [3, 4]], [1, 4]);
...
resize = function (size, defaultValue, copy) { // validate arguments if (!isArray(size)) throw new TypeError('Array expected'); if (size.length !== 2) throw new Error('Only two dimensions matrix are supported'); // check sizes size.forEach(function (value) { if (!number.isNumber(value) || !number.isInteger(value) || value < 0) { throw new TypeError('Invalid size, must contain positive integers ' + '(size: ' + string.format(size) + ')'); } }); // matrix to resize var m = copy ? this.clone() : this; // resize matrix return _resize(m, size[0], size[1], defaultValue); }
...
// get matrix storage constructor
var F = type.Matrix.storage(format);
// create diagonal matrix (use optimized implementation for storage format)
return F.diagonal(size, one, 0, defaultValue);
}
// create and resize array
var res = array.resize([], size, defaultValue);
// fill in ones on the diagonal
var minimum = rows < cols ? rows : cols;
// fill diagonal
for (var d = 0; d < minimum; d++) {
res[d][d] = one;
}
return res;
...
set = function (index, v, defaultValue) { if (!isArray(index)) throw new TypeError('Array expected'); if (index.length != this._size.length) throw new DimensionError(index.length, this._size.length); // check it is a pattern matrix if (!this._values) throw new Error('Cannot invoke set on a Pattern only matrix'); // row and column var i = index[0]; var j = index[1]; // rows & columns var rows = this._size[0]; var columns = this._size[1]; // equal signature to use var eq = equalScalar; // zero value var zero = 0; if (isString(this._datatype)) { // find signature that matches (datatype, datatype) eq = typed.find(equalScalar, [this._datatype, this._datatype]) || equalScalar; // convert 0 to the same datatype zero = typed.convert(0, this._datatype); } // check we need to resize matrix if (i > rows - 1 || j > columns - 1) { // resize matrix _resize(this, Math.max(i + 1, rows), Math.max(j + 1, columns), defaultValue); // update rows & columns rows = this._size[0]; columns = this._size[1]; } // check i, j are valid validateIndex(i, rows); validateIndex(j, columns); // find value index var k = _getValueIndex(i, this._ptr[j], this._ptr[j + 1], this._index); // check k is prior to next column k and it is in the correct row if (k < this._ptr[j + 1] && this._index[k] === i) { // check value != 0 if (!eq(v, zero)) { // update value this._values[k] = v; } else { // remove value from matrix _remove(k, j, this._values, this._index, this._ptr); } } else { // insert value @ (i, j) _insert(k, i, j, v, this._values, this._index, this._ptr); } return this; }
...
* keeps a scope containing variables in memory, which is used for all
* evaluations.
*
* Methods:
* var result = parser.eval(expr); // evaluate an expression
* var value = parser.get(name); // retrieve a variable from the parser
* var values = parser.getAll(); // retrieve all defined variables
* parser.set(name, value); // set a variable in the parser
* parser.remove(name); // clear a variable from the
* // parsers scope
* parser.clear(); // clear the parsers scope
*
* Example usage:
* var parser = new Parser();
* // Note: there is a convenience method which can be used instead:
...
size = function () { return this._size.slice(0); // copy the Array }
...
};
if (!Array.isArray(array) || !Array.isArray(sizes)) {
throw new TypeError('Array expected');
}
if (sizes.length === 0) {
throw new DimensionError(0, product(exports.size(array)), '!=');
}
try {
newArray = _reshape(flatArray, sizes);
} catch (e) {
if (e instanceof DimensionError) {
throw new DimensionError(
...
storage = function () { return 'sparse'; }
...
// we extend the signatures of addScalar with signatures dealing with matrices
'Matrix, Matrix': function (x, y) {
// result
var c;
// process matrix storage
switch (x.storage()) {
case 'sparse':
switch (y.storage()) {
case 'sparse':
// sparse + sparse
c = algorithm04(x, y, addScalar);
break;
default:
...
subset = function (index, replacement, defaultValue) { // check it is a pattern matrix if (!this._values) throw new Error('Cannot invoke subset on a Pattern only matrix'); // check arguments switch (arguments.length) { case 1: return _getsubset(this, index); // intentional fall through case 2: case 3: return _setsubset(this, index, replacement, defaultValue); default: throw new SyntaxError('Wrong number of arguments'); } }
...
function factory (type, config, load, typed) {
var matrix = load(require('../../type/matrix/function/matrix'));
/**
* Get or set a subset of a matrix or string.
*
* Syntax:
* math.subset(value, index) // retrieve a subset
* math.subset(value, index, replacement [, defaultValue]) // replace a subset
*
* Examples:
*
* // get a subset
* var d = [[1, 2], [3, 4]];
* math.subset(d, math.index(1, 0)); // returns 3
...
swapRows = function (i, j) { // check index if (!isNumber(i) || !isInteger(i) || !isNumber(j) || !isInteger(j)) { throw new Error('Row index must be positive integers'); } // check dimensions if (this._size.length !== 2) { throw new Error('Only two dimensional matrix is supported'); } // validate index validateIndex(i, this._size[0]); validateIndex(j, this._size[0]); // swap rows SparseMatrix._swapRows(i, j, this._size[1], this._values, this._index, this._ptr); // return current instance return this; }
n/a
toArray = function () { return _toArray(this._values, this._index, this._ptr, this._size, true); }
...
'... number | BigNumber': _hypot,
'Array': function (x) {
return hypot.apply(hypot, flatten(x));
},
'Matrix': function (x) {
return hypot.apply(hypot, flatten(x.toArray()));
}
});
/**
* Calculate the hypotenusa for an Array with values
* @param {Array.<number | BigNumber>} args
* @return {number | BigNumber} Returns the result
...
toJSON = function () { return { mathjs: 'SparseMatrix', values: this._values, index: this._index, ptr: this._ptr, size: this._size, datatype: this._datatype }; }
n/a
toString = function () { return string.format(this.toArray()); }
...
}
else {
scope.ans = res;
console.log(format(res));
}
}
else if (res instanceof math.type.Help) {
console.log(res.toString());
}
else {
scope.ans = res;
console.log(format(res));
}
}
}
...
valueOf = function () { return _toArray(this._values, this._index, this._ptr, this._size, false); }
...
throw new TypeError('Cannot implicitly convert a Fraction to BigNumber or vice versa. ' +
'Use function bignumber(x) to convert to BigNumber or fraction(x) to convert to Fraction.');
}
}, {
from: 'Fraction',
to: 'Complex',
convert: function (x) {
return new type.Complex(x.valueOf(), 0);
}
}, {
from: 'number',
to: 'Fraction',
convert: function (x) {
if (digits(x) > 15) {
throw new TypeError('Cannot implicitly convert a number with >15 significant digits to Fraction ' +
...
function Unit(value, name) { if (!(this instanceof Unit)) { throw new Error('Constructor must be called with the new operator'); } if (!(value === undefined || isNumeric(value) || value.isComplex)) { throw new TypeError('First parameter in Unit constructor must be number, BigNumber, Fraction, Complex, or undefined'); } if (name != undefined && (typeof name !== 'string' || name == '')) { throw new TypeError('Second parameter in Unit constructor must be a string'); } if (name != undefined) { var u = Unit.parse(name); this.units = u.units; this.dimensions = u.dimensions; } else { this.units = [ { unit: UNIT_NONE, prefix: PREFIXES.NONE, // link to a list with supported prefixes power: 0 } ]; this.dimensions = []; for(var i=0; i<BASE_DIMENSIONS.length; i++) { this.dimensions[i] = 0; } } this.value = (value != undefined) ? this._normalize(value) : null; this.fixPrefix = false; // if true, function format will not search for the // best prefix but leave it as initially provided. // fixPrefix is set true by the method Unit.to // The justification behind this is that if the constructor is explicitly called, // the caller wishes the units to be returned exactly as he supplied. this.isUnitListSimplified = true; }
n/a
_getNumberConverter = function (type) { if (!Unit.typeConverters[type]) { throw new TypeError('Unsupported type "' + type + '"'); } return Unit.typeConverters[type]; }
...
if (value == null || this.units.length === 0) {
return value;
}
else if (this._isDerived()) {
// This is a derived unit, so do not apply offsets.
// For example, with J kg^-1 degC^-1 you would NOT want to apply the offset.
var res = value;
convert = Unit._getNumberConverter(getTypeOf(value)); // convert to Fraction or BigNumber
if needed
for(var i=0; i < this.units.length; i++) {
unitValue = convert(this.units[i].unit.value);
unitPrefixValue = convert(this.units[i].prefix.value);
unitPower = convert(this.units[i].power);
res = multiply(res, pow(multiply(unitValue, unitPrefixValue), unitPower));
}
...
createUnit = function (obj, options) { if(typeof(obj) !== 'object') { throw new TypeError("createUnit expects first parameter to be of type 'Object'"); } // Remove all units and aliases we are overriding if(options && options.override) { for(var key in obj) { if(obj.hasOwnProperty(key)) { Unit.deleteUnit(key); } if(obj[key].aliases) { for(var i=0; i<obj[key].aliases.length; i++) { Unit.deleteUnit(obj[key].aliases[i]); } } } } // TODO: traverse multiple times until all units have been added var lastUnit; for(var key in obj) { if(obj.hasOwnProperty(key)) { lastUnit = Unit.createUnitSingle(key, obj[key]); } } return lastUnit; }
n/a
createUnitSingle = function (name, obj, options) { if(typeof(obj) === 'undefined' || obj === null) { obj = {}; } if(typeof(name) !== 'string') { throw new TypeError("createUnitSingle expects first parameter to be of type 'string'"); } // Check collisions with existing units if(UNITS.hasOwnProperty(name)) { throw new Error('Cannot create unit "' + name + '": a unit with that name already exists'); } // TODO: Validate name for collisions with other built-in functions (like abs or cos, for example), and for acceptable variable names. For example, '42' is probably not a valid unit. Nor is '%', since it is also an operator. assertUnitNameIsValid(name); var defUnit = null; // The Unit from which the new unit will be created. var aliases = []; var offset = 0; var definition; var prefixes; if(obj && obj.type === 'Unit') { defUnit = obj.clone(); } else if(typeof(obj) === 'string') { if(obj !== '') { definition = obj; } } else if(typeof(obj) === 'object') { definition = obj.definition; prefixes = obj.prefixes; offset = obj.offset; aliases = obj.aliases; } else { throw new TypeError('Cannot create unit "' + name + '" from "' + obj.toString() + '": expecting "string" or "Unit" or "Object "'); } if(aliases) { for (var i=0; i<aliases.length; i++) { if(UNITS.hasOwnProperty(aliases[i])) { throw new Error('Cannot create alias "' + aliases[i] + '": a unit with that name already exists'); } } } if(definition && typeof(definition) === 'string' && !defUnit) { try { defUnit = Unit.parse(definition, {allowNoUnits: true}); } catch (ex) { ex.message = 'Could not create unit "' + name + '" from "' + definition + '": ' + ex.message; throw(ex); } } else if(definition && definition.type === 'Unit') { defUnit = definition.clone(); } aliases = aliases || []; offset = offset || 0; if(prefixes && prefixes.toUpperCase) prefixes = PREFIXES[prefixes.toUpperCase()] || PREFIXES.NONE; else prefixes = PREFIXES.NONE; // If defUnit is null, it is because the user did not // specify a defintion. So create a new base dimension. var newUnit = {}; if(!defUnit) { // Add a new base dimension var baseName = name + "_STUFF"; // foo --> foo_STUFF, or the essence of foo if(BASE_DIMENSIONS.indexOf(baseName) >= 0) { throw new Error('Cannot create new base unit "' + name + '": a base unit with that name already exists (and cannot be overridden )'); } BASE_DIMENSIONS.push(baseName); // Push 0 onto existing base units for(var b in BASE_UNITS) { if(BASE_UNITS.hasOwnProperty(b)) { BASE_UNITS[b].dimensions[BASE_DIMENSIONS.length-1] = 0; } } // Add the new base unit var newBaseUnit = { dimensions: [] }; for(var i=0; i<BASE_DIMENSIONS.length; i++) { newBaseUnit.dimensions[i] = 0; } newBaseUnit.dimensions[BASE_DIMENSIONS.length-1] = 1; newBaseUnit.key = baseName; BASE_UNITS[baseName] = newBaseUnit; newUnit = { name: name, value: 1, dimensions: BASE_UNITS[baseName].dimensions.slice(0), prefixes: prefixes, offset: offset, base: baseName }; currentUnitSystem[baseName] = { unit: newUnit, prefix: PREFIXES.NONE[''] }; } else { newUnit = { name: name, value: defUnit.value, dimensions: defUnit.dimensions.slice(0), prefixes: prefixes, offset: offset, }; // Create a new base if no matching base exists var anyMatch = false; for(var i in BASE_UNITS) { if(BASE_UNITS.hasOwnProperty(i)) { var match = true; for(var j=0; j<BASE_DIMENSIONS.length; j++) { if (Math.abs((newUnit.dimensions[j] || 0) - (BASE_UNITS[i].dimensions[j] || 0)) > 1e-12) { match = false; break; } } if(match) { anyMatch = true; break; } } } if(!anyMatch) { var baseName = name + "_STUFF"; ...
...
}
}
// TODO: traverse multiple times until all units have been added
var lastUnit;
for(var key in obj) {
if(obj.hasOwnProperty(key)) {
lastUnit = Unit.createUnitSingle(key, obj[key]);
}
}
return lastUnit;
};
/**
* Create a user-defined unit and register it with the Unit type.
...
deleteUnit = function (name) { delete Unit.UNITS[name]; }
...
throw new TypeError("createUnit expects first parameter to be of type 'Object'");
}
// Remove all units and aliases we are overriding
if(options && options.override) {
for(var key in obj) {
if(obj.hasOwnProperty(key)) {
Unit.deleteUnit(key);
}
if(obj[key].aliases) {
for(var i=0; i<obj[key].aliases.length; i++) {
Unit.deleteUnit(obj[key].aliases[i]);
}
}
}
...
fromJSON = function (json) { var unit = new Unit(json.value, json.unit); unit.fixPrefix = json.fixPrefix || false; return unit; }
...
* @param {string} key
* @param {*} value
* @returns {*} Returns the revived object
*/
return function reviver(key, value) {
var constructor = type[value && value.mathjs];
if (constructor && typeof constructor.fromJSON === 'function') {
return constructor.fromJSON(value);
}
return value;
}
}
exports.name = 'reviver';
...
getUnitSystem = function () { for(var key in UNIT_SYSTEMS) { if(UNIT_SYSTEMS[key] === currentUnitSystem) { return key; } } }
n/a
isValuelessUnit = function (name) { return (_findUnit(name) != null); }
...
matches.push(prefix);
}
else if (keyword.indexOf(prefix) == 0) {
var unitKeyword = keyword.substring(prefix.length);
for (var n in Unit.UNITS) {
if (Unit.UNITS.hasOwnProperty(n)) {
if (n.indexOf(unitKeyword) == 0 &&
Unit.isValuelessUnit(prefix + n)) {
matches.push(prefix + n);
}
}
}
}
}
}
...
parse = function (str, options) { options = options || {}; text = str; index = -1; c = ''; if (typeof text !== 'string') { throw new TypeError('Invalid argument in Unit.parse, string expected'); } var unit = new Unit(); unit.units = []; // A unit should follow this pattern: // [number]unit[^number] [unit[^number]]...[/unit[^number] [unit[^number]]] // Rules: // number is any floating point number. // unit is any alphanumeric string beginning with an alpha. Units with names like e3 should be avoided because they look like the exponent of a floating point number! // The string may optionally begin with a number. // Each unit may optionally be followed by ^number. // Whitespace or a forward slash is recommended between consecutive units, although the following technically is parseable: // 2m^2kg/s^2 // it is not good form. If a unit starts with e, then it could be confused as a floating point number: // 4erg next(); skipWhitespace(); // Optional number at the start of the string var valueStr = parseNumber(); var value = null; if(valueStr) { if (config.number === 'BigNumber') { value = new type.BigNumber(valueStr); } else if (config.number === 'Fraction') { value = new type.Fraction(valueStr); } else { // number value = parseFloat(valueStr); } } skipWhitespace(); // Whitespace is not required here // Next, we read any number of unit[^number] var powerMultiplierCurrent = 1; var expectingUnit = false; // Stack to keep track of powerMultipliers applied to each parentheses group var powerMultiplierStack = []; // Running product of all elements in powerMultiplierStack var powerMultiplierStackProduct = 1; while (true) { skipWhitespace(); // Check for and consume opening parentheses, pushing powerMultiplierCurrent to the stack // A '(' will always appear directly before a unit. while (c === '(') { powerMultiplierStack.push(powerMultiplierCurrent); powerMultiplierStackProduct *= powerMultiplierCurrent; powerMultiplierCurrent = 1; next(); skipWhitespace(); } // Is there something here? if(c) { var oldC = c; var uStr = parseUnit(); if(uStr == null) { throw new SyntaxError('Unexpected "' + oldC + '" in "' + text + '" at index ' + index.toString()); } } else { // End of input. break; } // Verify the unit exists and get the prefix (if any) var res = _findUnit(uStr); if(res == null) { // Unit not found. throw new SyntaxError('Unit "' + uStr + '" not found.'); } var power = powerMultiplierCurrent * powerMultiplierStackProduct; // Is there a "^ number"? skipWhitespace(); if (parseCharacter('^')) { skipWhitespace(); var p = parseNumber(); if(p == null) { // No valid number found for the power! throw new SyntaxError('In "' + str + '", "^" must be followed by a floating-point number'); } power *= p; } // Add the unit to the list unit.units.push( { unit: res.unit, prefix: res.prefix, power: power }); for(var i=0; i<BASE_DIMENSIONS.length; i++) { unit.dimensions[i] += (res.unit.dimensions[i] || 0) * power; } // Check for and consume closing parentheses, popping from the stack. // A ')' will always follow a unit. skipWhitespace(); while (c === ')') { if(powerMultiplierStack.length === 0) { throw new SyntaxError('Unmatched ")" in "' + text + '" at index ' + index.toString()); } powerMultiplierStackProduct /= powerMultiplierStack.pop(); next(); skipWhitespace(); } // "*" and "/" should mean we are expecting something to come next. // Is there a forward slash? If so, negate powerMultiplierCurrent. The next unit or paren group is in the denominator. expectingUnit = false; if (parseCharacter('*')) { // explicit multiplication powerMultiplierCurrent = 1; expectingUnit = true; } ...
...
if (!expr) {
break;
}
switch (mode) {
case 'eval':
// evaluate expression
try {
var node = math.parse(expr);
var res = node.eval(scope);
if (res && res.isResultSet) {
// we can have 0 or 1 results in the ResultSet, as the CLI
// does not allow multiple expressions separated by a return
res = res.entries[0];
node = node.blocks
...
setUnitSystem = function (name) { if(UNIT_SYSTEMS.hasOwnProperty(name)) { currentUnitSystem = UNIT_SYSTEMS[name]; } else { throw new Error('Unit system ' + name + ' does not exist. Choices are: ' + Object.keys(UNIT_SYSTEMS).join(', ')); } }
n/a
_bestPrefix = function () { if (this.units.length !== 1) { throw new Error("Can only compute the best prefix for single units with integer powers, like kg, s^2, N^-1, and so forth!"); } if (Math.abs(this.units[0].power - Math.round(this.units[0].power)) >= 1e-14) { throw new Error("Can only compute the best prefix for single units with integer powers, like kg, s^2, N^-1, and so forth!"); } // find the best prefix value (resulting in the value of which // the absolute value of the log10 is closest to zero, // though with a little offset of 1.2 for nicer values: you get a // sequence 1mm 100mm 500mm 0.6m 1m 10m 100m 500m 0.6km 1km ... // Note: the units value can be any numeric type, but to find the best // prefix it's enough to work with limited precision of a regular number // Update: using mathjs abs since we also allow complex numbers var absValue = abs(this.value); var absUnitValue = abs(this.units[0].unit.value); var bestPrefix = this.units[0].prefix; if (absValue === 0) { return bestPrefix; } var power = this.units[0].power; var bestDiff = Math.log(absValue / Math.pow(bestPrefix.value * absUnitValue, power)) / Math.LN10 - 1.2; if(bestDiff > -2.200001 && bestDiff < 1.800001) return bestPrefix; // Allow the original prefix bestDiff = Math.abs(bestDiff); var prefixes = this.units[0].unit.prefixes; for (var p in prefixes) { if (prefixes.hasOwnProperty(p)) { var prefix = prefixes[p]; if (prefix.scientific) { var diff = Math.abs( Math.log(absValue / Math.pow(prefix.value * absUnitValue, power)) / Math.LN10 - 1.2); if (diff < bestDiff || (diff === bestDiff && prefix.name.length < bestPrefix.name.length)) { // choose the prefix with the smallest diff, or if equal, choose the one // with the shortest name (can happen with SHORTLONG for example) bestPrefix = prefix; bestDiff = diff; } } } } return bestPrefix; }
...
// Now apply the best prefix
// Units must have only one unit and not have the fixPrefix flag set
if (this.units.length === 1 && !this.fixPrefix) {
// Units must have integer powers, otherwise the prefix will change the
// outputted value by not-an-integer-power-of-ten
if (Math.abs(this.units[0].power - Math.round(this.units[0].power)) < 1e-14) {
// Apply the best prefix
this.units[0].prefix = this._bestPrefix();
}
}
var value = this._denormalize(this.value);
var str = (this.value !== null) ? format(value, options || {}) : '';
var unitStr = this.formatUnits();
...
_denormalize = function (value, prefixValue) { var unitValue, unitOffset, unitPower, unitPrefixValue; var convert; if (value == null || this.units.length === 0) { return value; } else if (this._isDerived()) { // This is a derived unit, so do not apply offsets. // For example, with J kg^-1 degC^-1 you would NOT want to apply the offset. // Also, prefixValue is ignored--but we will still use the prefix value stored in each unit, since kg is usually preferable to g unless the user decides otherwise. var res = value; convert = Unit._getNumberConverter(getTypeOf(value)); // convert to Fraction or BigNumber if needed for (var i = 0; i < this.units.length; i++) { unitValue = convert(this.units[i].unit.value); unitPrefixValue = convert(this.units[i].prefix.value); unitPower = convert(this.units[i].power); res = divide(res, pow(multiply(unitValue, unitPrefixValue), unitPower)); } return res; } else { // This is a single unit of power 1, like kg or degC convert = Unit._getNumberConverter(getTypeOf(value)); // convert to Fraction or BigNumber if needed unitValue = convert(this.units[0].unit.value); unitPrefixValue = convert(this.units[0].prefix.value); unitOffset = convert(this.units[0].unit.offset); if (prefixValue == undefined) { return subtract(divide(divide(value, unitValue), unitPrefixValue), unitOffset); } else { return subtract(divide(divide(value, unitValue), prefixValue), unitOffset); } } }
...
var other = this;
if(valuelessUnit) {
// Allow getting the numeric value without converting to a different unit
other = this.to(valuelessUnit);
}
if(other._isDerived()) {
return other._denormalize(other.value);
}
else {
return other._denormalize(other.value, other.units[0].prefix.value);
}
};
/**
...
_isDerived = function () { if(this.units.length === 0) { return false; } return this.units.length > 1 || Math.abs(this.units[0].power - 1.0) > 1e-15; }
...
Unit.prototype._normalize = function (value) {
var unitValue, unitOffset, unitPower, unitPrefixValue;
var convert;
if (value == null || this.units.length === 0) {
return value;
}
else if (this._isDerived()) {
// This is a derived unit, so do not apply offsets.
// For example, with J kg^-1 degC^-1 you would NOT want to apply the offset.
var res = value;
convert = Unit._getNumberConverter(getTypeOf(value)); // convert to Fraction or BigNumber if needed
for(var i=0; i < this.units.length; i++) {
unitValue = convert(this.units[i].unit.value);
...
_normalize = function (value) { var unitValue, unitOffset, unitPower, unitPrefixValue; var convert; if (value == null || this.units.length === 0) { return value; } else if (this._isDerived()) { // This is a derived unit, so do not apply offsets. // For example, with J kg^-1 degC^-1 you would NOT want to apply the offset. var res = value; convert = Unit._getNumberConverter(getTypeOf(value)); // convert to Fraction or BigNumber if needed for(var i=0; i < this.units.length; i++) { unitValue = convert(this.units[i].unit.value); unitPrefixValue = convert(this.units[i].prefix.value); unitPower = convert(this.units[i].power); res = multiply(res, pow(multiply(unitValue, unitPrefixValue), unitPower)); } return res; } else { // This is a single unit of power 1, like kg or degC convert = Unit._getNumberConverter(getTypeOf(value)); // convert to Fraction or BigNumber if needed unitValue = convert(this.units[0].unit.value); unitOffset = convert(this.units[0].unit.offset); unitPrefixValue = convert(this.units[0].prefix.value); return multiply(add(value, unitOffset), multiply(unitValue, unitPrefixValue)); } }
...
'Fraction, Fraction': function (x, y) {
return x.div(y);
},
'Unit, number | Fraction | BigNumber': function (x, y) {
var res = x.clone();
// TODO: move the divide function to Unit.js, it uses internals of Unit
res.value = divideScalar(((res.value === null) ? res._normalize(1) : res.value), y);
return res;
},
'number | Fraction | BigNumber, Unit': function (x, y) {
var res = y.pow(-1);
// TODO: move the divide function to Unit.js, it uses internals of Unit
res.value = multiplyScalar(((res.value === null) ? res._normalize(1) : res.value), x);
...
abs = function () { // This gives correct, but unexpected, results for units with an offset. // For example, abs(-283.15 degC) = -263.15 degC !!! var ret = this.clone(); ret.value = abs(ret.value); for(var i in ret.units) { if(ret.units[i].unit.name === 'VA' || ret.units[i].unit.name === 'VAR') { ret.units[i].unit = UNITS["W"]; } } return ret; }
...
function factory (type, config, load, typed) {
/**
* Calculate the absolute value of a number. For matrices, the function is
* evaluated element wise.
*
* Syntax:
*
* math.abs(x)
*
* Examples:
*
* math.abs(3.5); // returns number 3.5
* math.abs(-4.2); // returns number 4.2
*
* math.abs([3, -5, -1, 0, 2]); // returns Array [3, 5, 1, 0, 2]
...
clone = function () { var unit = new Unit(); unit.fixPrefix = this.fixPrefix; unit.isUnitListSimplified = this.isUnitListSimplified; unit.value = clone(this.value); unit.dimensions = this.dimensions.slice(0); unit.units = []; for(var i = 0; i < this.units.length; i++) { unit.units[i] = { }; for (var p in this.units[i]) { if (this.units[i].hasOwnProperty(p)) { unit.units[i][p] = this.units[i][p]; } } } return unit; }
...
return desc;
};
/**
* Export the help object to JSON
*/
Help.prototype.toJSON = function () {
var obj = object.clone(this.doc);
obj.mathjs = 'Help';
return obj;
};
/**
* Instantiate a Help object from a JSON object
* @param {Object} json
...
divide = function (other) { var res = this.clone(); for(var i=0; i<BASE_DIMENSIONS.length; i++) { // Dimensions arrays may be of different lengths. Default to 0. res.dimensions[i] = (this.dimensions[i] || 0) - (other.dimensions[i] || 0); } // Invert and append other's units list onto res (simplify later in Unit.prototype.format) for(var i=0; i<other.units.length; i++) { // Make a deep copy var inverted = {}; for(var key in other.units[i]) { inverted[key] = other.units[i][key]; } inverted.power = -inverted.power; res.units.push(inverted); } // If at least one operand has a value, the result should have a value if (this.value != null || other.value != null) { var valThis = this.value == null ? this._normalize(1) : this.value; var valOther = other.value == null ? other._normalize(1) : other.value; res.value = divide(valThis, valOther); } else { res.value = null; } // Trigger simplification of the unit list at some future time res.isUnitListSimplified = false; return getNumericIfUnitless(res); }
...
/**
* Divide two values, `x / y`.
* To divide matrices, `x` is multiplied with the inverse of `y`: `x * inv(y)`.
*
* Syntax:
*
* math.divide(x, y)
*
* Examples:
*
* math.divide(2, 3); // returns number 0.6666666666666666
*
* var a = math.complex(5, 14);
* var b = math.complex(4, 1);
...
equalBase = function (other) { // All dimensions must be the same for(var i=0; i<BASE_DIMENSIONS.length; i++) { if (Math.abs((this.dimensions[i] || 0) - (other.dimensions[i] || 0)) > 1e-12) { return false; } } return true; }
...
'Fraction, Fraction': function (x, y) {
return x.add(y);
},
'Unit, Unit': function (x, y) {
if (x.value == null) throw new Error('Parameter x contains a unit with undefined value');
if (y.value == null) throw new Error('Parameter y contains a unit with undefined value');
if (!x.equalBase(y)) throw new Error('Units do not match');
var res = x.clone();
res.value = add(res.value, y.value);
res.fixPrefix = false;
return res;
}
});
...
equals = function (other) { return (this.equalBase(other) && equal(this.value, other.value)); }
...
if (inv) {
root = root.neg();
}
if (root.isZero()) {
throw new Error('Root must be non-zero');
}
if (a.isNegative() && !root.abs().mod(2).equals(1)) {
throw new Error('Root must be odd when a is negative.');
}
// edge cases zero and infinity
if (a.isZero()) {
return inv ? new Big(Infinity) : 0;
}
...
format = function (options) { // Simplfy the unit list, if necessary this.simplifyUnitListLazy(); // Apply some custom logic for handling VA and VAR. The goal is to express the value of the unit as a real value, if possible. Otherwise, use a real-valued unit instead of a complex-valued one. var isImaginary = false; var isReal = true; if(typeof(this.value) !== 'undefined' && this.value !== null && this.value.isComplex) { // TODO: Make this better, for example, use relative magnitude of re and im rather than absolute isImaginary = Math.abs(this.value.re) < 1e-14; isReal = Math.abs(this.value.im) < 1e-14; } for(var i in this.units) { if(this.units[i].unit) { if(this.units[i].unit.name === 'VA' && isImaginary) { this.units[i].unit = UNITS["VAR"]; } else if(this.units[i].unit.name === 'VAR' && !isImaginary) { this.units[i].unit = UNITS["VA"]; } } } // Now apply the best prefix // Units must have only one unit and not have the fixPrefix flag set if (this.units.length === 1 && !this.fixPrefix) { // Units must have integer powers, otherwise the prefix will change the // outputted value by not-an-integer-power-of-ten if (Math.abs(this.units[0].power - Math.round(this.units[0].power)) < 1e-14) { // Apply the best prefix this.units[0].prefix = this._bestPrefix(); } } var value = this._denormalize(this.value); var str = (this.value !== null) ? format(value, options || {}) : ''; var unitStr = this.formatUnits(); if(this.value && this.value.isComplex) { str = "(" + str + ")"; // Surround complex values with ( ) to enable better parsing } if(unitStr.length > 0 && str.length > 0) { str += " "; } str += unitStr; return str; }
...
* Helper function to format a value. Regular numbers will be rounded
* to 14 digits to prevent round-off errors from showing up.
* @param {*} value
*/
function format(value) {
var math = getMath();
return math.format(value, {
fn: function (value) {
if (typeof value === 'number') {
// round numbers
return math.format(value, PRECISION);
}
else {
return math.format(value);
...
formatUnits = function () { // Lazy evaluation of the unit list this.simplifyUnitListLazy(); var strNum = ""; var strDen = ""; var nNum = 0; var nDen = 0; for(var i=0; i<this.units.length; i++) { if(this.units[i].power > 0) { nNum++; strNum += " " + this.units[i].prefix.name + this.units[i].unit.name; if(Math.abs(this.units[i].power - 1.0) > 1e-15) { strNum += "^" + this.units[i].power; } } else if(this.units[i].power < 0) { nDen++; } } if(nDen > 0) { for(var i=0; i<this.units.length; i++) { if(this.units[i].power < 0) { if(nNum > 0) { strDen += " " + this.units[i].prefix.name + this.units[i].unit.name; if(Math.abs(this.units[i].power + 1.0) > 1e-15) { strDen += "^" + (-this.units[i].power); } } else { strDen += " " + this.units[i].prefix.name + this.units[i].unit.name; strDen += "^" + (this.units[i].power); } } } } // Remove leading " " strNum = strNum.substr(1); strDen = strDen.substr(1); // Add parans for better copy/paste back into the eval, for example, or for better pretty print formatting if(nNum > 1 && nDen > 0) { strNum = "(" + strNum + ")"; } if(nDen > 1 && nNum > 0) { strDen = "(" + strDen + ")"; } var str = strNum; if(nNum > 0 && nDen > 0) { str += " / "; } str += strDen; return str; }
...
* @returns {Object} Returns a JSON object structured as:
* `{"mathjs": "Unit", "value": 2, "unit": "cm", "fixPrefix
": false}`
*/
Unit.prototype.toJSON = function () {
return {
mathjs: 'Unit',
value: this._denormalize(this.value),
unit: this.formatUnits(),
fixPrefix: this.fixPrefix
};
};
/**
* Instantiate a Unit from a JSON object
* @memberof Unit
...
hasBase = function (base) { if(typeof(base) === "string") { base = BASE_UNITS[base]; } if(!base) return false; // All dimensions must be the same for(var i=0; i<BASE_DIMENSIONS.length; i++) { if (Math.abs((this.dimensions[i] || 0) - (base.dimensions[i] || 0)) > 1e-12) { return false; } } return true; }
...
},
'BigNumber': function (x) {
return x.cosh();
},
'Unit': function (x) {
if (!x.hasBase(type.Unit.BASE_UNITS.ANGLE)) {
throw new TypeError ('Unit in function cosh is no angle');
}
return cosh(x.value);
},
'Array | Matrix': function (x) {
return deepMap(x, cosh);
...
multiply = function (other) { var res = this.clone(); for(var i = 0; i<BASE_DIMENSIONS.length; i++) { // Dimensions arrays may be of different lengths. Default to 0. res.dimensions[i] = (this.dimensions[i] || 0) + (other.dimensions[i] || 0); } // Append other's units list onto res (simplify later in Unit.prototype.format) for(var i=0; i<other.units.length; i++) { // Make a deep copy var inverted = {}; for(var key in other.units[i]) { inverted[key] = other.units[i][key]; } res.units.push(inverted); } // If at least one operand has a value, then the result should also have a value if(this.value != null || other.value != null) { var valThis = this.value == null ? this._normalize(1) : this.value; var valOther = other.value == null ? other._normalize(1) : other.value; res.value = multiply(valThis, valOther); } else { res.value = null; } // Trigger simplification of the unit list at some future time res.isUnitListSimplified = false; return getNumericIfUnitless(res); }
...
math.eval('sin(45 deg) ^ 2'); // 0.5
math.eval('9 / 3 + 2i'); // 3 + 2i
math.eval('det([-1, 2; 3, 1])'); // -7
// chaining
math.chain(3)
.add(4)
.multiply(2)
.done(); // 14
```
## Browser support
Math.js works on any ES5 compatible JavaScript engine: node.js 0.10, and Internet Explorer 9 and newer, and all other browsers (
Chrome, Firefox, Safari). If support for old browsers like Internet Explorer 8 is required, the [es5-shim](https://github.com/kriskowal
/es5-shim) library has to be loaded.
...
pow = function (p) { var res = this.clone(); for(var i=0; i<BASE_DIMENSIONS.length; i++) { // Dimensions arrays may be of different lengths. Default to 0. res.dimensions[i] = (this.dimensions[i] || 0) * p; } // Adjust the power of each unit in the list for(var i=0; i<res.units.length; i++) { res.units[i].power *= p; } if(res.value != null) { res.value = pow(res.value, p); // only allow numeric output, we don't want to return a Complex number //if (!isNumeric(res.value)) { // res.value = NaN; //} // Update: Complex supported now } else { res.value = null; } // Trigger lazy evaluation of the unit list res.isUnitListSimplified = false; return getNumericIfUnitless(res); }
...
var math = require('mathjs');
// functions and constants
math.round(math.e, 3); // 2.718
math.atan2(3, -3) / math.pi; // 0.75
math.log(1000, 10); // 3
math.sqrt(-4); // 2i
math.pow([[-1, 2], [3, 1]], 2); // [[7, 0], [0, 7]]
math.derivative('x^2 + x', 'x'); // 2 * x + 1
// expressions
math.eval('12 / (2.3 + 0.7)'); // 4
math.eval('5.08 cm to inch'); // 2 inch
math.eval('sin(45 deg) ^ 2'); // 0.5
math.eval('9 / 3 + 2i'); // 3 + 2i
...
simplifyUnitListLazy = function () { if (this.isUnitListSimplified || this.value == null) { return; } var proposedUnitList = []; // Search for a matching base var matchingBase; for(var key in currentUnitSystem) { if(this.hasBase(BASE_UNITS[key])) { matchingBase = key; break; } } if(matchingBase === 'NONE') { this.units = []; } else { var matchingUnit; if(matchingBase) { // Does the unit system have a matching unit? if(currentUnitSystem.hasOwnProperty(matchingBase)) { matchingUnit = currentUnitSystem[matchingBase]; } } var value; var str; if(matchingUnit) { this.units = [{ unit: matchingUnit.unit, prefix: matchingUnit.prefix, power: 1.0 }]; } else { // Multiple units or units with powers are formatted like this: // 5 (kg m^2) / (s^3 mol) // Build an representation from the base units of the current unit system var missingBaseDim = false; for(var i=0; i<BASE_DIMENSIONS.length; i++) { var baseDim = BASE_DIMENSIONS[i]; if(Math.abs(this.dimensions[i] || 0) > 1e-12) { if(currentUnitSystem.hasOwnProperty(baseDim)) { proposedUnitList.push({ unit: currentUnitSystem[baseDim].unit, prefix: currentUnitSystem[baseDim].prefix, power: this.dimensions[i] || 0 }); } else { missingBaseDim = true; } } } // Is the proposed unit list "simpler" than the existing one? if(proposedUnitList.length < this.units.length && !missingBaseDim) { // Replace this unit list with the proposed list this.units = proposedUnitList; } } } this.isUnitListSimplified = true; }
...
* Get a string representation of the units of this Unit, without the value.
* @memberof Unit
* @return {string}
*/
Unit.prototype.formatUnits = function () {
// Lazy evaluation of the unit list
this.simplifyUnitListLazy();
var strNum = "";
var strDen = "";
var nNum = 0;
var nDen = 0;
for(var i=0; i<this.units.length; i++) {
...
splitUnit = function (parts) { var x = this.clone(); var ret = []; for(var i=0; i<parts.length; i++) { x = x.to(parts[i]); if(i==parts.length-1) break; // fix rounds a number towards 0 var fixedVal = fix(x.toNumeric()); var y = new Unit(fixedVal, parts[i].toString()); ret.push(y); x = subtract(x, y); } ret.push(x); return ret; }
...
* Returns an array of units whose sum is equal to this unit
* @memberof Unit
* @param {Array} [parts] An array of strings or valueless units.
*
* Example:
*
* var u = new Unit(1, 'm');
* u.splitUnit(['feet', 'inch']);
* [ 3 feet, 3.3700787401575 inch ]
*
* @return {Array} An array of units.
*/
Unit.prototype.splitUnit = function(parts) {
var x = this.clone();
...
to = function (valuelessUnit) { var other; var value = this.value == null ? this._normalize(1) : this.value; if (typeof valuelessUnit === 'string') { //other = new Unit(null, valuelessUnit); other = Unit.parse(valuelessUnit); if (!this.equalBase(other)) { throw new Error('Units do not match'); } if (other.value !== null) { throw new Error('Cannot convert to a unit with a value'); } other.value = clone(value); other.fixPrefix = true; other.isUnitListSimplified = true; return other; } else if (valuelessUnit && valuelessUnit.isUnit) { if (!this.equalBase(valuelessUnit)) { throw new Error('Units do not match'); } if (valuelessUnit.value !== null) { throw new Error('Cannot convert to a unit with a value'); } other = valuelessUnit.clone(); other.value = clone(value); other.fixPrefix = true; other.isUnitListSimplified = true; return other; } else { throw new Error('String or Unit expected as parameter'); } }
...
*
* Examples:
*
* math.string(4.2); // returns string '4.2'
* math.string(math.complex(3, 2); // returns string '3 + 2i'
*
* var u = math.unit(5, 'km');
* math.string(u.to('m')); // returns string '5000 m'
*
* math.string([true, false]); // returns ['true', 'false']
*
* See also:
*
* bignumber, boolean, complex, index, matrix, number, unit
*
...
toJSON = function () { return { mathjs: 'Unit', value: this._denormalize(this.value), unit: this.formatUnits(), fixPrefix: this.fixPrefix }; }
n/a
toNumber = function (valuelessUnit) { return toNumber(this.toNumeric(valuelessUnit)); }
...
convert: function (x) {
return x + '';
}
}, {
from: 'BigNumber',
to: 'Complex',
convert: function (x) {
return new type.Complex(x.toNumber(), 0);
}
}, {
from: 'Fraction',
to: 'BigNumber',
convert: function (x) {
throw new TypeError('Cannot implicitly convert a Fraction to BigNumber or vice versa. ' +
'Use function bignumber(x) to convert to BigNumber or fraction(x) to convert to Fraction.');
...
toNumeric = function (valuelessUnit) { var other = this; if(valuelessUnit) { // Allow getting the numeric value without converting to a different unit other = this.to(valuelessUnit); } if(other._isDerived()) { return other._denormalize(other.value); } else { return other._denormalize(other.value, other.units[0].prefix.value); } }
...
* Return the value of the unit when represented with given valueless unit
* @memberof Unit
* @param {string | Unit} valuelessUnit For example 'cm' or 'inch'
* @return {number} Returns the unit value as number.
*/
// TODO: deprecate Unit.toNumber? It's always better to use toNumeric
Unit.prototype.toNumber = function (valuelessUnit) {
return toNumber(this.toNumeric(valuelessUnit));
};
/**
* Return the value of the unit in the original numeric type
* @memberof Unit
* @param {string | Unit} valuelessUnit For example 'cm' or 'inch'
* @return {number | BigNumber | Fraction} Returns the unit value
...
toSI = function () { var ret = this.clone(); var proposedUnitList = []; // Multiple units or units with powers are formatted like this: // 5 (kg m^2) / (s^3 mol) // Build an representation from the base units of the SI unit system var missingBaseDim = false; for(var i=0; i<BASE_DIMENSIONS.length; i++) { var baseDim = BASE_DIMENSIONS[i]; if(Math.abs(ret.dimensions[i] || 0) > 1e-12) { if(UNIT_SYSTEMS["si"].hasOwnProperty(baseDim)) { proposedUnitList.push({ unit: UNIT_SYSTEMS["si"][baseDim].unit, prefix: UNIT_SYSTEMS["si"][baseDim].prefix, power: ret.dimensions[i] || 0 }); } else { throw new Error("Cannot express custom unit " + baseDim + " in SI units"); } } } // Replace this unit list with the proposed list ret.units = proposedUnitList; ret.isUnitListSimplified = true; return ret; }
n/a
toString = function () { return this.format(); }
...
}
else {
scope.ans = res;
console.log(format(res));
}
}
else if (res instanceof math.type.Help) {
console.log(res.toString());
}
else {
scope.ans = res;
console.log(format(res));
}
}
}
...
valueOf = function () { return this.format(); }
...
throw new TypeError('Cannot implicitly convert a Fraction to BigNumber or vice versa. ' +
'Use function bignumber(x) to convert to BigNumber or fraction(x) to convert to Fraction.');
}
}, {
from: 'Fraction',
to: 'Complex',
convert: function (x) {
return new type.Complex(x.valueOf(), 0);
}
}, {
from: 'number',
to: 'Fraction',
convert: function (x) {
if (digits(x) > 15) {
throw new TypeError('Cannot implicitly convert a number with >15 significant digits to Fraction ' +
...
function typed(arg0, arg1) { "use strict"; var name = 'typed'; if (test0(arg0)) { // type: string if (test1(arg1)) { // type: Object if (arguments.length === 2) { return signature0(arg0, arg1); // signature: string, Object } if (arguments.length > 2) { throw createError(name, arguments.length, 2, arguments[2]); } } throw createError(name, arguments.length, 1, arguments[1], 'Object'); } if (test2(arg0)) { // type: ...Function var varArgs = [arg0]; for (var i = 1; i < arguments.length; i++) { if (test2(arguments[i])) { varArgs.push(arguments[i]); } else { throw createError(name, arguments.length, i, arguments[i], 'Function'); } } return signature1(varArgs); // signature: ...Function } if (test1(arg0)) { // type: Object if (arguments.length === 1) { return signature2(arg0); // signature: Object } if (arguments.length > 1) { throw createError(name, arguments.length, 1, arguments[1]); } } throw createError(name, arguments.length, 0, arguments[0], 'string,Function,Object'); }
n/a
addConversion = function (conversion) { if (!conversion || typeof conversion.from !== 'string' || typeof conversion.to !== 'string' || typeof conversion.convert !== 'function') { throw new TypeError('Object with properties {from: string, to: string, convert: function} expected'); } typed.conversions.push(conversion); }
n/a
addType = function (type) { if (!type || typeof type.name !== 'string' || typeof type.test !== 'function') { throw new TypeError('Object with properties {name: string, test: function} expected'); } typed.types.push(type); }
n/a
function convert(value, type) { var from = getTypeOf(value); // check conversion is needed if (type === from) { return value; } for (var i = 0; i < typed.conversions.length; i++) { var conversion = typed.conversions[i]; if (conversion.from === from && conversion.to === type) { return conversion.convert(value); } } throw new Error('Cannot convert from ' + from + ' to ' + type); }
...
// datatype
dt = adt;
// find signatures that matches (dt, dt)
af = typed.find(addScalar, [dt, dt]);
mf = typed.find(multiplyScalar, [dt, dt]);
eq = typed.find(equalScalar, [dt, dt]);
// convert 0 to the same datatype
zero = typed.convert(0, dt);
}
// result
var cvalues = [];
var cindex = [];
var cptr = [];
// c matrix
...
function create() {
/**
* Get a type test function for a specific data type
* @param {string} name Name of a data type like 'number' or 'string'
* @returns {Function(obj: *) : boolean} Returns a type testing function.
* Throws an error for an unknown type.
*/
function getTypeTest(name) {
var test;
for (var i = 0; i < typed.types.length; i++) {
var entry = typed.types[i];
if (entry.name === name) {
test = entry.test;
break;
}
}
if (!test) {
var hint;
for (i = 0; i < typed.types.length; i++) {
entry = typed.types[i];
if (entry.name.toLowerCase() == name.toLowerCase()) {
hint = entry.name;
break;
}
}
throw new Error('Unknown type "' + name + '"' +
(hint ? ('. Did you mean "' + hint + '"?') : ''));
}
return test;
}
/**
* Retrieve the function name from a set of functions, and check
* whether the name of all functions match (if given)
* @param {Array.<function>} fns
*/
function getName (fns) {
var name = '';
for (var i = 0; i < fns.length; i++) {
var fn = fns[i];
// merge function name when this is a typed function
if (fn.signatures && fn.name != '') {
if (name == '') {
name = fn.name;
}
else if (name != fn.name) {
var err = new Error('Function names do not match (expected: ' + name + ', actual: ' + fn.name + ')');
err.data = {
actual: fn.name,
expected: name
};
throw err;
}
}
}
return name;
}
/**
* Create an ArgumentsError. Creates messages like:
*
* Unexpected type of argument (expected: ..., actual: ..., index: ...)
* Too few arguments (expected: ..., index: ...)
* Too many arguments (expected: ..., actual: ...)
*
* @param {String} fn Function name
* @param {number} argCount Number of arguments
* @param {Number} index Current argument index
* @param {*} actual Current argument
* @param {string} [expected] An optional, comma separated string with
* expected types on given index
* @extends Error
*/
function createError(fn, argCount, index, actual, expected) {
var actualType = getTypeOf(actual);
var _expected = expected ? expected.split(',') : null;
var _fn = (fn || 'unnamed');
var anyType = _expected && contains(_expected, 'any');
var message;
var data = {
fn: fn,
index: index,
actual: actual,
expected: _expected
};
if (_expected) {
if (argCount > index && !anyType) {
// unexpected type
message = 'Unexpected type of argument in function ' + _fn +
' (expected: ' + _expected.join(' or ') + ', actual: ' + actualType + ', index: ' + index + ')';
}
else {
// too few arguments
message = 'Too few arguments in function ' + _fn +
' (expected: ' + _expected.join(' or ') + ', index: ' + index + ')';
}
}
else {
// too many arguments
message = 'Too many arguments in function ' + _fn +
' (expected: ' + index + ', actual: ' + argCount + ')'
}
var err = new TypeError(message);
err.data = data;
return err;
}
/**
* Collection with function references (local shortcuts to functions)
* @constructor
* @param {string} [name='refs'] Optional name for the refs, used to generate
* JavaScript code
*/
function Refs(name) {
this.name = name || 'refs';
this.categories = {};
}
/**
* Add a function reference.
* @param {Function} fn
* @param {string} [category='fn'] A function category, like 'fn' or 'signature'
* @returns {string} Returns the function name, for example 'fn0' or 'signature2'
*/
Refs.prototype.add = function (fn, category) {
var cat = category || 'fn';
if (!this.categories[cat]) this.categ ...
...
* false (default), output type can vary depending
* on input values. For example `math.sqrt(-4)`
* returns `complex('2i')` when predictable is false, and
* returns `NaN` when true.
*/
function create (config) {
// create a new math.js instance
var math = core.create(config);
math.create = create;
// import data types, functions, constants, expression parser, etc.
math['import'](require('./lib'));
return math;
}
...
function find(fn, signature) { if (!fn.signatures) { throw new TypeError('Function is no typed-function'); } // normalize input var arr; if (typeof signature === 'string') { arr = signature.split(','); for (var i = 0; i < arr.length; i++) { arr[i] = arr[i].trim(); } } else if (Array.isArray(signature)) { arr = signature; } else { throw new TypeError('String array or a comma separated string expected'); } var str = arr.join(','); // find an exact match var match = fn.signatures[str]; if (match) { return match; } // TODO: extend find to match non-exact signatures throw new TypeError('Signature not found (signature: ' + (fn.name || 'unnamed') + '(' + arr.join(', ') + '))'); }
...
var mf = multiplyScalar;
// process data types
if (adt && bdt && adt === bdt && typeof adt === 'string') {
// datatype
dt = adt;
// find signatures that matches (dt, dt)
af = typed.find(addScalar, [dt, dt]);
mf = typed.find(multiplyScalar, [dt, dt]);
}
// result (do not initialize it with zero)
var c = mf(adata[0], bdata[0]);
// loop data
for (var i = 1; i < n; i++) {
...
Object = function (signatures) { var fns = []; for (var signature in signatures) { if (signatures.hasOwnProperty(signature)) { fns.push(signatures[signature]); } } var name = getName(fns); return _typed(name, signatures); }
n/a
function factory(type, config, load, typed) {
/**
* Determine the type of a variable.
*
* Function `typeof` recognizes the following types of objects:
*
* Object | Returns | Example
* ---------------------- | ------------- | ------------------------------------------
* null | `'null'` | `math.typeof(null)`
* number | `'number'` | `math.typeof(3.5)`
* boolean | `'boolean'` | `math.typeof (true)`
* string | `'string'` | `math.typeof ('hello world')`
* Array | `'Array'` | `math.typeof ([1, 2, 3])`
* Date | `'Date'` | `math.typeof (new Date())`
* Function | `'Function'` | `math.typeof (function () {})`
* Object | `'Object'` | `math.typeof ({a: 2, b: 3})`
* RegExp | `'RegExp'` | `math.typeof (/a regexp/)`
* undefined | `'undefined'` | `math.typeof(undefined)`
* math.type.BigNumber | `'BigNumber'` | `math.typeof (math.bignumber('2.3e500'))`
* math.type.Chain | `'Chain'` | `math.typeof (math.chain(2))`
* math.type.Complex | `'Complex'` | `math.typeof (math.complex(2, 3))`
* math.type.Fraction | `'Fraction'` | `math.typeof (math.fraction(1, 3))`
* math.type.Help | `'Help'` | `math.typeof (math.help('sqrt'))`
* math.type.Index | `'Index'` | `math.typeof (math.index(1, 3))`
* math.type.Matrix | `'Matrix'` | `math.typeof (math.matrix([[1,2], [3, 4]]))`
* math.type.Range | `'Range'` | `math.typeof (math.range(0, 10))`
* math.type.Unit | `'Unit'` | `math.typeof (math.unit('45 deg'))`
*
* Syntax:
*
* math.typeof(x)
*
* Examples:
*
* math.typeof(3.5); // returns 'number'
* math.typeof(math.complex('2-4i')); // returns 'Complex'
* math.typeof(math.unit('45 deg')); // returns 'Unit'
* math.typeof('hello world'); // returns 'string'
*
* @param {*} x The variable for which to test the type.
* @return {string} Returns the name of the type. Primitive types are lower case,
* non-primitive types are upper-camel-case.
* For example 'number', 'string', 'Array', 'Date'.
*/
var _typeof = typed('_typeof', {
'any': function (x) {
// JavaScript types
var t = types.type(x);
// math.js types
if (t === 'Object') {
if (x.isBigNumber === true) return 'BigNumber';
if (x.isComplex === true) return 'Complex';
if (x.isFraction === true) return 'Fraction';
if (x.isMatrix === true) return 'Matrix';
if (x.isUnit === true) return 'Unit';
if (x.isIndex === true) return 'Index';
if (x.isRange === true) return 'Range';
if (x.isChain === true) return 'Chain';
if (x.isHelp === true) return 'Help';
}
return t;
}
});
_typeof.toTex = undefined; // use default template
return _typeof;
}
n/a
isScalar = function (x) { return !((x && x.isMatrix) || Array.isArray(x)); }
...
* @private
*/
function _get (matrix, index) {
if (!index || index.isIndex !== true) {
throw new TypeError('Invalid index');
}
var isScalar = index.isScalar();
if (isScalar) {
// return a scalar
return matrix.get(index.min());
}
else {
// validate dimensions
var size = index.size();
...
type = function (x) { var type = typeof x; if (type === 'object') { if (x === null) return 'null'; if (x instanceof Boolean) return 'boolean'; if (x instanceof Number) return 'number'; if (x instanceof String) return 'string'; if (Array.isArray(x)) return 'Array'; if (x instanceof Date) return 'Date'; if (x instanceof RegExp) return 'RegExp'; return 'Object'; } if (type === 'function') return 'Function'; return type; }
...
* @return {string} Returns the name of the type. Primitive types are lower case,
* non-primitive types are upper-camel-case.
* For example 'number', 'string', 'Array', 'Date'.
*/
var _typeof = typed('_typeof', {
'any': function (x) {
// JavaScript types
var t = types.type(x);
// math.js types
if (t === 'Object') {
if (x.isBigNumber === true) return 'BigNumber';
if (x.isComplex === true) return 'Complex';
if (x.isFraction === true) return 'Fraction';
if (x.isMatrix === true) return 'Matrix';
...
function factory(type, config, load, typed) {
var latex = require('../../utils/latex');
/**
* Inverse the sign of a value, apply a unary minus operation.
*
* For matrices, the function is evaluated element wise. Boolean values and
* strings will be converted to a number. For complex numbers, both real and
* complex value are inverted.
*
* Syntax:
*
* math.unaryMinus(x)
*
* Examples:
*
* math.unaryMinus(3.5); // returns -3.5
* math.unaryMinus(-4.2); // returns 4.2
*
* See also:
*
* add, subtract, unaryPlus
*
* @param {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} x Number to be inverted.
* @return {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} Returns the value with inverted sign.
*/
var unaryMinus = typed('unaryMinus', {
'number': function (x) {
return -x;
},
'Complex': function (x) {
return x.neg();
},
'BigNumber': function (x) {
return x.neg();
},
'Fraction': function (x) {
return x.neg();
},
'Unit': function (x) {
var res = x.clone();
res.value = unaryMinus(x.value);
return res;
},
'Array | Matrix': function (x) {
// deep map collection, skip zeros since unaryMinus(0) = 0
return deepMap(x, unaryMinus, true);
}
// TODO: add support for string
});
unaryMinus.toTex = {
1: latex.operators['unaryMinus'] + '\\left(${args[0]}\\right)'
};
return unaryMinus;
}
n/a
function factory(type, config, load, typed) {
var latex = require('../../utils/latex');
/**
* Unary plus operation.
* Boolean values and strings will be converted to a number, numeric values will be returned as is.
*
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.unaryPlus(x)
*
* Examples:
*
* math.unaryPlus(3.5); // returns 3.5
* math.unaryPlus(1); // returns 1
*
* See also:
*
* unaryMinus, add, subtract
*
* @param {number | BigNumber | Fraction | string | Complex | Unit | Array | Matrix} x
* Input value
* @return {number | BigNumber | Fraction | Complex | Unit | Array | Matrix}
* Returns the input value when numeric, converts to a number when input is non-numeric.
*/
var unaryPlus = typed('unaryPlus', {
'number': function (x) {
return x;
},
'Complex': function (x) {
return x; // complex numbers are immutable
},
'BigNumber': function (x) {
return x; // bignumbers are immutable
},
'Fraction': function (x) {
return x; // fractions are immutable
},
'Unit': function (x) {
return x.clone();
},
'Array | Matrix': function (x) {
// deep map collection, skip zeros since unaryPlus(0) = 0
return deepMap(x, unaryPlus, true);
},
'boolean | string | null': function (x) {
// convert to a number or bignumber
return (config.number == 'BigNumber') ? new type.BigNumber(+x): +x;
}
});
unaryPlus.toTex = {
1: latex.operators['unaryPlus'] + '\\left(${args[0]}\\right)'
};
return unaryPlus;
}
n/a
function factory(type, config, load, typed) {
var matrix = load(require('../../type/matrix/function/matrix'));
var algorithm03 = load(require('../../type/matrix/utils/algorithm03'));
var algorithm07 = load(require('../../type/matrix/utils/algorithm07'));
var algorithm12 = load(require('../../type/matrix/utils/algorithm12'));
var algorithm13 = load(require('../../type/matrix/utils/algorithm13'));
var algorithm14 = load(require('../../type/matrix/utils/algorithm14'));
var latex = require('../../utils/latex');
/**
* Test whether two values are unequal.
*
* The function tests whether the relative difference between x and y is
* larger than the configured epsilon. The function cannot be used to compare
* values smaller than approximately 2.22e-16.
*
* For matrices, the function is evaluated element wise.
* In case of complex numbers, x.re must unequal y.re, or x.im must unequal y.im.
*
* Values `null` and `undefined` are compared strictly, thus `null` is unequal
* with everything except `null`, and `undefined` is unequal with everying
* except. `undefined`.
*
* Syntax:
*
* math.unequal(x, y)
*
* Examples:
*
* math.unequal(2 + 2, 3); // returns true
* math.unequal(2 + 2, 4); // returns false
*
* var a = math.unit('50 cm');
* var b = math.unit('5 m');
* math.unequal(a, b); // returns false
*
* var c = [2, 5, 1];
* var d = [2, 7, 1];
*
* math.unequal(c, d); // returns [false, true, false]
* math.deepEqual(c, d); // returns false
*
* math.unequal(0, null); // returns true
* See also:
*
* equal, deepEqual, smaller, smallerEq, larger, largerEq, compare
*
* @param {number | BigNumber | Fraction | boolean | Complex | Unit | string | Array | Matrix | undefined} x First value to compare
* @param {number | BigNumber | Fraction | boolean | Complex | Unit | string | Array | Matrix | undefined} y Second value to
compare
* @return {boolean | Array | Matrix} Returns true when the compared values are unequal, else returns false
*/
var unequal = typed('unequal', {
'any, any': function (x, y) {
// strict equality for null and undefined?
if (x === null) { return y !== null; }
if (y === null) { return x !== null; }
if (x === undefined) { return y !== undefined; }
if (y === undefined) { return x !== undefined; }
return _unequal(x, y);
},
'Matrix, Matrix': function (x, y) {
// result
var c;
// process matrix storage
switch (x.storage()) {
case 'sparse':
switch (y.storage()) {
case 'sparse':
// sparse + sparse
c = algorithm07(x, y, _unequal);
break;
default:
// sparse + dense
c = algorithm03(y, x, _unequal, true);
break;
}
break;
default:
switch (y.storage()) {
case 'sparse':
// dense + sparse
c = algorithm03(x, y, _unequal, false);
break;
default:
// dense + dense
c = algorithm13(x, y, _unequal);
break;
}
break;
}
return c;
},
'Array, Array': function (x, y) {
// use matrix implementation
return unequal(matrix(x), matrix(y)).valueOf();
},
'Array, Matrix': function (x, y) {
// use matrix implementation
return unequal(matrix(x), y);
},
'Matrix, Array': function (x, y) {
// use matrix implementation
return unequal(x, matrix(y));
},
'Matrix, any': function (x, y) {
// result
var c;
// check storage format
switch (x.storage()) {
case 'sparse':
c = algorithm12(x, y, _unequal, false);
break;
default:
c = algorithm14(x, y, _unequal, false);
break;
}
return c;
},
'any, Matrix': functi ...
n/a
function factory(type, config, load, typed) {
var add = load(require('../arithmetic/addScalar'));
var subtract = load(require('../arithmetic/subtract'));
var multiply = load(require('../arithmetic/multiplyScalar'));
var divide = load(require('../arithmetic/divideScalar'));
/**
* Compute the variance of a matrix or a list with values.
* In case of a (multi dimensional) array or matrix, the variance over all
* elements will be calculated.
*
* Optionally, the type of normalization can be specified as second
* parameter. The parameter `normalization` can be one of the following values:
*
* - 'unbiased' (default) The sum of squared errors is divided by (n - 1)
* - 'uncorrected' The sum of squared errors is divided by n
* - 'biased' The sum of squared errors is divided by (n + 1)
*
* Note that older browser may not like the variable name `var`. In that
* case, the function can be called as `math['var'](...)` instead of
* `math.var(...)`.
*
* Syntax:
*
* math.var(a, b, c, ...)
* math.var(A)
* math.var(A, normalization)
*
* Examples:
*
* math.var(2, 4, 6); // returns 4
* math.var([2, 4, 6, 8]); // returns 6.666666666666667
* math.var([2, 4, 6, 8], 'uncorrected'); // returns 5
* math.var([2, 4, 6, 8], 'biased'); // returns 4
*
* math.var([[1, 2, 3], [4, 5, 6]]); // returns 3.5
*
* See also:
*
* mean, median, max, min, prod, std, sum
*
* @param {Array | Matrix} array
* A single matrix or or multiple scalar values
* @param {string} [normalization='unbiased']
* Determines how to normalize the variance.
* Choose 'unbiased' (default), 'uncorrected', or 'biased'.
* @return {*} The variance
*/
var variance = typed('variance', {
// var([a, b, c, d, ...])
'Array | Matrix': function (array) {
return _var(array, DEFAULT_NORMALIZATION);
},
// var([a, b, c, d, ...], normalization)
'Array | Matrix, string': _var,
// var(a, b, c, d, ...)
'...': function (args) {
return _var(args, DEFAULT_NORMALIZATION);
}
});
variance.toTex = '\\mathrm{Var}\\left(${args}\\right)';
return variance;
/**
* Recursively calculate the variance of an n-dimensional array
* @param {Array} array
* @param {string} normalization
* Determines how to normalize the variance:
* - 'unbiased' The sum of squared errors is divided by (n - 1)
* - 'uncorrected' The sum of squared errors is divided by n
* - 'biased' The sum of squared errors is divided by (n + 1)
* @return {number | BigNumber} variance
* @private
*/
function _var(array, normalization) {
var sum = 0;
var num = 0;
if (array.length == 0) {
throw new SyntaxError('Function var requires one or more parameters (0 provided)');
}
// calculate the mean and number of elements
deepForEach(array, function (value) {
sum = add(sum, value);
num++;
});
if (num === 0) throw new Error('Cannot calculate var of an empty array');
var mean = divide(sum, num);
// calculate the variance
sum = 0;
deepForEach(array, function (value) {
var diff = subtract(value, mean);
sum = add(sum, multiply(diff, diff));
});
switch (normalization) {
case 'uncorrected':
return divide(sum, num);
case 'biased':
return divide(sum, num + 1);
case 'unbiased':
var zero = (sum && sum.isBigNumber === true) ? new type.BigNumber(0) : 0;
return (num == 1) ? zero : divide(sum, num - 1);
default:
throw new Error('Unknown normalization "' + normalization + '". ' +
'Choose "unbiased" (default), "uncorrected", or "biased".');
}
}
}
n/a
function factory(type, config, load, typed) {
var matrix = load(require('../../type/matrix/function/matrix'));
/**
* Calculate the extended greatest common divisor for two values.
* See http://en.wikipedia.org/wiki/Extended_Euclidean_algorithm.
*
* Syntax:
*
* math.xgcd(a, b)
*
* Examples:
*
* math.xgcd(8, 12); // returns [4, -1, 1]
* math.gcd(8, 12); // returns 4
* math.xgcd(36163, 21199); // returns [1247, -7, 12]
*
* See also:
*
* gcd, lcm
*
* @param {number | BigNumber} a An integer number
* @param {number | BigNumber} b An integer number
* @return {Array} Returns an array containing 3 integers `[div, m, n]`
* where `div = gcd(a, b)` and `a*m + b*n = div`
*/
var xgcd = typed('xgcd', {
'number, number': _xgcd,
'BigNumber, BigNumber': _xgcdBigNumber
// TODO: implement support for Fraction
});
xgcd.toTex = undefined; // use default template
return xgcd;
/**
* Calculate xgcd for two numbers
* @param {number} a
* @param {number} b
* @return {number} result
* @private
*/
function _xgcd (a, b) {
// source: http://en.wikipedia.org/wiki/Extended_Euclidean_algorithm
var t, // used to swap two variables
q, // quotient
r, // remainder
x = 0, lastx = 1,
y = 1, lasty = 0;
if (!isInteger(a) || !isInteger(b)) {
throw new Error('Parameters in function xgcd must be integer numbers');
}
while (b) {
q = Math.floor(a / b);
r = a - q*b;
t = x;
x = lastx - q * x;
lastx = t;
t = y;
y = lasty - q * y;
lasty = t;
a = b;
b = r;
}
var res;
if (a < 0) {
res = [-a, -lastx, -lasty];
}
else {
res = [a, a ? lastx : 0, lasty];
}
return (config.matrix === 'Array') ? res : matrix(res);
}
/**
* Calculate xgcd for two BigNumbers
* @param {BigNumber} a
* @param {BigNumber} b
* @return {BigNumber[]} result
* @private
*/
function _xgcdBigNumber(a, b) {
// source: http://en.wikipedia.org/wiki/Extended_Euclidean_algorithm
var t, // used to swap two variables
q, // quotient
r, // remainder
zero = new type.BigNumber(0),
one = new type.BigNumber(1),
x = zero,
lastx = one,
y = one,
lasty = zero;
if (!a.isInt() || !b.isInt()) {
throw new Error('Parameters in function xgcd must be integer numbers');
}
while (!b.isZero()) {
q = a.div(b).floor();
r = a.mod(b);
t = x;
x = lastx.minus(q.times(x));
lastx = t;
t = y;
y = lasty.minus(q.times(y));
lasty = t;
a = b;
b = r;
}
var res;
if (a.lt(zero)) {
res = [a.neg(), lastx.neg(), lasty.neg()];
}
else {
res = [a, !a.isZero() ? lastx : 0, lasty];
}
return (config.matrix === 'Array') ? res : matrix(res);
}
}
n/a
function factory(type, config, load, typed) {
var latex = require('../../utils/latex');
var matrix = load(require('../../type/matrix/function/matrix'));
var algorithm03 = load(require('../../type/matrix/utils/algorithm03'));
var algorithm07 = load(require('../../type/matrix/utils/algorithm07'));
var algorithm12 = load(require('../../type/matrix/utils/algorithm12'));
var algorithm13 = load(require('../../type/matrix/utils/algorithm13'));
var algorithm14 = load(require('../../type/matrix/utils/algorithm14'));
/**
* Logical `xor`. Test whether one and only one value is defined with a nonzero/nonempty value.
* For matrices, the function is evaluated element wise.
*
* Syntax:
*
* math.xor(x, y)
*
* Examples:
*
* math.xor(2, 4); // returns false
*
* a = [2, 0, 0];
* b = [2, 7, 0];
* c = 0;
*
* math.xor(a, b); // returns [false, true, false]
* math.xor(a, c); // returns [true, false, false]
*
* See also:
*
* and, not, or
*
* @param {number | BigNumber | Complex | Unit | Array | Matrix} x First value to check
* @param {number | BigNumber | Complex | Unit | Array | Matrix} y Second value to check
* @return {boolean | Array | Matrix}
* Returns true when one and only one input is defined with a nonzero/nonempty value.
*/
var xor = typed('xor', {
'number, number': function (x, y) {
return !!(!!x ^ !!y);
},
'Complex, Complex': function (x, y) {
return ((x.re !== 0 || x.im !== 0) !== (y.re !== 0 || y.im !== 0));
},
'BigNumber, BigNumber': function (x, y) {
return ((!x.isZero() && !x.isNaN()) !== (!y.isZero() && !y.isNaN()));
},
'Unit, Unit': function (x, y) {
return xor(x.value, y.value);
},
'Matrix, Matrix': function (x, y) {
// result
var c;
// process matrix storage
switch (x.storage()) {
case 'sparse':
switch (y.storage()) {
case 'sparse':
// sparse + sparse
c = algorithm07(x, y, xor);
break;
default:
// sparse + dense
c = algorithm03(y, x, xor, true);
break;
}
break;
default:
switch (y.storage()) {
case 'sparse':
// dense + sparse
c = algorithm03(x, y, xor, false);
break;
default:
// dense + dense
c = algorithm13(x, y, xor);
break;
}
break;
}
return c;
},
'Array, Array': function (x, y) {
// use matrix implementation
return xor(matrix(x), matrix(y)).valueOf();
},
'Array, Matrix': function (x, y) {
// use matrix implementation
return xor(matrix(x), y);
},
'Matrix, Array': function (x, y) {
// use matrix implementation
return xor(x, matrix(y));
},
'Matrix, any': function (x, y) {
// result
var c;
// check storage format
switch (x.storage()) {
case 'sparse':
c = algorithm12(x, y, xor, false);
break;
default:
c = algorithm14(x, y, xor, false);
break;
}
return c;
},
'any, Matrix': function (x, y) {
// result
var c;
// check storage format
switch (y.storage()) {
case 'sparse':
c = algorithm12(y, x, xor, true);
break;
default:
c = algorithm14(y, x, xor, true);
break;
}
return c;
},
'Array, any': function (x, y) {
// use matrix implementation
return algorithm14(matrix(x), y, xor, false).valueOf();
},
'any, Array': function (x, y) {
// use matrix implementation
return algorithm14(matrix(y), x, xor, true).valueOf();
}
});
xor.toTex = {
2: '\\left(${args[0]}' + latex.operators['xor'] + '${args[1]}\\right)'
};
return xor;
}
n/a
function factory(type, config, load, typed) {
var matrix = load(require('../../type/matrix/function/matrix'));
/**
* Create a matrix filled with zeros. The created matrix can have one or
* multiple dimensions.
*
* Syntax:
*
* math.zeros(m)
* math.zeros(m, format)
* math.zeros(m, n)
* math.zeros(m, n, format)
* math.zeros([m, n])
* math.zeros([m, n], format)
*
* Examples:
*
* math.zeros(3); // returns [0, 0, 0]
* math.zeros(3, 2); // returns [[0, 0], [0, 0], [0, 0]]
* math.zeros(3, 'dense'); // returns [0, 0, 0]
*
* var A = [[1, 2, 3], [4, 5, 6]];
* math.zeros(math.size(A)); // returns [[0, 0, 0], [0, 0, 0]]
*
* See also:
*
* ones, eye, size, range
*
* @param {...number | Array} size The size of each dimension of the matrix
* @param {string} [format] The Matrix storage format
*
* @return {Array | Matrix} A matrix filled with zeros
*/
var zeros = typed('zeros', {
'': function () {
return (config.matrix === 'Array')
? _zeros([])
: _zeros([], 'default');
},
// math.zeros(m, n, p, ..., format)
// TODO: more accurate signature '...number | BigNumber, string' as soon as typed-function supports this
'...number | BigNumber | string': function (size) {
var last = size[size.length - 1];
if (typeof last === 'string') {
var format = size.pop();
return _zeros(size, format);
}
else if (config.matrix === 'Array') {
return _zeros(size);
}
else {
return _zeros(size, 'default');
}
},
'Array': _zeros,
'Matrix': function (size) {
var format = size.storage();
return _zeros(size.valueOf(), format);
},
'Array | Matrix, string': function (size, format) {
return _zeros (size.valueOf(), format);
}
});
zeros.toTex = undefined; // use default template
return zeros;
/**
* Create an Array or Matrix with zeros
* @param {Array} size
* @param {string} [format='default']
* @return {Array | Matrix}
* @private
*/
function _zeros(size, format) {
var hasBigNumbers = _normalize(size);
var defaultValue = hasBigNumbers ? new type.BigNumber(0) : 0;
_validate(size);
if (format) {
// return a matrix
var m = matrix(format);
if (size.length > 0) {
return m.resize(size, defaultValue);
}
return m;
}
else {
// return an Array
var arr = [];
if (size.length > 0) {
return resize(arr, size, defaultValue);
}
return arr;
}
}
// replace BigNumbers with numbers, returns true if size contained BigNumbers
function _normalize(size) {
var hasBigNumbers = false;
size.forEach(function (value, index, arr) {
if (value && value.isBigNumber === true) {
hasBigNumbers = true;
arr[index] = value.toNumber();
}
});
return hasBigNumbers;
}
// validate arguments
function _validate (size) {
size.forEach(function (value) {
if (typeof value !== 'number' || !isInteger(value) || value < 0) {
throw new Error('Parameters in function zeros must be positive integers');
}
});
}
}
n/a