Intial Commit

This commit is contained in:
valki
2020-10-17 18:42:50 +02:00
commit 664c6d8ca3
5892 changed files with 759183 additions and 0 deletions

View File

@@ -0,0 +1,68 @@
'use strict';
var object = require('./utils/object');
var bigConstants = require('./utils/bignumber/constants');
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);
}
});
math['true'] = true;
math['false'] = false;
math['null'] = null;
math['uninitialized'] = require('./utils/array').UNINITIALIZED;
if (config.number === 'BigNumber') {
math['Infinity'] = new type.BigNumber(Infinity);
math['NaN'] = new type.BigNumber(NaN);
object.lazy(math, 'pi', function () {return bigConstants.pi(type.BigNumber)});
object.lazy(math, 'tau', function () {return bigConstants.tau(type.BigNumber)});
object.lazy(math, 'e', function () {return bigConstants.e(type.BigNumber)});
object.lazy(math, 'phi', function () {return bigConstants.phi(type.BigNumber)}); // golden ratio, (1+sqrt(5))/2
// uppercase constants (for compatibility with built-in Math)
object.lazy(math, 'E', function () {return math.e;});
object.lazy(math, 'LN2', function () {return new type.BigNumber(2).ln();});
object.lazy(math, 'LN10', function () {return new type.BigNumber(10).ln()});
object.lazy(math, 'LOG2E', function () {return new type.BigNumber(1).div(new type.BigNumber(2).ln());});
object.lazy(math, 'LOG10E', function () {return new type.BigNumber(1).div(new type.BigNumber(10).ln())});
object.lazy(math, 'PI', function () {return math.pi});
object.lazy(math, 'SQRT1_2', function () {return new type.BigNumber('0.5').sqrt()});
object.lazy(math, 'SQRT2', function () {return new type.BigNumber(2).sqrt()});
}
else {
math['Infinity'] = Infinity;
math['NaN'] = NaN;
math.pi = Math.PI;
math.tau = Math.PI * 2;
math.e = Math.E;
math.phi = 1.61803398874989484820458683436563811772030917980576286213545; // golden ratio, (1+sqrt(5))/2
// uppercase constants (for compatibility with built-in Math)
math.E = math.e;
math.LN2 = Math.LN2;
math.LN10 = Math.LN10;
math.LOG2E = Math.LOG2E;
math.LOG10E = Math.LOG10E;
math.PI = math.pi;
math.SQRT1_2 = Math.SQRT1_2;
math.SQRT2 = Math.SQRT2;
}
// complex i
math.i = type.Complex.I;
// meta information
math.version = require('./version');
}
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

View File

@@ -0,0 +1,125 @@
var isFactory = require('./../utils/object').isFactory;
var deepExtend = require('./../utils/object').deepExtend;
var typedFactory = require('./typed');
var emitter = require('./../utils/emitter');
var importFactory = require('./function/import');
var configFactory = require('./function/config');
/**
* Math.js core. Creates a new, empty math.js instance
* @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.
* {boolean} predictable
* 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.
* @returns {Object} Returns a bare-bone math.js instance containing
* functions:
* - `import` to add new functions
* - `config` to change configuration
* - `on`, `off`, `once`, `emit` for events
*/
exports.create = 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: Object.create(math)
};
math.algebra = {};
// 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
};
/**
* 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);
// apply options
if (options) {
math.config(options);
}
return math;
};

View File

@@ -0,0 +1,119 @@
'use strict';
var object = require('../../utils/object');
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).
*
* 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.
* @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);
// emit 'config' event
math.emit('config', curr, prev);
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;
}
/**
* Test whether an Array contains a specific item.
* @param {Array.<string>} array
* @param {string} item
* @return {boolean}
*/
function contains (array, item) {
return array.indexOf(item) !== -1;
}
/**
* Find a string in an array. Case insensitive search
* @param {Array.<string>} array
* @param {string} item
* @return {number} Returns the index when found. Returns -1 when not found
*/
function findIndex (array, item) {
return array
.map(function (i) {
return i.toLowerCase();
})
.indexOf(item.toLowerCase());
}
/**
* Validate an option
* @param {Object} options Object with options
* @param {string} name Name of the option to validate
* @param {Array.<string>} values Array with valid values for this option
*/
function validateOption(options, name, values) {
if (options[name] !== undefined && !contains(values, options[name])) {
var index = findIndex(values, options[name]);
if (index !== -1) {
// right value, wrong casing
// TODO: lower case values are deprecated since v3, remove this warning some day.
console.warn('Warning: Wrong casing for configuration option "' + name + '", should be "' + values[index] + '" instead of "' + options[name] + '".');
options[name] = values[index]; // change the option to the right casing
}
else {
// unknown value
console.warn('Warning: Unknown value "' + options[name] + '" for configuration option "' + name + '". Available options: ' + values.map(JSON.stringify).join(', ') + '.');
}
}
}
exports.name = 'config';
exports.math = true; // request the math namespace as fifth argument
exports.factory = factory;

View File

@@ -0,0 +1,266 @@
'use strict';
var lazy = require('../../utils/object').lazy;
var isFactory = require('../../utils/object').isFactory;
var traverse = require('../../utils/object').traverse;
var extend = require('../../utils/object').extend;
var ArgumentsError = require('../../error/ArgumentsError');
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) {
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.transform === 'function') {
math.expression.transform[name] = value.transform;
}
}
/**
* Create a wrapper a round an function which converts the arguments
* to their primitive values (like convert a Matrix to Array)
* @param {Function} fn
* @return {Function} Returns the wrapped function
* @private
*/
function _wrap (fn) {
var wrapper = function wrapper () {
var args = [];
for (var i = 0, len = arguments.length; i < len; i++) {
var arg = arguments[i];
args[i] = arg && arg.valueOf();
}
return fn.apply(math, args);
};
if (fn.transform) {
wrapper.transform = fn.transform;
}
return wrapper;
}
/**
* Import an instance of a factory into math.js
* @param {{factory: Function, name: string, path: string, math: boolean}} factory
* @param {Object} options See import for a description of the options
* @private
*/
function _importFactory(factory, options) {
if (typeof factory.name === 'string') {
var name = factory.name;
var namespace = factory.path ? traverse(math, factory.path) : math;
var existing = namespace.hasOwnProperty(name) ? namespace[name] : undefined;
var resolver = function () {
var instance = load(factory);
if (instance && typeof instance.transform === 'function') {
throw new Error('Transforms cannot be attached to factory functions. ' +
'Please create a separate function for it with exports.path="expression.transform"');
}
if (isTypedFunction(existing) && isTypedFunction(instance)) {
if (options.override) {
// replace the existing typed function (nothing to do)
}
else {
// merge the existing and new typed function
instance = typed(existing, instance);
}
return instance;
}
if (existing === undefined || options.override) {
return instance;
}
if (!options.silent) {
throw new Error('Cannot import "' + name + '": already exists');
}
};
if (factory.lazy !== false) {
lazy(namespace, name, resolver);
}
else {
namespace[name] = resolver();
}
math.emit('import', name, resolver, factory.path);
}
else {
// unnamed factory.
// no lazy loading
load(factory);
}
}
/**
* Check whether given object is a type which can be imported
* @param {Function | number | string | boolean | null | Unit | Complex} object
* @return {boolean}
* @private
*/
function isSupportedType(object) {
return typeof object == 'function'
|| typeof object === 'number'
|| typeof object === 'string'
|| typeof object === 'boolean'
|| object === null
|| (object && object.isUnit === true)
|| (object && object.isComplex === true)
|| (object && object.isBigNumber === true)
|| (object && object.isFraction === true)
|| (object && object.isMatrix === true)
|| (object && Array.isArray(object) === true)
}
/**
* Test whether a given thing is a typed-function
* @param {*} fn
* @return {boolean} Returns true when `fn` is a typed-function
*/
function isTypedFunction (fn) {
return typeof fn === 'function' && typeof fn.signatures === 'object';
}
return math_import;
}
exports.math = true; // request access to the math namespace as 5th argument of the factory function
exports.name = 'import';
exports.factory = factory;
exports.lazy = true;

View File

@@ -0,0 +1,47 @@
'use strict';
// Note: this file is here purely for generation of documentation for `math.typed`
function factory (type, config, load, typed, math) {
/**
* Create a typed-function which checks the types of the arguments and
* can match them against multiple provided signatures. The typed-function
* automatically converts inputs in order to find a matching signature.
* Typed functions throw informative errors in case of wrong input arguments.
*
* See the library [typed-function](https://github.com/josdejong/typed-function)
* for detailed documentation.
*
* Syntax:
*
* math.typed(name, signatures) : function
* math.typed(signatures) : function
*
* Examples:
*
* // create a typed function with multiple types per argument (type union)
* var fn2 = typed({
* 'number | boolean': function (b) {
* return 'b is a number or boolean';
* },
* 'string, number | boolean': function (a, b) {
* return 'a is a string, b is a number or boolean';
* }
* });
*
* // create a typed function with an any type argument
* var log = typed({
* 'string, any': function (event, data) {
* console.log('event: ' + event + ', data: ' + JSON.stringify(data));
* }
* });
*
* @param {string} [name] Optional name for the typed-function
* @param {Object<string, function>} signatures Object with one ore multiple function signatures
* @returns {function} The created typed-function.
*/
return typed;
}
exports.name = 'typed';
exports.factory = factory;

View File

@@ -0,0 +1,236 @@
var typedFunction = require('typed-function');
var digits = require('./../utils/number').digits;
// returns a new instance of typed-function
var createTyped = function () {
// initially, return the original instance of typed-function
// consecutively, return a new instance from typed.create.
createTyped = typedFunction.create;
return typedFunction;
};
/**
* Factory function for creating a new typed instance
* @param {Object} type Object with data types like Complex and BigNumber
* @returns {Function}
*/
exports.create = function create(type) {
// TODO: typed-function must be able to silently ignore signatures with unknown data types
// get a new instance of typed-function
var typed = createTyped();
// define all types. The order of the types determines in which order function
// arguments are type-checked (so for performance it's important to put the
// most used types first).
typed.types = [
{ name: 'number', test: function (x) { return typeof x === 'number' } },
{ name: 'Complex', test: function (x) { return x && x.isComplex } },
{ name: 'BigNumber', test: function (x) { return x && x.isBigNumber } },
{ name: 'Fraction', test: function (x) { return x && x.isFraction } },
{ name: 'Unit', test: function (x) { return x && x.isUnit } },
{ name: 'string', test: function (x) { return typeof x === 'string' } },
{ name: 'Array', test: Array.isArray },
{ name: 'Matrix', test: function (x) { return x && x.isMatrix } },
{ name: 'DenseMatrix', test: function (x) { return x && x.isDenseMatrix } },
{ name: 'SparseMatrix', test: function (x) { return x && x.isSparseMatrix } },
{ name: 'Range', test: function (x) { return x && x.isRange } },
{ name: 'Index', test: function (x) { return x && x.isIndex } },
{ name: 'boolean', test: function (x) { return typeof x === 'boolean' } },
{ name: 'ResultSet', test: function (x) { return x && x.isResultSet } },
{ name: 'Help', test: function (x) { return x && x.isHelp } },
{ name: 'function', test: function (x) { return typeof x === 'function'} },
{ name: 'Date', test: function (x) { return x instanceof Date } },
{ name: 'RegExp', test: function (x) { return x instanceof RegExp } },
{ name: 'Object', test: function (x) { return typeof x === 'object' } },
{ name: 'null', test: function (x) { return x === null } },
{ name: 'undefined', test: function (x) { return x === undefined } },
{ name: 'OperatorNode', test: function (x) { return x && x.isOperatorNode } },
{ name: 'ConstantNode', test: function (x) { return x && x.isConstantNode } },
{ name: 'SymbolNode', test: function (x) { return x && x.isSymbolNode } },
{ name: 'ParenthesisNode', test: function (x) { return x && x.isParenthesisNode } },
{ name: 'FunctionNode', test: function (x) { return x && x.isFunctionNode } },
{ name: 'FunctionAssignmentNode', test: function (x) { return x && x.isFunctionAssignmentNode } },
{ name: 'ArrayNode', test: function (x) { return x && x.isArrayNode } },
{ name: 'AssignmentNode', test: function (x) { return x && x.isAssignmentNode } },
{ name: 'BlockNode', test: function (x) { return x && x.isBlockNode } },
{ name: 'ConditionalNode', test: function (x) { return x && x.isConditionalNode } },
{ name: 'IndexNode', test: function (x) { return x && x.isIndexNode } },
{ name: 'RangeNode', test: function (x) { return x && x.isRangeNode } },
{ name: 'UpdateNode', test: function (x) { return x && x.isUpdateNode } },
{ name: 'Node', test: function (x) { return x && x.isNode } }
];
// TODO: add conversion from BigNumber to number?
typed.conversions = [
{
from: 'number',
to: 'BigNumber',
convert: function (x) {
// note: conversion from number to BigNumber can fail if x has >15 digits
if (digits(x) > 15) {
throw new TypeError('Cannot implicitly convert a number with >15 significant digits to BigNumber ' +
'(value: ' + x + '). ' +
'Use function bignumber(x) to convert to BigNumber.');
}
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 + '';
}
}, {
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.');
}
}, {
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 ' +
'(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();
// }
//}, {
from: 'string',
to: 'number',
convert: function (x) {
var n = Number(x);
if (isNaN(n)) {
throw new Error('Cannot convert "' + x + '" to a number');
}
return n;
}
}, {
from: 'string',
to: 'BigNumber',
convert: function (x) {
try {
return new type.BigNumber(x);
}
catch (err) {
throw new Error('Cannot convert "' + x + '" to BigNumber');
}
}
}, {
from: 'string',
to: 'Fraction',
convert: function (x) {
try {
return new type.Fraction(x);
}
catch (err) {
throw new Error('Cannot convert "' + x + '" to Fraction');
}
}
}, {
from: 'string',
to: 'Complex',
convert: function (x) {
try {
return new type.Complex(x);
}
catch (err) {
throw new Error('Cannot convert "' + x + '" to Complex');
}
}
}, {
from: 'boolean',
to: 'number',
convert: function (x) {
return +x;
}
}, {
from: 'boolean',
to: 'BigNumber',
convert: function (x) {
return new type.BigNumber(+x);
}
}, {
from: 'boolean',
to: 'Fraction',
convert: function (x) {
return new type.Fraction(+x);
}
}, {
from: 'boolean',
to: 'string',
convert: function (x) {
return +x;
}
}, {
from: 'null',
to: 'number',
convert: function () {
return 0;
}
}, {
from: 'null',
to: 'string',
convert: function () {
return 'null';
}
}, {
from: 'null',
to: 'BigNumber',
convert: function () {
return new type.BigNumber(0);
}
}, {
from: 'null',
to: 'Fraction',
convert: function () {
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();
}
}
];
return typed;
};

View File

@@ -0,0 +1,34 @@
'use strict';
/**
* Create a syntax error with the message:
* 'Wrong number of arguments in function <fn> (<count> provided, <min>-<max> expected)'
* @param {string} fn Function name
* @param {number} count Actual argument count
* @param {number} min Minimum required argument count
* @param {number} [max] Maximum required argument count
* @extends Error
*/
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;
}
ArgumentsError.prototype = new Error();
ArgumentsError.prototype.constructor = Error;
ArgumentsError.prototype.name = 'ArgumentsError';
ArgumentsError.prototype.isArgumentsError = true;
module.exports = ArgumentsError;

View File

@@ -0,0 +1,35 @@
'use strict';
/**
* Create a range error with the message:
* 'Dimension mismatch (<actual size> != <expected size>)'
* @param {number | number[]} actual The actual size
* @param {number | number[]} expected The expected size
* @param {string} [relation='!='] Optional relation between actual
* and expected size: '!=', '<', etc.
* @extends RangeError
*/
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;
}
DimensionError.prototype = new RangeError();
DimensionError.prototype.constructor = RangeError;
DimensionError.prototype.name = 'DimensionError';
DimensionError.prototype.isDimensionError = true;
module.exports = DimensionError;

View File

@@ -0,0 +1,46 @@
'use strict';
/**
* Create a range error with the message:
* 'Index out of range (index < min)'
* 'Index out of range (index < max)'
*
* @param {number} index The actual index
* @param {number} [min=0] Minimum index (included)
* @param {number} [max] Maximum index (excluded)
* @extends RangeError
*/
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;
}
IndexError.prototype = new RangeError();
IndexError.prototype.constructor = RangeError;
IndexError.prototype.name = 'IndexError';
IndexError.prototype.isIndexError = true;
module.exports = IndexError;

View File

@@ -0,0 +1,30 @@
'use strict';
var ArgumentsError = require('./ArgumentsError');
var DimensionError = require('./DimensionError');
var IndexError = require('./IndexError');
module.exports = [
{
name: 'ArgumentsError', path: 'error',
factory: function () {
return ArgumentsError;
}
},
{
name: 'DimensionError',
path: 'error',
factory: function () {
return DimensionError;
}
},
{
name: 'IndexError',
path: 'error',
factory: function () {
return IndexError;
}
}
];
// TODO: implement an InvalidValueError?

View File

@@ -0,0 +1,117 @@
'use strict';
var object = require('../utils/object');
var string = require('../utils/string');
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;
}
exports.name = 'Help';
exports.path = 'type';
exports.factory = factory;

View File

@@ -0,0 +1,161 @@
'use strict';
var extend = require('../utils/object').extend;
function factory (type, config, load, typed, math) {
var _parse = load(require('./parse'));
/**
* @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 this.scope[name];
};
/**
* Get a map with all defined variables
* @return {Object} values
*/
Parser.prototype.getAll = function () {
return extend({}, this.scope);
};
/**
* Set a symbol (a function or variable) by name from the parsers scope.
* @param {string} name
* @param {* | undefined} value
*/
Parser.prototype.set = function (name, value) {
// TODO: validate arguments
return this.scope[name] = value;
};
/**
* Remove a variable from the parsers scope
* @param {string} name
*/
Parser.prototype.remove = function (name) {
// TODO: validate arguments
delete this.scope[name];
};
/**
* Clear the scope with variables and functions
*/
Parser.prototype.clear = function () {
for (var name in this.scope) {
if (this.scope.hasOwnProperty(name)) {
delete this.scope[name];
}
}
};
return Parser;
}
exports.name = 'Parser';
exports.path = 'expression';
exports.factory = factory;
exports.math = true; // requires the math namespace as 5th argument

View File

@@ -0,0 +1,13 @@
module.exports = {
'name': 'Infinity',
'category': 'Constants',
'syntax': [
'Infinity'
],
'description': 'Infinity, a number which is larger than the maximum number that can be handled by a floating point number.',
'examples': [
'Infinity',
'1 / 0'
],
'seealso': []
};

View File

@@ -0,0 +1,13 @@
module.exports = {
'name': 'LN10',
'category': 'Constants',
'syntax': [
'LN10'
],
'description': 'Returns the natural logarithm of 10, approximately equal to 2.302',
'examples': [
'LN10',
'log(10)'
],
'seealso': []
};

View File

@@ -0,0 +1,13 @@
module.exports = {
'name': 'LN2',
'category': 'Constants',
'syntax': [
'LN2'
],
'description': 'Returns the natural logarithm of 2, approximately equal to 0.693',
'examples': [
'LN2',
'log(2)'
],
'seealso': []
};

View File

@@ -0,0 +1,13 @@
module.exports = {
'name': 'LOG10E',
'category': 'Constants',
'syntax': [
'LOG10E'
],
'description': 'Returns the base-10 logarithm of E, approximately equal to 0.434',
'examples': [
'LOG10E',
'log(e, 10)'
],
'seealso': []
};

View File

@@ -0,0 +1,13 @@
module.exports = {
'name': 'LOG2E',
'category': 'Constants',
'syntax': [
'LOG2E'
],
'description': 'Returns the base-2 logarithm of E, approximately equal to 1.442',
'examples': [
'LOG2E',
'log(e, 2)'
],
'seealso': []
};

View File

@@ -0,0 +1,13 @@
module.exports = {
'name': 'NaN',
'category': 'Constants',
'syntax': [
'NaN'
],
'description': 'Not a number',
'examples': [
'NaN',
'0 / 0'
],
'seealso': []
};

View File

@@ -0,0 +1,13 @@
module.exports = {
'name': 'SQRT1_2',
'category': 'Constants',
'syntax': [
'SQRT1_2'
],
'description': 'Returns the square root of 1/2, approximately equal to 0.707',
'examples': [
'SQRT1_2',
'sqrt(1/2)'
],
'seealso': []
};

View File

@@ -0,0 +1,13 @@
module.exports = {
'name': 'SQRT2',
'category': 'Constants',
'syntax': [
'SQRT2'
],
'description': 'Returns the square root of 2, approximately equal to 1.414',
'examples': [
'SQRT2',
'sqrt(2)'
],
'seealso': []
};

View File

@@ -0,0 +1,15 @@
module.exports = {
'name': 'e',
'category': 'Constants',
'syntax': [
'e'
],
'description': 'Euler\'s number, the base of the natural logarithm. Approximately equal to 2.71828',
'examples': [
'e',
'e ^ 2',
'exp(2)',
'log(e)'
],
'seealso': ['exp']
};

View File

@@ -0,0 +1,12 @@
module.exports = {
'name': 'false',
'category': 'Constants',
'syntax': [
'false'
],
'description': 'Boolean value false',
'examples': [
'false'
],
'seealso': ['true']
};

View File

@@ -0,0 +1,14 @@
module.exports = {
'name': 'i',
'category': 'Constants',
'syntax': [
'i'
],
'description': 'Imaginary unit, defined as i*i=-1. A complex number is described as a + b*i, where a is the real part, and b is the imaginary part.',
'examples': [
'i',
'i * i',
'sqrt(-1)'
],
'seealso': []
};

View File

@@ -0,0 +1,12 @@
module.exports = {
'name': 'null',
'category': 'Constants',
'syntax': [
'null'
],
'description': 'Value null',
'examples': [
'null'
],
'seealso': ['true', 'false']
};

View File

@@ -0,0 +1,12 @@
module.exports = {
'name': 'phi',
'category': 'Constants',
'syntax': [
'phi'
],
'description': 'Phi is the golden ratio. Two quantities are in the golden ratio if their ratio is the same as the ratio of their sum to the larger of the two quantities. Phi is defined as `(1 + sqrt(5)) / 2` and is approximately 1.618034...',
'examples': [
'tau'
],
'seealso': []
};

View File

@@ -0,0 +1,13 @@
module.exports = {
'name': 'pi',
'category': 'Constants',
'syntax': [
'pi'
],
'description': 'The number pi is a mathematical constant that is the ratio of a circle\'s circumference to its diameter, and is approximately equal to 3.14159',
'examples': [
'pi',
'sin(pi/2)'
],
'seealso': ['tau']
};

View File

@@ -0,0 +1,13 @@
module.exports = {
'name': 'tau',
'category': 'Constants',
'syntax': [
'tau'
],
'description': 'Tau is the ratio constant of a circle\'s circumference to radius, equal to 2 * pi, approximately 6.2832.',
'examples': [
'tau',
'2 * pi'
],
'seealso': ['pi']
};

View File

@@ -0,0 +1,12 @@
module.exports = {
'name': 'true',
'category': 'Constants',
'syntax': [
'true'
],
'description': 'Boolean value true',
'examples': [
'true'
],
'seealso': ['false']
};

View File

@@ -0,0 +1,12 @@
module.exports = {
'name': 'version',
'category': 'Constants',
'syntax': [
'version'
],
'description': 'A string with the version number of math.js',
'examples': [
'version'
],
'seealso': []
};

View File

@@ -0,0 +1,19 @@
module.exports = {
'name': 'bignumber',
'category': 'Construction',
'syntax': [
'bignumber(x)'
],
'description':
'Create a big number from a number or string.',
'examples': [
'0.1 + 0.2',
'bignumber(0.1) + bignumber(0.2)',
'bignumber("7.2")',
'bignumber("7.2e500")',
'bignumber([0.1, 0.2, 0.3])'
],
'seealso': [
'boolean', 'complex', 'fraction', 'index', 'matrix', 'string', 'unit'
]
};

View File

@@ -0,0 +1,21 @@
module.exports = {
'name': 'boolean',
'category': 'Construction',
'syntax': [
'x',
'boolean(x)'
],
'description':
'Convert a string or number into a boolean.',
'examples': [
'boolean(0)',
'boolean(1)',
'boolean(3)',
'boolean("true")',
'boolean("false")',
'boolean([1, 0, 1, 1])'
],
'seealso': [
'bignumber', 'complex', 'index', 'matrix', 'number', 'string', 'unit'
]
};

View File

@@ -0,0 +1,19 @@
module.exports = {
'name': 'complex',
'category': 'Construction',
'syntax': [
'complex()',
'complex(re, im)',
'complex(string)'
],
'description':
'Create a complex number.',
'examples': [
'complex()',
'complex(2, 3)',
'complex("7 - 2i")'
],
'seealso': [
'bignumber', 'boolean', 'index', 'matrix', 'number', 'string', 'unit'
]
};

View File

@@ -0,0 +1,18 @@
module.exports = {
'name': 'createUnit',
'category': 'Construction',
'syntax': [
'createUnit(definitions)',
'createUnit(name, definition)'
],
'description':
'Create a user-defined unit and register it with the Unit type.',
'examples': [
'createUnit("foo")',
'createUnit("knot", {definition: "0.514444444 m/s", aliases: ["knots", "kt", "kts"]})',
'createUnit("mph", "1 mile/hour")'
],
'seealso': [
'unit', 'splitUnit'
]
};

View File

@@ -0,0 +1,17 @@
module.exports = {
'name': 'fraction',
'category': 'Construction',
'syntax': [
'fraction(num)',
'fraction(num,den)'
],
'description':
'Create a fraction from a number or from a numerator and denominator.',
'examples': [
'fraction(0.125)',
'fraction(1, 3) + fraction(2, 5)'
],
'seealso': [
'bignumber', 'boolean', 'complex', 'index', 'matrix', 'string', 'unit'
]
};

View File

@@ -0,0 +1,25 @@
module.exports = {
'name': 'index',
'category': 'Construction',
'syntax': [
'[start]',
'[start:end]',
'[start:step:end]',
'[start1, start 2, ...]',
'[start1:end1, start2:end2, ...]',
'[start1:step1:end1, start2:step2:end2, ...]'
],
'description':
'Create an index to get or replace a subset of a matrix',
'examples': [
'[]',
'[1, 2, 3]',
'A = [1, 2, 3; 4, 5, 6]',
'A[1, :]',
'A[1, 2] = 50',
'A[0:2, 0:2] = ones(2, 2)'
],
'seealso': [
'bignumber', 'boolean', 'complex', 'matrix,', 'number', 'range', 'string', 'unit'
]
};

View File

@@ -0,0 +1,25 @@
module.exports = {
'name': 'matrix',
'category': 'Construction',
'syntax': [
'[]',
'[a1, b1, ...; a2, b2, ...]',
'matrix()',
'matrix("dense")',
'matrix([...])'
],
'description':
'Create a matrix.',
'examples': [
'[]',
'[1, 2, 3]',
'[1, 2, 3; 4, 5, 6]',
'matrix()',
'matrix([3, 4])',
'matrix([3, 4; 5, 6], "sparse")',
'matrix([3, 4; 5, 6], "sparse", "number")'
],
'seealso': [
'bignumber', 'boolean', 'complex', 'index', 'number', 'string', 'unit', 'sparse'
]
};

View File

@@ -0,0 +1,23 @@
module.exports = {
'name': 'number',
'category': 'Construction',
'syntax': [
'x',
'number(x)'
],
'description':
'Create a number or convert a string or boolean into a number.',
'examples': [
'2',
'2e3',
'4.05',
'number(2)',
'number("7.2")',
'number(true)',
'number([true, false, true, true])',
'number("52cm", "m")'
],
'seealso': [
'bignumber', 'boolean', 'complex', 'fraction', 'index', 'matrix', 'string', 'unit'
]
};

View File

@@ -0,0 +1,19 @@
module.exports = {
'name': 'sparse',
'category': 'Construction',
'syntax': [
'sparse()',
'sparse([a1, b1, ...; a1, b2, ...])',
'sparse([a1, b1, ...; a1, b2, ...], "number")'
],
'description':
'Create a sparse matrix.',
'examples': [
'sparse()',
'sparse([3, 4; 5, 6])',
'sparse([3, 0; 5, 0], "number")'
],
'seealso': [
'bignumber', 'boolean', 'complex', 'index', 'number', 'string', 'unit', 'matrix'
]
};

View File

@@ -0,0 +1,15 @@
module.exports = {
'name': 'splitUnit',
'category': 'Construction',
'syntax': [
'splitUnit(unit: Unit, parts: Unit[])'
],
'description':
'Split a unit in an array of units whose sum is equal to the original unit.',
'examples': [
'splitUnit(1 m, ["feet", "inch"])'
],
'seealso': [
'unit', 'createUnit'
]
};

View File

@@ -0,0 +1,18 @@
module.exports = {
'name': 'string',
'category': 'Construction',
'syntax': [
'"text"',
'string(x)'
],
'description':
'Create a string or convert a value to a string',
'examples': [
'"Hello World!"',
'string(4.2)',
'string(3 + 2i)'
],
'seealso': [
'bignumber', 'boolean', 'complex', 'index', 'matrix', 'number', 'unit'
]
};

View File

@@ -0,0 +1,20 @@
module.exports = {
'name': 'unit',
'category': 'Construction',
'syntax': [
'value unit',
'unit(value, unit)',
'unit(string)'
],
'description':
'Create a unit.',
'examples': [
'5.5 mm',
'3 inch',
'unit(7.1, "kilogram")',
'unit("23 deg")'
],
'seealso': [
'bignumber', 'boolean', 'complex', 'index', 'matrix', 'number', 'string'
]
};

View File

@@ -0,0 +1,16 @@
module.exports = {
'name': 'config',
'category': 'Core',
'syntax': [
'config()',
'config(options)'
],
'description': 'Get configuration or change configuration.',
'examples': [
'config()',
'1/3 + 1/4',
'config({number: "Fraction"})',
'1/3 + 1/4'
],
'seealso': []
};

View File

@@ -0,0 +1,15 @@
module.exports = {
'name': 'import',
'category': 'Core',
'syntax': [
'import(functions)',
'import(functions, options)'
],
'description': 'Import functions or constants from an object.',
'examples': [
'import({myFn: f(x)=x^2, myConstant: 32 })',
'myFn(2)',
'myConstant'
],
'seealso': []
};

View File

@@ -0,0 +1,15 @@
module.exports = {
'name': 'typed',
'category': 'Core',
'syntax': [
'typed(signatures)',
'typed(name, signatures)'
],
'description': 'Create a typed function.',
'examples': [
'double = typed({ "number, number": f(x)=x+x })',
'double(2)',
'double("hello")'
],
'seealso': []
};

View File

@@ -0,0 +1,22 @@
module.exports = {
'name': 'derivative',
'category': 'Algebra',
'syntax': [
'derivative(expr)',
'derivative(expr, {simplify: boolean})'
],
'description': 'Takes the derivative of an expression expressed in parser Nodes. The derivative will be taken over the supplied variable in the second parameter. If there are multiple variables in the expression, it will return a partial derivative.',
'examples': [
'derivative("2x^3", "x")',
'derivative("2x^3", "x", {simplify: false})',
'derivative("2x^2 + 3x + 4", "x")',
'derivative("sin(2x)", "x")',
'f = parse("x^2 + x")',
'x = parse("x")',
'df = derivative(f, x)',
'df.eval({x: 3})'
],
'seealso': [
'simplify', 'parse', 'eval'
]
};

View File

@@ -0,0 +1,17 @@
module.exports = {
'name': 'lsolve',
'category': 'Algebra',
'syntax': [
'x=lsolve(L, b)'
],
'description':
'Solves the linear system L * x = b where L is an [n x n] lower triangular matrix and b is a [n] column vector.',
'examples': [
'a = [-2, 3; 2, 1]',
'b = [11, 9]',
'x = lsolve(a, b)'
],
'seealso': [
'lup', 'lusolve', 'usolve', 'matrix', 'sparse'
]
};

View File

@@ -0,0 +1,17 @@
module.exports = {
'name': 'lup',
'category': 'Algebra',
'syntax': [
'lup(m)'
],
'description':
'Calculate the Matrix LU decomposition with partial pivoting. Matrix A is decomposed in three matrices (L, U, P) where P * A = L * U',
'examples': [
'lup([[2, 1], [1, 4]])',
'lup(matrix([[2, 1], [1, 4]]))',
'lup(sparse([[2, 1], [1, 4]]))'
],
'seealso': [
'lusolve', 'lsolve', 'usolve', 'matrix', 'sparse', 'slu'
]
};

View File

@@ -0,0 +1,17 @@
module.exports = {
'name': 'lusolve',
'category': 'Algebra',
'syntax': [
'x=lusolve(A, b)',
'x=lusolve(lu, b)'
],
'description': 'Solves the linear system A * x = b where A is an [n x n] matrix and b is a [n] column vector.',
'examples': [
'a = [-2, 3; 2, 1]',
'b = [11, 9]',
'x = lusolve(a, b)'
],
'seealso': [
'lup', 'slu', 'lsolve', 'usolve', 'matrix', 'sparse'
]
};

View File

@@ -0,0 +1,19 @@
module.exports = {
'name': 'simplify',
'category': 'Algebra',
'syntax': [
'simplify(expr)',
'simplify(expr, rules)'
],
'description': 'Simplify an expression tree.',
'examples': [
'simplify("3 + 2 / 4")',
'simplify("2x + x")',
'f = parse("x * (x + 2 + x)")',
'simplified = simplify(f)',
'simplified.eval({x: 2})'
],
'seealso': [
'derivative', 'parse', 'eval'
]
};

View File

@@ -0,0 +1,14 @@
module.exports = {
'name': 'slu',
'category': 'Algebra',
'syntax': [
'slu(A, order, threshold)'
],
'description': 'Calculate the Matrix LU decomposition with full pivoting. Matrix A is decomposed in two matrices (L, U) and two permutation vectors (pinv, q) where P * A * Q = L * U',
'examples': [
'slu(sparse([4.5, 0, 3.2, 0; 3.1, 2.9, 0, 0.9; 0, 1.7, 3, 0; 3.5, 0.4, 0, 1]), 1, 0.001)'
],
'seealso': [
'lusolve', 'lsolve', 'usolve', 'matrix', 'sparse', 'lup'
]
};

View File

@@ -0,0 +1,15 @@
module.exports = {
'name': 'usolve',
'category': 'Algebra',
'syntax': [
'x=usolve(U, b)'
],
'description':
'Solves the linear system U * x = b where U is an [n x n] upper triangular matrix and b is a [n] column vector.',
'examples': [
'x=usolve(sparse([1, 1, 1, 1; 0, 1, 1, 1; 0, 0, 1, 1; 0, 0, 0, 1]), [1; 2; 3; 4])'
],
'seealso': [
'lup', 'lusolve', 'lsolve', 'matrix', 'sparse'
]
};

View File

@@ -0,0 +1,13 @@
module.exports = {
'name': 'abs',
'category': 'Arithmetic',
'syntax': [
'abs(x)'
],
'description': 'Compute the absolute value.',
'examples': [
'abs(3.5)',
'abs(-4.2)'
],
'seealso': ['sign']
};

View File

@@ -0,0 +1,19 @@
module.exports = {
'name': 'add',
'category': 'Operators',
'syntax': [
'x + y',
'add(x, y)'
],
'description': 'Add two values.',
'examples': [
'a = 2.1 + 3.6',
'a - 3.6',
'3 + 2i',
'3 cm + 2 inch',
'"2.3" + "4"'
],
'seealso': [
'subtract'
]
};

View File

@@ -0,0 +1,25 @@
module.exports = {
'name': 'cbrt',
'category': 'Arithmetic',
'syntax': [
'cbrt(x)',
'cbrt(x, allRoots)'
],
'description':
'Compute the cubic root value. If x = y * y * y, then y is the cubic root of x. When `x` is a number or complex number, an optional second argument `allRoots` can be provided to return all three cubic roots. If not provided, the principal root is returned',
'examples': [
'cbrt(64)',
'cube(4)',
'cbrt(-8)',
'cbrt(2 + 3i)',
'cbrt(8i)',
'cbrt(8i, true)',
'cbrt(27 m^3)'
],
'seealso': [
'square',
'sqrt',
'cube',
'multiply'
]
};

View File

@@ -0,0 +1,15 @@
module.exports = {
'name': 'ceil',
'category': 'Arithmetic',
'syntax': [
'ceil(x)'
],
'description':
'Round a value towards plus infinity. If x is complex, both real and imaginary part are rounded towards plus infinity.',
'examples': [
'ceil(3.2)',
'ceil(3.8)',
'ceil(-4.2)'
],
'seealso': ['floor', 'fix', 'round']
};

View File

@@ -0,0 +1,18 @@
module.exports = {
'name': 'cube',
'category': 'Arithmetic',
'syntax': [
'cube(x)'
],
'description': 'Compute the cube of a value. The cube of x is x * x * x.',
'examples': [
'cube(2)',
'2^3',
'2 * 2 * 2'
],
'seealso': [
'multiply',
'square',
'pow'
]
};

View File

@@ -0,0 +1,20 @@
module.exports = {
'name': 'divide',
'category': 'Operators',
'syntax': [
'x / y',
'divide(x, y)'
],
'description': 'Divide two values.',
'examples': [
'a = 2 / 3',
'a * 3',
'4.5 / 2',
'3 + 4 / 2',
'(3 + 4) / 2',
'18 km / 4.5'
],
'seealso': [
'multiply'
]
};

View File

@@ -0,0 +1,19 @@
module.exports = {
'name': 'dotDivide',
'category': 'Operators',
'syntax': [
'x ./ y',
'dotDivide(x, y)'
],
'description': 'Divide two values element wise.',
'examples': [
'a = [1, 2, 3; 4, 5, 6]',
'b = [2, 1, 1; 3, 2, 5]',
'a ./ b'
],
'seealso': [
'multiply',
'dotMultiply',
'divide'
]
};

View File

@@ -0,0 +1,19 @@
module.exports = {
'name': 'dotMultiply',
'category': 'Operators',
'syntax': [
'x .* y',
'dotMultiply(x, y)'
],
'description': 'Multiply two values element wise.',
'examples': [
'a = [1, 2, 3; 4, 5, 6]',
'b = [2, 1, 1; 3, 2, 5]',
'a .* b'
],
'seealso': [
'multiply',
'divide',
'dotDivide'
]
};

View File

@@ -0,0 +1,17 @@
module.exports = {
'name': 'dotpow',
'category': 'Operators',
'syntax': [
'x .^ y',
'dotpow(x, y)'
],
'description':
'Calculates the power of x to y element wise.',
'examples': [
'a = [1, 2, 3; 4, 5, 6]',
'a .^ 2'
],
'seealso': [
'pow'
]
};

View File

@@ -0,0 +1,19 @@
module.exports = {
'name': 'exp',
'category': 'Arithmetic',
'syntax': [
'exp(x)'
],
'description': 'Calculate the exponent of a value.',
'examples': [
'exp(1.3)',
'e ^ 1.3',
'log(exp(1.3))',
'x = 2.4',
'(exp(i*x) == cos(x) + i*sin(x)) # Euler\'s formula'
],
'seealso': [
'pow',
'log'
]
};

View File

@@ -0,0 +1,16 @@
module.exports = {
'name': 'fix',
'category': 'Arithmetic',
'syntax': [
'fix(x)'
],
'description':
'Round a value towards zero. If x is complex, both real and imaginary part are rounded towards zero.',
'examples': [
'fix(3.2)',
'fix(3.8)',
'fix(-4.2)',
'fix(-4.8)'
],
'seealso': ['ceil', 'floor', 'round']
};

View File

@@ -0,0 +1,15 @@
module.exports = {
'name': 'floor',
'category': 'Arithmetic',
'syntax': [
'floor(x)'
],
'description':
'Round a value towards minus infinity.If x is complex, both real and imaginary part are rounded towards minus infinity.',
'examples': [
'floor(3.2)',
'floor(3.8)',
'floor(-4.2)'
],
'seealso': ['ceil', 'fix', 'round']
};

View File

@@ -0,0 +1,15 @@
module.exports = {
'name': 'gcd',
'category': 'Arithmetic',
'syntax': [
'gcd(a, b)',
'gcd(a, b, c, ...)'
],
'description': 'Compute the greatest common divisor.',
'examples': [
'gcd(8, 12)',
'gcd(-4, 6)',
'gcd(25, 15, -10)'
],
'seealso': [ 'lcm', 'xgcd' ]
};

View File

@@ -0,0 +1,16 @@
module.exports = {
'name': 'hypot',
'category': 'Arithmetic',
'syntax': [
'hypot(a, b, c, ...)',
'hypot([a, b, c, ...])'
],
'description': 'Calculate the hypotenusa of a list with values. ',
'examples': [
'hypot(3, 4)',
'sqrt(3^2 + 4^2)',
'hypot(-2)',
'hypot([3, 4, 5])'
],
'seealso': [ 'abs', 'norm' ]
};

View File

@@ -0,0 +1,14 @@
module.exports = {
'name': 'lcm',
'category': 'Arithmetic',
'syntax': [
'lcm(x, y)'
],
'description': 'Compute the least common multiple.',
'examples': [
'lcm(4, 6)',
'lcm(6, 21)',
'lcm(6, 21, 5)'
],
'seealso': [ 'gcd' ]
};

View File

@@ -0,0 +1,23 @@
module.exports = {
'name': 'log',
'category': 'Arithmetic',
'syntax': [
'log(x)',
'log(x, base)'
],
'description': 'Compute the logarithm of a value. If no base is provided, the natural logarithm of x is calculated. If base if provided, the logarithm is calculated for the specified base. log(x, base) is defined as log(x) / log(base).',
'examples': [
'log(3.5)',
'a = log(2.4)',
'exp(a)',
'10 ^ 4',
'log(10000, 10)',
'log(10000) / log(10)',
'b = log(1024, 2)',
'2 ^ b'
],
'seealso': [
'exp',
'log10'
]
};

View File

@@ -0,0 +1,19 @@
module.exports = {
'name': 'log10',
'category': 'Arithmetic',
'syntax': [
'log10(x)'
],
'description': 'Compute the 10-base logarithm of a value.',
'examples': [
'log10(0.00001)',
'log10(10000)',
'10 ^ 4',
'log(10000) / log(10)',
'log(10000, 10)'
],
'seealso': [
'exp',
'log'
]
};

View File

@@ -0,0 +1,20 @@
module.exports = {
'name': 'mod',
'category': 'Operators',
'syntax': [
'x % y',
'x mod y',
'mod(x, y)'
],
'description':
'Calculates the modulus, the remainder of an integer division.',
'examples': [
'7 % 3',
'11 % 2',
'10 mod 4',
'function isOdd(x) = x % 2',
'isOdd(2)',
'isOdd(3)'
],
'seealso': ['divide']
};

View File

@@ -0,0 +1,19 @@
module.exports = {
'name': 'multiply',
'category': 'Operators',
'syntax': [
'x * y',
'multiply(x, y)'
],
'description': 'multiply two values.',
'examples': [
'a = 2.1 * 3.4',
'a / 3.4',
'2 * 3 + 4',
'2 * (3 + 4)',
'3 * 2.1 km'
],
'seealso': [
'divide'
]
};

View File

@@ -0,0 +1,20 @@
module.exports = {
'name': 'norm',
'category': 'Arithmetic',
'syntax': [
'norm(x)',
'norm(x, p)'
],
'description': 'Calculate the norm of a number, vector or matrix.',
'examples': [
'abs(-3.5)',
'norm(-3.5)',
'norm(3 - 4i))',
'norm([1, 2, -3], Infinity)',
'norm([1, 2, -3], -Infinity)',
'norm([3, 4], 2)',
'norm([[1, 2], [3, 4]], 1)',
'norm([[1, 2], [3, 4]], \'inf\')',
'norm([[1, 2], [3, 4]], \'fro\')'
]
};

View File

@@ -0,0 +1,21 @@
module.exports = {
'name': 'nthRoot',
'category': 'Arithmetic',
'syntax': [
'nthRoot(a)',
'nthRoot(a, root)'
],
'description': '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".',
'examples': [
'4 ^ 3',
'nthRoot(64, 3)',
'nthRoot(9, 2)',
'sqrt(9)'
],
'seealso': [
'sqrt',
'pow'
]
};

View File

@@ -0,0 +1,16 @@
module.exports = {
'name': 'pow',
'category': 'Operators',
'syntax': [
'x ^ y',
'pow(x, y)'
],
'description':
'Calculates the power of x to y, x^y.',
'examples': [
'2^3 = 8',
'2*2*2',
'1 + e ^ (pi * i)'
],
'seealso': [ 'multiply' ]
};

View File

@@ -0,0 +1,19 @@
module.exports = {
'name': 'round',
'category': 'Arithmetic',
'syntax': [
'round(x)',
'round(x, n)'
],
'description':
'round a value towards the nearest integer.If x is complex, both real and imaginary part are rounded towards the nearest integer. When n is specified, the value is rounded to n decimals.',
'examples': [
'round(3.2)',
'round(3.8)',
'round(-4.2)',
'round(-4.8)',
'round(pi, 3)',
'round(123.45678, 2)'
],
'seealso': ['ceil', 'floor', 'fix']
};

View File

@@ -0,0 +1,17 @@
module.exports = {
'name': 'sign',
'category': 'Arithmetic',
'syntax': [
'sign(x)'
],
'description':
'Compute the sign of a value. The sign of a value x is 1 when x>1, -1 when x<0, and 0 when x=0.',
'examples': [
'sign(3.5)',
'sign(-4.2)',
'sign(0)'
],
'seealso': [
'abs'
]
};

View File

@@ -0,0 +1,18 @@
module.exports = {
'name': 'sqrt',
'category': 'Arithmetic',
'syntax': [
'sqrt(x)'
],
'description':
'Compute the square root value. If x = y * y, then y is the square root of x.',
'examples': [
'sqrt(25)',
'5 * 5',
'sqrt(-1)'
],
'seealso': [
'square',
'multiply'
]
};

View File

@@ -0,0 +1,21 @@
module.exports = {
'name': 'square',
'category': 'Arithmetic',
'syntax': [
'square(x)'
],
'description':
'Compute the square of a value. The square of x is x * x.',
'examples': [
'square(3)',
'sqrt(9)',
'3^2',
'3 * 3'
],
'seealso': [
'multiply',
'pow',
'sqrt',
'cube'
]
};

View File

@@ -0,0 +1,19 @@
module.exports = {
'name': 'subtract',
'category': 'Operators',
'syntax': [
'x - y',
'subtract(x, y)'
],
'description': 'subtract two values.',
'examples': [
'a = 5.3 - 2',
'a + 2',
'2/3 - 1/6',
'2 * 3 - 3',
'2.1 km - 500m'
],
'seealso': [
'add'
]
};

View File

@@ -0,0 +1,18 @@
module.exports = {
'name': 'unaryMinus',
'category': 'Operators',
'syntax': [
'-x',
'unaryMinus(x)'
],
'description':
'Inverse the sign of a value. Converts booleans and strings to numbers.',
'examples': [
'-4.5',
'-(-5.6)',
'-"22"'
],
'seealso': [
'add', 'subtract', 'unaryPlus'
]
};

View File

@@ -0,0 +1,17 @@
module.exports = {
'name': 'unaryPlus',
'category': 'Operators',
'syntax': [
'+x',
'unaryPlus(x)'
],
'description':
'Converts booleans and strings to numbers.',
'examples': [
'+true',
'+"2"'
],
'seealso': [
'add', 'subtract', 'unaryMinus'
]
};

View File

@@ -0,0 +1,14 @@
module.exports = {
'name': 'xgcd',
'category': 'Arithmetic',
'syntax': [
'xgcd(a, b)'
],
'description': 'Calculate the extended greatest common divisor for two values',
'examples': [
'xgcd(8, 12)',
'gcd(8, 12)',
'xgcd(36163, 21199)'
],
'seealso': [ 'gcd', 'lcm' ]
};

View File

@@ -0,0 +1,17 @@
module.exports = {
'name': 'bitAnd',
'category': 'Bitwise',
'syntax': [
'x & y',
'bitAnd(x, y)'
],
'description': 'Bitwise AND operation. Performs the logical AND operation on each pair of the corresponding bits of the two given values by multiplying them. If both bits in the compared position are 1, the bit in the resulting binary representation is 1, otherwise, the result is 0',
'examples': [
'5 & 3',
'bitAnd(53, 131)',
'[1, 12, 31] & 42'
],
'seealso': [
'bitNot', 'bitOr', 'bitXor', 'leftShift', 'rightArithShift', 'rightLogShift'
]
};

View File

@@ -0,0 +1,17 @@
module.exports = {
'name': 'bitNot',
'category': 'Bitwise',
'syntax': [
'~x',
'bitNot(x)'
],
'description': 'Bitwise NOT operation. Performs a logical negation on each bit of the given value. Bits that are 0 become 1, and those that are 1 become 0.',
'examples': [
'~1',
'~2',
'bitNot([2, -3, 4])'
],
'seealso': [
'bitAnd', 'bitOr', 'bitXor', 'leftShift', 'rightArithShift', 'rightLogShift'
]
};

View File

@@ -0,0 +1,16 @@
module.exports = {
'name': 'bitOr',
'category': 'Bitwise',
'syntax': [
'x | y',
'bitOr(x, y)'
],
'description': 'Bitwise OR operation. Performs the logical inclusive OR operation on each pair of corresponding bits of the two given values. The result in each position is 1 if the first bit is 1 or the second bit is 1 or both bits are 1, otherwise, the result is 0.',
'examples': [
'5 | 3',
'bitOr([1, 2, 3], 4)'
],
'seealso': [
'bitAnd', 'bitNot', 'bitXor', 'leftShift', 'rightArithShift', 'rightLogShift'
]
};

View File

@@ -0,0 +1,15 @@
module.exports = {
'name': 'bitXor',
'category': 'Bitwise',
'syntax': [
'bitXor(x, y)'
],
'description': 'Bitwise XOR operation, exclusive OR. Performs the logical exclusive OR operation on each pair of corresponding bits of the two given values. The result in each position is 1 if only the first bit is 1 or only the second bit is 1, but will be 0 if both are 0 or both are 1.',
'examples': [
'bitOr(1, 2)',
'bitXor([2, 3, 4], 4)'
],
'seealso': [
'bitAnd', 'bitNot', 'bitOr', 'leftShift', 'rightArithShift', 'rightLogShift'
]
};

View File

@@ -0,0 +1,16 @@
module.exports = {
'name': 'leftShift',
'category': 'Bitwise',
'syntax': [
'x << y',
'leftShift(x, y)'
],
'description': 'Bitwise left logical shift of a value x by y number of bits.',
'examples': [
'4 << 1',
'8 >> 1'
],
'seealso': [
'bitAnd', 'bitNot', 'bitOr', 'bitXor', 'rightArithShift', 'rightLogShift'
]
};

View File

@@ -0,0 +1,17 @@
module.exports = {
'name': 'rightArithShift',
'category': 'Bitwise',
'syntax': [
'x >> y',
'leftShift(x, y)'
],
'description': 'Bitwise right arithmetic shift of a value x by y number of bits.',
'examples': [
'8 >> 1',
'4 << 1',
'-12 >> 2'
],
'seealso': [
'bitAnd', 'bitNot', 'bitOr', 'bitXor', 'leftShift', 'rightLogShift'
]
};

View File

@@ -0,0 +1,17 @@
module.exports = {
'name': 'rightLogShift',
'category': 'Bitwise',
'syntax': [
'x >> y',
'leftShift(x, y)'
],
'description': 'Bitwise right logical shift of a value x by y number of bits.',
'examples': [
'8 >>> 1',
'4 << 1',
'-12 >>> 2'
],
'seealso': [
'bitAnd', 'bitNot', 'bitOr', 'bitXor', 'leftShift', 'rightArithShift'
]
};

View File

@@ -0,0 +1,13 @@
module.exports = {
'name': 'bellNumbers',
'category': 'Combinatorics',
'syntax': [
'bellNumbers(n)'
],
'description': '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.',
'examples': [
'bellNumbers(3)',
'bellNumbers(8)'
],
'seealso': ['stirlingS2']
};

View File

@@ -0,0 +1,13 @@
module.exports = {
'name': 'catalan',
'category': 'Combinatorics',
'syntax': [
'catalan(n)'
],
'description': 'The Catalan Numbers enumerate combinatorial structures of many different types. catalan only takes integer arguments. The following condition must be enforced: n >= 0.',
'examples': [
'catalan(3)',
'catalan(8)'
],
'seealso': ['bellNumbers']
};

View File

@@ -0,0 +1,12 @@
module.exports = {
'name': 'composition',
'category': 'Combinatorics',
'syntax': [
'composition(n, k)'
],
'description': 'The composition counts of n into k parts. composition only takes integer arguments. The following condition must be enforced: k <= n.',
'examples': [
'composition(5, 3)'
],
'seealso': ['combinations']
};

View File

@@ -0,0 +1,12 @@
module.exports = {
'name': 'stirlingS2',
'category': 'Combinatorics',
'syntax': [
'stirlingS2(n, k)'
],
'description': 'he 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.',
'examples': [
'stirlingS2(5, 3)'
],
'seealso': ['bellNumbers']
};

View File

@@ -0,0 +1,20 @@
module.exports = {
'name': 'arg',
'category': 'Complex',
'syntax': [
'arg(x)'
],
'description':
'Compute the argument of a complex value. If x = a+bi, the argument is computed as atan2(b, a).',
'examples': [
'arg(2 + 2i)',
'atan2(3, 2)',
'arg(2 + 3i)'
],
'seealso': [
're',
'im',
'conj',
'abs'
]
};

View File

@@ -0,0 +1,20 @@
module.exports = {
'name': 'conj',
'category': 'Complex',
'syntax': [
'conj(x)'
],
'description':
'Compute the complex conjugate of a complex value. If x = a+bi, the complex conjugate is a-bi.',
'examples': [
'conj(2 + 3i)',
'conj(2 - 3i)',
'conj(-5.2i)'
],
'seealso': [
're',
'im',
'abs',
'arg'
]
};

View File

@@ -0,0 +1,20 @@
module.exports = {
'name': 'im',
'category': 'Complex',
'syntax': [
'im(x)'
],
'description': 'Get the imaginary part of a complex number.',
'examples': [
'im(2 + 3i)',
're(2 + 3i)',
'im(-5.2i)',
'im(2.4)'
],
'seealso': [
're',
'conj',
'abs',
'arg'
]
};

View File

@@ -0,0 +1,20 @@
module.exports = {
'name': 're',
'category': 'Complex',
'syntax': [
're(x)'
],
'description': 'Get the real part of a complex number.',
'examples': [
're(2 + 3i)',
'im(2 + 3i)',
're(-5.2i)',
're(2.4)'
],
'seealso': [
'im',
'conj',
'abs',
'arg'
]
};

View File

@@ -0,0 +1,14 @@
module.exports = {
'name': 'eval',
'category': 'Expression',
'syntax': [
'eval(expression)',
'eval([expr1, expr2, expr3, ...])'
],
'description': 'Evaluate an expression or an array with expressions.',
'examples': [
'eval("2 + 3")',
'eval("sqrt(" + 4 + ")")'
],
'seealso': []
};

View File

@@ -0,0 +1,14 @@
module.exports = {
'name': 'help',
'category': 'Expression',
'syntax': [
'help(object)',
'help(string)'
],
'description': 'Display documentation on a function or data type.',
'examples': [
'help(sqrt)',
'help("complex")'
],
'seealso': []
};

View File

@@ -0,0 +1,14 @@
module.exports = {
'name': 'distance',
'category': 'Geometry',
'syntax': [
'distance([x1, y1], [x2, y2])',
'distance([[x1, y1], [x2, y2])'
],
'description': 'Calculates the Euclidean distance between two points.',
'examples': [
'distance([0,0], [4,4])',
'distance([[0,0], [4,4]])'
],
'seealso': []
};

View File

@@ -0,0 +1,14 @@
module.exports = {
'name': 'intersect',
'category': 'Geometry',
'syntax': [
'intersect(expr1, expr2, expr3, expr4)',
'intersect(expr1, expr2, expr3)'
],
'description': 'Computes the intersection point of lines and/or planes.',
'examples': [
'intersect([0, 0], [10, 10], [10, 0], [0, 10])',
'intersect([1, 0, 1], [4, -2, 2], [1, 1, 1, 6])'
],
'seealso': []
};

Some files were not shown because too many files have changed in this diff Show More