code
stringlengths
24
2.07M
docstring
stringlengths
25
85.3k
func_name
stringlengths
1
92
language
stringclasses
1 value
repo
stringlengths
5
64
path
stringlengths
4
172
url
stringlengths
44
218
license
stringclasses
7 values
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(val...
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
_import
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _importTransform(name, value) { if (value && typeof value.transform === 'function') { math.expression.transform[name] = value.transform; if (allowedInExpressions(name)) { math.expression.mathWithTransform[name] = value.transform; } } else { // remove existing transform ...
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
_importTransform
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _deleteTransform(name) { delete math.expression.transform[name]; if (allowedInExpressions(name)) { math.expression.mathWithTransform[name] = math[name]; } else { delete math.expression.mathWithTransform[name]; } }
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
_deleteTransform
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _importFactory(factory, options) { if (typeof factory.name === 'string') { var name = factory.name; var existingTransform = name in math.expression.transform; var namespace = factory.path ? traverse(math, factory.path) : math; var existing = namespace.hasOwnProperty(name) ? namespac...
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
_importFactory
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
resolver = function resolver() { 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"'); } ...
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
resolver
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function isSupportedType(object) { return typeof object === 'function' || typeof object === 'number' || typeof object === 'string' || typeof object === 'boolean' || object === null || object && type.isUnit(object) || object && type.isComplex(object) || object && type.isBigNumber(object) || object && type.isFraction...
Check whether given object is a type which can be imported @param {Function | number | string | boolean | null | Unit | Complex} object @return {boolean} @private
isSupportedType
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function isTypedFunction(fn) { return typeof fn === 'function' && _typeof(fn.signatures) === 'object'; }
Test whether a given thing is a typed-function @param {*} fn @return {boolean} Returns true when `fn` is a typed-function
isTypedFunction
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function allowedInExpressions(name) { return !unsafe.hasOwnProperty(name); }
Test whether a given thing is a typed-function @param {*} fn @return {boolean} Returns true when `fn` is a typed-function
allowedInExpressions
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function factoryAllowedInExpressions(factory) { return factory.path === undefined && !unsafe.hasOwnProperty(factory.name); } // namespaces and functions not available in the parser for safety reasons
Test whether a given thing is a typed-function @param {*} fn @return {boolean} Returns true when `fn` is a typed-function
factoryAllowedInExpressions
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function contains(array, item) { return array.indexOf(item) !== -1; }
Test whether an Array contains a specific item. @param {Array.<string>} array @param {string} item @return {boolean}
contains
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function findIndex(array, item) { return array.map(function (i) { return i.toLowerCase(); }).indexOf(item.toLowerCase()); }
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
findIndex
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
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. ...
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
validateOption
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function Chain(value) { if (!(this instanceof Chain)) { throw new SyntaxError('Constructor must be called with the new operator'); } if (type.isChain(value)) { this.value = value.value; } else { this.value = value; } }
@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 fina...
Chain
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
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} fn The function to be proxied If fn is no function, it is silently ignored. @private
createProxy
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
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 }); }
Create a proxy method for the chain @param {string} name @param {function} resolver The function resolving with the function to be proxied @private
createLazyProxy
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
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)); }; }
Make a function chainable @param {function} fn @return {Function} chain function @private
chainify
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
cosh = function(x) { return (Math.exp(x) + Math.exp(-x)) * 0.5; }
This class allows the manipulation of complex numbers. You can pass a complex number in different formats. Either as object, double, string or two integer parameters. Object form { re: <real>, im: <imaginary> } { arg: <angle>, abs: <radius> } { phi: <angle>, r: <radius> } Array / Vector form [ real, imaginary ] Doub...
cosh
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
sinh = function(x) { return (Math.exp(x) - Math.exp(-x)) * 0.5; }
This class allows the manipulation of complex numbers. You can pass a complex number in different formats. Either as object, double, string or two integer parameters. Object form { re: <real>, im: <imaginary> } { arg: <angle>, abs: <radius> } { phi: <angle>, r: <radius> } Array / Vector form [ real, imaginary ] Doub...
sinh
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
cosm1 = function(x) { var limit = Math.PI/4; if (x < -limit || x > limit) { return (Math.cos(x) - 1.0); } var xx = x * x; return xx * (-0.5 + xx * (1/24 + xx * (-1/720 + xx * (1/40320 + xx * (-1/3628800 + xx * (1/4790014600 + x...
Calculates cos(x) - 1 using Taylor series if x is small. @param {number} x @returns {number} cos(x) - 1
cosm1
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
hypot = function(x, y) { var a = Math.abs(x); var b = Math.abs(y); if (a < 3000 && b < 3000) { return Math.sqrt(a * a + b * b); } if (a < b) { a = b; b = x / y; } else { b = y / x; } return a * Math.sqrt(1 + b * b); }
Calculates cos(x) - 1 using Taylor series if x is small. @param {number} x @returns {number} cos(x) - 1
hypot
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
parser_exit = function() { throw SyntaxError('Invalid Param'); }
Calculates cos(x) - 1 using Taylor series if x is small. @param {number} x @returns {number} cos(x) - 1
parser_exit
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
parse = function(a, b) { var z = {'re': 0, 'im': 0}; if (a === undefined || a === null) { z['re'] = z['im'] = 0; } else if (b !== undefined) { z['re'] = a; z['im'] = b; } else switch (typeof a) { case 'object': if ('im' in a && 're' in a) { ...
Calculates log(sqrt(a^2+b^2)) in a way to avoid overflows @param {number} a @param {number} b @returns {number}
parse
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
_loop = function _loop() { var specialCharFound = false; escapeKeys.forEach(function (key, index) { if (specialCharFound) { return; } if (runningStr.length >= key.length && runningStr.slice(0, key.length) === key) { result += escapes[escapeKeys[index]]; runningStr = run...
Escape a string to be used in LaTeX documents. @param {string} str the string to be escaped. @param {boolean} params.preserveFormatting whether formatting escapes should be performed (default: false). @param {function} params.escapeMapFn the function to modify the escape maps. @return {string} the escaped string, read...
_loop
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function factory(type, config, load, typed) { return Fraction; }
Instantiate a Fraction from a JSON object @param {Object} json a JSON object structured as: `{"mathjs": "Fraction", "n": 3, "d": 8}` @return {BigNumber}
factory
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function createError(name) { function errorConstructor() { var temp = Error.apply(this, arguments); temp['name'] = this['name'] = name; this['stack'] = temp['stack']; this['message'] = temp['message']; } /** * Error constructor * * @constructor */ function I...
This class offers the possibility to calculate fractions. You can pass a fraction in different formats. Either as array, as double, as string or as an integer. Array/Object form [ 0 => <nominator>, 1 => <denominator> ] [ n => <nominator>, d => <denominator> ] Integer form - Single integer value Double form - Single ...
createError
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function errorConstructor() { var temp = Error.apply(this, arguments); temp['name'] = this['name'] = name; this['stack'] = temp['stack']; this['message'] = temp['message']; }
This class offers the possibility to calculate fractions. You can pass a fraction in different formats. Either as array, as double, as string or as an integer. Array/Object form [ 0 => <nominator>, 1 => <denominator> ] [ n => <nominator>, d => <denominator> ] Integer form - Single integer value Double form - Single ...
errorConstructor
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
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; }
Module constructor @constructor @param {number|Fraction=} a @param {number=} b
Fraction
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function rec(a) { if (a.length === 1) return new Fraction(a[0]); return rec(a.slice(1))['inverse']()['add'](a[0]); }
Check if two rational numbers are the same Ex: new Fraction(19.6).equals([98, 5]);
rec
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
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 (type.isMatrix(data)) { // cre...
Sparse Matrix implementation. This type implements a Compressed Column Storage format for sparse matrices. @class SparseMatrix
SparseMatrix
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _createFromMatrix(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._pt...
Sparse Matrix implementation. This type implements a Compressed Column Storage format for sparse matrices. @class SparseMatrix
_createFromMatrix
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _createFromArray(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 ...
Sparse Matrix implementation. This type implements a Compressed Column Storage format for sparse matrices. @class SparseMatrix
_createFromArray
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _getsubset(matrix, idx) { // check idx if (!type.isIndex(idx)) { throw new TypeError('Invalid index'); } var isScalar = idx.isScalar(); if (isScalar) { // return a scalar return matrix.get(idx.min()); } // validate dimensions var size = idx.size(); if (siz...
Get a subset of the matrix, or replace a subset of the matrix. Usage: const subset = matrix.subset(index) // retrieve subset const value = matrix.subset(index, replacement) // replace subset @memberof SparseMatrix @param {Index} index @param {Array | Matrix | *} [replacement] @param {*} [defau...
_getsubset
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _setsubset(matrix, index, submatrix, defaultValue) { // check index if (!index || index.isIndex !== true) { throw new TypeError('Invalid index'); } // get index size and check whether the index contains a single value var iSize = index.size(); var isScalar = index.isScalar(); // cal...
Get a subset of the matrix, or replace a subset of the matrix. Usage: const subset = matrix.subset(index) // retrieve subset const value = matrix.subset(index, replacement) // replace subset @memberof SparseMatrix @param {Index} index @param {Array | Matrix | *} [replacement] @param {*} [defau...
_setsubset
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _getValueIndex(i, top, bottom, index) { // check row is on the bottom side if (bottom - top === 0) { return bottom; } // loop rows [top, bottom[ for (var r = top; r < bottom; r++) { // check we found value index if (index[r] === i) { return r; } } // we did...
Replace a single element in the matrix. @memberof SparseMatrix @param {number[]} index Zero-based index @param {*} v @param {*} [defaultValue] Default value, filled in on new entries when the matrix is resized. If not provided, new matrix elemen...
_getValueIndex
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _remove(k, j, values, index, ptr) { // remove value @ k values.splice(k, 1); index.splice(k, 1); // update pointers for (var x = j + 1; x < ptr.length; x++) { ptr[x]--; } }
Replace a single element in the matrix. @memberof SparseMatrix @param {number[]} index Zero-based index @param {*} v @param {*} [defaultValue] Default value, filled in on new entries when the matrix is resized. If not provided, new matrix elemen...
_remove
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _insert(k, i, j, v, values, index, ptr) { // insert value values.splice(k, 0, v); // update row for k index.splice(k, 0, i); // update column pointers for (var x = j + 1; x < ptr.length; x++) { ptr[x]++; } }
Replace a single element in the matrix. @memberof SparseMatrix @param {number[]} index Zero-based index @param {*} v @param {*} [defaultValue] Default value, filled in on new entries when the matrix is resized. If not provided, new matrix elemen...
_insert
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _resize(matrix, rows, columns, defaultValue) { // value to insert at the time of growing matrix var value = defaultValue || 0; // equal signature to use var eq = equalScalar; // zero value var zero = 0; if (isString(matrix._datatype)) { // find signature that matches (datatype, dat...
Resize the matrix to the given size. Returns a copy of the matrix when `copy=true`, otherwise return the matrix itself (resize in place). @memberof SparseMatrix @param {number[]} size The new size the matrix should have. @param {*} [defaultValue=0] Default value, filled in on new entries. ...
_resize
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
invoke = function invoke(v, i, j) { // invoke callback return callback(v, [i, j], me); }
Create a new matrix with the results of the callback function executed on each entry of the matrix. @memberof SparseMatrix @param {Function} callback The callback function is invoked with three parameters: the value of the element, the index of the element, an...
invoke
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _map(matrix, minRow, maxRow, minColumn, maxColumn, callback, skipZeros) { // result arrays var values = []; var index = []; var ptr = []; // equal signature to use var eq = equalScalar; // zero value var zero = 0; if (isString(matrix._datatype)) { // find signature that mat...
Create a new matrix with the results of the callback function executed on the interval [minRow..maxRow, minColumn..maxColumn].
_map
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
invoke = function invoke(v, x, y) { // invoke callback v = callback(v, x, y); // check value != 0 if (!eq(v, zero)) { // store value values.push(v); // index index.push(x); } }
Create a new matrix with the results of the callback function executed on the interval [minRow..maxRow, minColumn..maxColumn].
invoke
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
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(); }
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.
Spa
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
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; }
Fibonacci Heap implementation, used interally for Matrix math. @class FibonacciHeap @constructor FibonacciHeap
FibonacciHeap
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _decreaseKey(minimum, node, key) { // set node key node.key = key; // get parent node var parent = node.parent; if (parent && smaller(node.key, parent.key)) { // remove node from parent _cut(minimum, node, parent); // remove all nodes from parent to the root parent _cascad...
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
_decreaseKey
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _cut(minimum, node, parent) { // remove node from parent children and decrement Degree[parent] node.left.right = node.right; node.right.left = node.left; parent.degree--; // reset y.child if necessary if (parent.child === node) { parent.child = node.right; } // remove child if de...
The reverse of the link operation: removes node from the child list of parent. This method assumes that min is non-null. Running time: O(1). @memberof FibonacciHeap
_cut
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _cascadingCut(minimum, node) { // store parent node var parent = node.parent; // if there's a parent... if (!parent) { return; } // if node is unmarked, set it marked if (!node.mark) { node.mark = true; } else { // it's marked, cut it from parent _cut(minimum,...
Performs a cascading cut operation. This cuts node from its parent and then does the same for its parent, and so on up the tree. Running time: O(log n); O(1) excluding the recursion. @memberof FibonacciHeap
_cascadingCut
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
_linkNodes = function _linkNodes(node, parent) { // remove node from root list of heap node.left.right = node.right; node.right.left = node.left; // make node a Child of parent node.parent = parent; if (!parent.child) { parent.child = node; node.right = node; node.left = node; ...
Make the first node a child of the second one. Running time: O(1) actual. @memberof FibonacciHeap
_linkNodes
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _findMinimumNode(minimum, size) { // to find trees of the same degree efficiently we use an array of length O(log n) in which we keep a pointer to one root of each degree var arraySize = Math.floor(Math.log(size) * oneOverLogPhi) + 1; // create list with initial capacity var array = new Array(arra...
Make the first node a child of the second one. Running time: O(1) actual. @memberof FibonacciHeap
_findMinimumNode
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function Unit(value, name) { if (!(this instanceof Unit)) { throw new Error('Constructor must be called with the new operator'); } if (!(value === null || value === undefined || isNumeric(value) || type.isComplex(value))) { throw new TypeError('First parameter in Unit constructor must be number...
A unit can be constructed in the following ways: const a = new Unit(value, name) const b = new Unit(null, name) const c = Unit.parse(str) Example usage: const a = new Unit(5, 'cm') // 50 mm const b = Unit.parse('23 kg') // 23 kg const c = math.in(a, new Unit(null, 'm...
Unit
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _findUnit(str) { // First, match units names exactly. For example, a user could define 'mm' as 10^-4 m, which is silly, but then we would want 'mm' to match the user-defined unit. if (UNITS.hasOwnProperty(str)) { var unit = UNITS[str]; var prefix = unit.prefixes['']; return { ...
Find a unit from a string @memberof Unit @param {string} str A string like 'cm' or 'inch' @returns {Object | null} result When found, an object with fields unit and prefix is returned. Else, null is returned. @private
_findUnit
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function getNumericIfUnitless(unit) { if (unit.equalBase(BASE_UNITS.NONE) && unit.value !== null && !config.predictable) { return unit.value; } else { return unit; } }
Return the numeric value of this unit if it is dimensionless, has a value, and config.predictable == false; or the original unit otherwise @param {Unit} unit @returns {number | Fraction | BigNumber | Unit} The numeric value of the unit if conditions are met, or the original unit otherwise
getNumericIfUnitless
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function calculateAngleValues(config) { if (config.number === 'BigNumber') { var pi = constants.pi(type.BigNumber); UNITS.rad.value = new type.BigNumber(1); UNITS.deg.value = pi.div(180); // 2 * pi / 360 UNITS.grad.value = pi.div(200); // 2 * pi / 400 UNITS.cycle.value = pi.times(2);...
Calculate the values for the angle units. Value is calculated as number or BigNumber depending on the configuration @param {{number: 'number' | 'BigNumber'}} config
calculateAngleValues
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function assertUnitNameIsValid(name) { for (var i = 0; i < name.length; i++) { var _c = name.charAt(i); var isValidAlpha = function isValidAlpha(p) { return /^[a-zA-Z]$/.test(p); }; var _isDigit = function _isDigit(c) { return c >= '0' && c <= '9'; }; if (i ===...
Retrieve the right convertor function corresponding with the type of provided exampleValue. @param {string} type A string 'number', 'BigNumber', or 'Fraction' In case of an unknown type, @return {Function}
assertUnitNameIsValid
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
isValidAlpha = function isValidAlpha(p) { return /^[a-zA-Z]$/.test(p); }
Retrieve the right convertor function corresponding with the type of provided exampleValue. @param {string} type A string 'number', 'BigNumber', or 'Fraction' In case of an unknown type, @return {Function}
isValidAlpha
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
_isDigit = function _isDigit(c) { return c >= '0' && c <= '9'; }
Retrieve the right convertor function corresponding with the type of provided exampleValue. @param {string} type A string 'number', 'BigNumber', or 'Fraction' In case of an unknown type, @return {Function}
_isDigit
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function funcArgsCheck(node) { // TODO add min, max etc if ((node.name === 'log' || node.name === 'nthRoot' || node.name === 'pow') && node.args.length === 2) { return; } // There should be an incorrect number of arguments if we reach here // Change all args to constants to avoid unidentified ...
Ensures the number of arguments for a function are correct, and will throw an error otherwise. @param {FunctionNode} node
funcArgsCheck
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function createConstantNode(value, valueType) { return new ConstantNode(numeric(value, valueType || config.number)); }
Helper function to create a constant node with a specific type (number, BigNumber, Fraction) @param {number} value @param {string} [valueType] @return {ConstantNode}
createConstantNode
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function resolve(node, scope) { if (!scope) { return node; } if (type.isSymbolNode(node)) { var value = scope[node.name]; if (value instanceof Node) { return resolve(value, scope); } else if (typeof value === 'number') { return math.parse(String(value)); } ...
resolve(expr, scope) replaces variable nodes with their scoped values Syntax: simplify.resolve(expr, scope) Examples: math.simplify.resolve('x + y', {x:1, y:2}) // Node {1 + 2} math.simplify.resolve(math.parse('x+y'), {x:1, y:2}) // Node {1 + 2} math.simplify('x+y', {x:2, y:'x+x'}).toStrin...
resolve
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function polynomial(expr, scope, extended, rules) { var variables = []; var node = simplify(expr, rules, scope, { exactFractions: false }); // Resolves any variables and functions with all defined parameters extended = !!extended; var oper = '+-*' + (extended ? '/' : ''); recPoly(node); ...
Function to simplify an expression using an optional scope and return it if the expression is a polynomial expression, i.e. an expression with one or more variables and the operators +, -, *, and ^, where the exponent can only be a positive integer. Syntax: polynomial(expr,scope,extended, rules) @param {Node...
polynomial
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function recPoly(node) { var tp = node.type; // node type if (tp === 'FunctionNode') { // No function call in polynomial expression throw new Error('There is an unsolved function call'); } else if (tp === 'OperatorNode') { if (node.op === '^') { if (node.args[1].fn =...
Function to simplify an expression using an optional scope and return it if the expression is a polynomial expression, i.e. an expression with one or more variables and the operators +, -, *, and ^, where the exponent can only be a positive integer. Syntax: recPoly(node) @param {Node} node The...
recPoly
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function expandPower(node, parent, indParent) { var tp = node.type; var internal = arguments.length > 1; // TRUE in internal calls if (tp === 'OperatorNode' && node.isBinary()) { var does = false; var val; if (node.op === '^') { // First operator: Parenthesis or UnaryMinus ...
Expand recursively a tree node for handling with expressions with exponents (it's not for constants, symbols or functions with exponents) PS: The other parameters are internal for recursion Syntax: expandPower(node) @param {Node} node Current expression node @param {node} parent Parent current ...
expandPower
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function recurPol(node, noPai, o) { var tp = node.type; if (tp === 'FunctionNode') { // ***** FunctionName ***** // No function call in polynomial expression throw new Error('There is an unsolved function call'); } else if (tp === 'OperatorNode') { // ***** OperatorNam...
Recursive auxilary function inside polyToCanonical for converting expression in canonical form Syntax: recurPol(node, noPai, obj) @param {Node} node The current subpolynomial expression @param {Node | Null} noPai The current parent node @param {object} obj Object with many internal flags ...
recurPol
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _denseQR(m) { // rows & columns (m x n) var rows = m._size[0]; // m var cols = m._size[1]; // n var Q = identity([rows], 'dense'); var Qdata = Q._data; var R = m.clone(); var Rdata = R._data; // vars var i, j, k; var w = zeros([rows], ''); for (k = 0; k < Math.min(co...
Calculate the Matrix QR decomposition. Matrix `A` is decomposed in two matrices (`Q`, `R`) where `Q` is an orthogonal matrix and `R` is an upper triangular matrix. Syntax: math.qr(A) Example: const m = [ [1, -1, 4], [1, 4, -2], [1, 4, 2], [1, -1, 0] ] const result = math.qr(m) ...
_denseQR
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _sparseQR(m) { throw new Error('qr not implemented for sparse matrices yet'); }
Calculate the Matrix QR decomposition. Matrix `A` is decomposed in two matrices (`Q`, `R`) where `Q` is an orthogonal matrix and `R` is an upper triangular matrix. Syntax: math.qr(A) Example: const m = [ [1, -1, 4], [1, 4, -2], [1, 4, 2], [1, -1, 0] ] const result = math.qr(m) ...
_sparseQR
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
csSqr = function csSqr(order, a, qr) { // a arrays var aptr = a._ptr; var asize = a._size; // columns var n = asize[1]; // vars var k; // symbolic analysis result var s = {}; // fill-reducing ordering s.q = csAmd(order, a); // validate results if (order && !s.q) { return null;...
Symbolic ordering and analysis for QR and LU decompositions. @param {Number} order The ordering strategy (see csAmd for more details) @param {Matrix} a The A matrix @param {boolean} qr Symbolic ordering and analysis for QR decomposition (true) or ...
csSqr
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _vcount(a, s) { // a arrays var aptr = a._ptr; var aindex = a._index; var asize = a._size; // rows & columns var m = asize[0]; var n = asize[1]; // initialize s arrays s.pinv = []; // (m + n) s.leftmost = []; // (m) // vars var parent = s.parent; var pinv = s.pin...
Compute nnz(V) = s.lnz, s.pinv, s.leftmost, s.m2 from A and s.parent
_vcount
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
csAmd = function csAmd(order, a) { // check input parameters if (!a || order <= 0 || order > 3) { return null; } // a matrix arrays var asize = a._size; // rows and columns var m = asize[0]; var n = asize[1]; // initialize vars var lemax = 0; // dense threshold var dense = Mat...
Approximate minimum degree ordering. The minimum degree algorithm is a widely used heuristic for finding a permutation P so that P*A*P' has fewer nonzeros in its factorization than A. It is a gready method that selects the sparsest pivot row and column during the course of a right looking sparse Cholesky factorization....
csAmd
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _createTargetMatrix(order, a, m, n, dense) { // compute A' var at = transpose(a); // check order = 1, matrix must be square if (order === 1 && n === m) { // C = A + A' return add(a, at); } // check order = 2, drop dense columns from M' if (order === 2) { // transpose ar...
Creates the matrix that will be used by the approximate minimum degree ordering algorithm. The function accepts the matrix M as input and returns a permutation vector P. The amd algorithm operates on a symmetrix matrix, so one of three symmetric matrices is formed. Order: 0 A natural ordering P=null matrix is return...
_createTargetMatrix
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _initializeQuotientGraph(n, cptr, W, len, head, last, next, hhead, nv, w, elen, degree) { // Initialize quotient graph for (var k = 0; k < n; k++) { W[len + k] = cptr[k + 1] - cptr[k]; } W[len + n] = 0; // initialize workspace for (var i = 0; i <= n; i++) { // degree list i is...
Initialize quotient graph. There are four kind of nodes and elements that must be represented: - A live node is a node i (or a supernode) that has not been selected as a pivot nad has not been merged into another supernode. - A dead node i is one that has been removed from the graph, having been absorved into r = fl...
_initializeQuotientGraph
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _initializeDegreeLists(n, cptr, W, degree, elen, w, dense, nv, head, last, next) { // result var nel = 0; // loop columns for (var i = 0; i < n; i++) { // degree @ i var d = W[degree + i]; // check node i is empty if (d === 0) { // element i is dead W[elen + i] =...
Initialize degree lists. Each node is placed in its degree lists. Nodes of zero degree are eliminated immediately. Nodes with degree >= dense are alsol eliminated and merged into a placeholder node n, a dead element. Thes nodes will appera last in the output permutation p.
_initializeDegreeLists
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _wclear(mark, lemax, W, w, n) { if (mark < 2 || mark + lemax < 0) { for (var k = 0; k < n; k++) { if (W[w + k] !== 0) { W[w + k] = 1; } } mark = 2; } // at this point, W [0..n-1] < mark holds return mark; }
Initialize degree lists. Each node is placed in its degree lists. Nodes of zero degree are eliminated immediately. Nodes with degree >= dense are alsol eliminated and merged into a placeholder node n, a dead element. Thes nodes will appera last in the output permutation p.
_wclear
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _diag(i, j) { return i !== j; }
Initialize degree lists. Each node is placed in its degree lists. Nodes of zero degree are eliminated immediately. Nodes with degree >= dense are alsol eliminated and merged into a placeholder node n, a dead element. Thes nodes will appera last in the output permutation p.
_diag
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
csFkeep = function csFkeep(a, callback, other) { // a arrays var avalues = a._values; var aindex = a._index; var aptr = a._ptr; var asize = a._size; // columns var n = asize[1]; // nonzero items var nz = 0; // loop columns for (var j = 0; j < n; j++) { // get current location of...
Keeps entries in the matrix when the callback function returns true, removes the entry otherwise @param {Matrix} a The sparse matrix @param {function} callback The callback function, function will be invoked with the following args: - The entry row ...
csFkeep
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
csPermute = function csPermute(a, pinv, q, values) { // a arrays var avalues = a._values; var aindex = a._index; var aptr = a._ptr; var asize = a._size; var adt = a._datatype; // rows & columns var m = asize[0]; var n = asize[1]; // c arrays var cvalues = values && a._values ? [] :...
Permutes a sparse matrix C = P * A * Q @param {Matrix} a The Matrix A @param {Array} pinv The row permutation vector @param {Array} q The column permutation vector @param {boolean} values Create a pattern matrix (false), values and pattern otherwise @return {Matrix...
csPermute
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
csEtree = function csEtree(a, ata) { // check inputs if (!a) { return null; } // a arrays var aindex = a._index; var aptr = a._ptr; var asize = a._size; // rows & columns var m = asize[0]; var n = asize[1]; // allocate result var parent = []; // (n) // allocate workspac...
Computes the elimination tree of Matrix A (using triu(A)) or the elimination tree of A'A without forming A'A. @param {Matrix} a The A Matrix @param {boolean} ata A value of true the function computes the etree of A'A Reference: http://faculty.cse.tamu.edu/davis/publications.html
csEtree
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
csPost = function csPost(parent, n) { // check inputs if (!parent) { return null; } // vars var k = 0; var j; // allocate result var post = []; // (n) // workspace, head: first n entries, next: next n entries, stack: last n entries var w = []; // (3 * n) var head = 0; ...
Post order a tree of forest @param {Array} parent The tree or forest @param {Number} n Number of columns Reference: http://faculty.cse.tamu.edu/davis/publications.html
csPost
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
csCounts = function csCounts(a, parent, post, ata) { // check inputs if (!a || !parent || !post) { return null; } // a matrix arrays var asize = a._size; // rows and columns var m = asize[0]; var n = asize[1]; // variables var i, j, k, J, p, p0, p1; // workspace size var s = 4...
Computes the column counts using the upper triangular part of A. It transposes A internally, none of the input parameters are modified. @param {Matrix} a The sparse matrix A @param {Matrix} ata Count the columns of A'A instead @return An array of size n of the column counts or n...
csCounts
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
csLeaf = function csLeaf(i, j, w, first, maxfirst, prevleaf, ancestor) { var s, sparent, jprev; // our result var jleaf = 0; var q; // check j is a leaf if (i <= j || w[first + j] <= w[maxfirst + i]) { return -1; } // update max first[j] seen so far w[maxfirst + i] = w[first + j]; // j...
This function determines if j is a leaf of the ith row subtree. Consider A(i,j), node j in ith row subtree and return lca(jprev,j) @param {Number} i The ith row subtree @param {Number} j The node to test @param {Array} w The workspace array @param {Number} first ...
csLeaf
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
csLu = function csLu(m, s, tol) { // validate input if (!m) { return null; } // m arrays var size = m._size; // columns var n = size[1]; // symbolic analysis result var q; var lnz = 100; var unz = 100; // update symbolic analysis parameters if (s) { q = s.q; ln...
Computes the numeric LU factorization of the sparse matrix A. Implements a Left-looking LU factorization algorithm that computes L and U one column at a tume. At the kth step, it access columns 1 to k-1 of L and column k of A. Given the fill-reducing column ordering q (see parameter s) computes L, U and pinv so L * U =...
csLu
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
csSpsolve = function csSpsolve(g, b, k, xi, x, pinv, lo) { // g arrays var gvalues = g._values; var gindex = g._index; var gptr = g._ptr; var gsize = g._size; // columns var n = gsize[1]; // b arrays var bvalues = b._values; var bindex = b._index; var bptr = b._ptr; // vars va...
The function csSpsolve() computes the solution to G * x = bk, where bk is the kth column of B. When lo is true, the function assumes G = L is lower triangular with the diagonal entry as the first entry in each column. When lo is true, the function assumes G = U is upper triangular with the diagonal entry as the last en...
csSpsolve
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
csReach = function csReach(g, b, k, xi, pinv) { // g arrays var gptr = g._ptr; var gsize = g._size; // b arrays var bindex = b._index; var bptr = b._ptr; // columns var n = gsize[1]; // vars var p, p0, p1; // initialize top var top = n; // loop column indeces in B for (p0 = bptr...
The csReach function computes X = Reach(B), where B is the nonzero pattern of the n-by-1 sparse column of vector b. The function returns the set of nodes reachable from any node in B. The nonzero pattern xi of the solution x to the sparse linear system Lx=b is given by X=Reach(B). @param {Matrix} g The ...
csReach
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
csDfs = function csDfs(j, g, top, xi, pinv) { // g arrays var index = g._index; var ptr = g._ptr; var size = g._size; // columns var n = size[1]; // vars var i, p, p2; // initialize head var head = 0; // initialize the recursion stack xi[0] = j; // loop while (head >= 0) { ...
Depth-first search computes the nonzero pattern xi of the directed graph G (Matrix) starting at nodes in B (see csReach()). @param {Number} j The starting node for the DFS algorithm @param {Matrix} g The G matrix to search, ptr array modified, then restored @param {Number} top ...
csDfs
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
csUnflip = function csUnflip(i) { // flip the value if it is negative return i < 0 ? csFlip(i) : i; }
Flips the value if it is negative of returns the same value otherwise. @param {Number} i The value to flip Reference: http://faculty.cse.tamu.edu/davis/publications.html
csUnflip
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
_toMatrix = function _toMatrix(a) { // check it is a matrix if (type.isMatrix(a)) { return a; } // check array if (isArray(a)) { return matrix(a); } // throw throw new TypeError('Invalid Matrix LU decomposition'); }
Solves the linear system `A * x = b` where `A` is an [n x n] matrix and `b` is a [n] column vector. Syntax: math.lusolve(A, b) // returns column vector with the solution to the linear system A * x = b math.lusolve(lup, b) // returns column vector with the solution to the linear system A * x = b, lup = mat...
_toMatrix
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _lusolve(l, u, p, q, b) { // verify L, U, P l = _toMatrix(l); u = _toMatrix(u); // validate matrix and vector b = solveValidation(l, b, false); // apply row permutations if needed (b is a DenseMatrix) if (p) { b._data = csIpvec(p, b._data); } // use forward substitution to resol...
Solves the linear system `A * x = b` where `A` is an [n x n] matrix and `b` is a [n] column vector. Syntax: math.lusolve(A, b) // returns column vector with the solution to the linear system A * x = b math.lusolve(lup, b) // returns column vector with the solution to the linear system A * x = b, lup = mat...
_lusolve
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function csIpvec(p, b) { // vars var k; var n = b.length; var x = []; // check permutation vector was provided, p = null denotes identity if (p) { // loop vector for (k = 0; k < n; k++) { // apply permutation x[p[k]] = b[k]; } } else { // loop vector ...
Permutes a vector; x = P'b. In MATLAB notation, x(p)=b. @param {Array} p The permutation vector of length n. null value denotes identity @param {Array} b The input vector @return {Array} The output vector x = P'b
csIpvec
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _cbrtComplex(x, allRoots) { // https://www.wikiwand.com/en/Cube_root#/Complex_numbers var arg3 = x.arg() / 3; var abs = x.abs(); // principal root: var principal = new type.Complex(_cbrtNumber(abs), 0).mul(new type.Complex(0, arg3).exp()); if (allRoots) { var all = [principal, new t...
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....
_cbrtComplex
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _cbrtUnit(x) { if (x.value && type.isComplex(x.value)) { 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.valu...
Calculate the cubic root for a Unit @param {Unit} x @return {Unit} Returns the cubic root of x @private
_cbrtUnit
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _expm1(x) { return x >= 2e-4 || x <= -2e-4 ? Math.exp(x) - 1 : x + x * x / 2 + x * x * x / 6; }
Calculates exponentiation minus 1. @param {number} x @return {number} res @private
_expm1
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _gcdBigNumber(a, b) { if (!a.isInt() || !b.isInt()) { throw new Error('Parameters in function gcd must be integer numbers'); } // https://en.wikipedia.org/wiki/Euclidean_algorithm var zero = new type.BigNumber(0); while (!b.isZero()) { var r = a.mod(b); a = b; b = r; ...
Calculate gcd for BigNumbers @param {BigNumber} a @param {BigNumber} b @returns {BigNumber} Returns greatest common denominator of a and b @private
_gcdBigNumber
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _gcd(a, b) { if (!isInteger(a) || !isInteger(b)) { throw new Error('Parameters in function gcd must be integer numbers'); } // https://en.wikipedia.org/wiki/Euclidean_algorithm var r; while (b !== 0) { r = a % b; a = b; b = r; } return a < 0 ? -a : a; }
Calculate gcd for numbers @param {number} a @param {number} b @returns {number} Returns the greatest common denominator of a and b @private
_gcd
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
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 ...
Calculate the hypotenusa for an Array with values @param {Array.<number | BigNumber>} args @return {number | BigNumber} Returns the result @private
_hypot
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _lcmBigNumber(a, b) { if (!a.isInt() || !b.isInt()) { throw new Error('Parameters in function lcm must be integer numbers'); } if (a.isZero() || b.isZero()) { return new type.BigNumber(0); } // https://en.wikipedia.org/wiki/Euclidean_algorithm // evaluate lcm here inline to red...
Calculate lcm for two BigNumbers @param {BigNumber} a @param {BigNumber} b @returns {BigNumber} Returns the least common multiple of a and b @private
_lcmBigNumber
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _lcm(a, b) { if (!isInteger(a) || !isInteger(b)) { throw new Error('Parameters in function lcm must be integer numbers'); } if (a === 0 || b === 0) { return 0; } // https://en.wikipedia.org/wiki/Euclidean_algorithm // evaluate lcm here inline to reduce overhead var t; var prod = a * b;...
Calculate lcm for two numbers @param {number} a @param {number} b @returns {number} Returns the least common multiple of a and b @private
_lcm
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _log1pNumber(x) { if (x >= -1 || config.predictable) { return Math.log1p ? Math.log1p(x) : Math.log(x + 1); } else { // negative value -> complex value computation return _log1pComplex(new type.Complex(x, 0)); } }
Calculate the natural logarithm of a `number+1` @param {number} x @returns {number | Complex} @private
_log1pNumber
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _log1pComplex(x) { var xRe1p = x.re + 1; return new type.Complex(Math.log(Math.sqrt(xRe1p * xRe1p + x.im * x.im)), Math.atan2(x.im, xRe1p)); }
Calculate the natural logarithm of a complex number + 1 @param {Complex} x @returns {Complex} @private
_log1pComplex
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _log2Complex(x) { var newX = Math.sqrt(x.re * x.re + x.im * x.im); return new type.Complex(Math.log2 ? Math.log2(newX) : Math.log(newX) / Math.LN2, Math.atan2(x.im, x.re) / Math.LN2); }
Calculate log2 for a complex value @param {Complex} x @returns {Complex} @private
_log2Complex
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _mod(x, y) { if (y > 0) { // We don't use JavaScript's % operator here as this doesn't work // correctly for x < 0 and x === 0 // see https://en.wikipedia.org/wiki/Modulo_operation return x - y * Math.floor(x / y); } else if (y === 0) { return x; } else { // y < ...
Calculate the modulus of two numbers @param {number} x @param {number} y @returns {number} res @private
_mod
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
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...
Calculate the norm for an array @param {Matrix} x @param {number | string} p @returns {number} Returns the norm @private
_norm
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _bigNthRoot(a, root) { var precision = type.BigNumber.precision; var Big = type.BigNumber.clone({ precision: precision + 2 }); var zero = new type.BigNumber(0); var one = new Big(1); var inv = root.isNegative(); if (inv) { root = root.neg(); } if (root.isZero()...
Calculate the nth root of a for BigNumbers, solve x^root == a https://rosettacode.org/wiki/Nth_root#JavaScript @param {BigNumber} a @param {BigNumber} root @private
_bigNthRoot
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _nthRoot(a, root) { var inv = root < 0; if (inv) { root = -root; } if (root === 0) { throw new Error('Root must be non-zero'); } if (a < 0 && Math.abs(root) % 2 !== 1) { throw new Error('Root must be odd when a is negative.'); } // edge cases zero and infinity if (a === 0) { ...
Calculate the nth root of a, solve x^root == a https://rosettacode.org/wiki/Nth_root#JavaScript @param {number} a @param {number} root @private
_nthRoot
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT