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 parseImplicitMultiplication(state) { var node, last, previous; node = parseRule2(state); last = node; previous = last; while (true) { if (state.tokenType === TOKENTYPE.SYMBOL || state.token === 'in' && type.isConstantNode(node) || state.tokenType === TOKENTYPE.NUMBER && !type.isConst...
implicit multiplication @return {Node} node @private
parseImplicitMultiplication
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function parseRule2(state) { var node = parseUnary(state); var last = node; var tokenStates = []; while (true) { // Match the "number /" part of the pattern "number / number symbol" if (state.token === '/' && type.isConstantNode(last)) { // Look ahead to see if the next token is a n...
Infamous "rule 2" as described in https://github.com/josdejong/mathjs/issues/792#issuecomment-361065370 Explicit division gets higher precedence than implicit multiplication when the division matches this pattern: [number] / [number] [symbol] @return {Node} node @private
parseRule2
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function parseUnary(state) { var name, params, fn; var operators = { '-': 'unaryMinus', '+': 'unaryPlus', '~': 'bitNot', 'not': 'not' }; if (operators.hasOwnProperty(state.token)) { fn = operators[state.token]; name = state.token; getTokenSkipNewline(state); ...
Unary plus and minus, and logical and bitwise not @return {Node} node @private
parseUnary
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function parsePow(state) { var node, name, fn, params; node = parseLeftHandOperators(state); if (state.token === '^' || state.token === '.^') { name = state.token; fn = name === '^' ? 'pow' : 'dotPow'; getTokenSkipNewline(state); params = [node, parseUnary(state)]; // Go back to una...
power Note: power operator is right associative @return {Node} node @private
parsePow
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function parseLeftHandOperators(state) { var node, operators, name, fn, params; node = parseCustomNodes(state); operators = { '!': 'factorial', '\'': 'ctranspose' }; while (operators.hasOwnProperty(state.token)) { name = state.token; fn = operators[name]; getToken(stat...
Left hand operators: factorial x!, ctranspose x' @return {Node} node @private
parseLeftHandOperators
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function parseCustomNodes(state) { var params = []; if (state.tokenType === TOKENTYPE.SYMBOL && state.extraNodes.hasOwnProperty(state.token)) { var CustomNode = state.extraNodes[state.token]; getToken(state); // parse parameters if (state.token === '(') { params = []; openPar...
Parse a custom node handler. A node handler can be used to process nodes in a custom way, for example for handling a plot. A handler must be passed as second argument of the parse function. - must extend math.expression.node.Node - must contain a function _compile(defs: Object) : string - must contain a function find(...
parseCustomNodes
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function parseSymbol(state) { var node, name; if (state.tokenType === TOKENTYPE.SYMBOL || state.tokenType === TOKENTYPE.DELIMITER && state.token in NAMED_DELIMITERS) { name = state.token; getToken(state); if (CONSTANTS.hasOwnProperty(name)) { // true, false, null, ... node = ...
parse symbols: functions, variables, constants, units @return {Node} node @private
parseSymbol
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function parseAccessors(state, node, types) { var params; while ((state.token === '(' || state.token === '[' || state.token === '.') && (!types || types.indexOf(state.token) !== -1)) { // eslint-disable-line no-unmodified-loop-condition params = []; if (state.token === '(') { if (typ...
parse accessors: - function invocation in round brackets (...), for example sqrt(2) - index enclosed in square brackets [...], for example A[2,3] - dot notation for properties, like foo.bar @param {Node} node Node on which to apply the parameters. If there are no parameters in the expression, t...
parseAccessors
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function parseDoubleQuotesString(state) { var node, str; if (state.token === '"') { str = parseDoubleQuotesStringToken(state); // create constant node = new ConstantNode(str); // parse index parameters node = parseAccessors(state, node); return node; } return parseSingleQuote...
Parse a double quotes string. @return {Node} node @private
parseDoubleQuotesString
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function parseDoubleQuotesStringToken(state) { var str = ''; while (currentCharacter(state) !== '' && currentCharacter(state) !== '"') { if (currentCharacter(state) === '\\') { // escape character, immediately process the next // character to prevent stopping at a next '\"' str +=...
Parse a string surrounded by double quotes "..." @return {string}
parseDoubleQuotesStringToken
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function parseSingleQuotesString(state) { var node, str; if (state.token === '\'') { str = parseSingleQuotesStringToken(state); // create constant node = new ConstantNode(str); // parse index parameters node = parseAccessors(state, node); return node; } return parseMatrix(sta...
Parse a single quotes string. @return {Node} node @private
parseSingleQuotesString
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function parseSingleQuotesStringToken(state) { var str = ''; while (currentCharacter(state) !== '' && currentCharacter(state) !== '\'') { if (currentCharacter(state) === '\\') { // escape character, immediately process the next // character to prevent stopping at a next '\'' str +...
Parse a string surrounded by single quotes '...' @return {string}
parseSingleQuotesStringToken
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function parseMatrix(state) { var array, params, rows, cols; if (state.token === '[') { // matrix [...] openParams(state); getToken(state); if (state.token !== ']') { // this is a non-empty matrix var row = parseRow(state); if (state.token === ';') { ...
parse the matrix @return {Node} node @private
parseMatrix
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function parseRow(state) { var params = [parseAssignment(state)]; var len = 1; while (state.token === ',') { // eslint-disable-line no-unmodified-loop-condition getToken(state); // parse expression params[len] = parseAssignment(state); len++; } return new ArrayNode(params)...
Parse a single comma-separated row from a matrix, like 'a, b, c' @return {ArrayNode} node
parseRow
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function parseObject(state) { if (state.token === '{') { openParams(state); var key; var properties = {}; do { getToken(state); if (state.token !== '}') { // parse key if (state.token === '"') { key = parseDoubleQuotesStringToken(state); ...
parse an object, enclosed in angle brackets{...}, for example {value: 2} @return {Node} node @private
parseObject
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function parseNumber(state) { var numberStr; if (state.tokenType === TOKENTYPE.NUMBER) { // this is a number numberStr = state.token; getToken(state); return new ConstantNode(numeric(numberStr, config.number)); } return parseParentheses(state); }
parse a number @return {Node} node @private
parseNumber
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function parseEnd(state) { if (state.token === '') { // syntax error or unexpected end of expression throw createSyntaxError(state, 'Unexpected end of expression'); } else { throw createSyntaxError(state, 'Value expected'); } }
Evaluated when the expression is not yet ended but expected to end @return {Node} res @private
parseEnd
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function col(state) { return state.index - state.token.length + 1; }
Shortcut for getting the current col value (one based) Returns the column (position) where the last state.token starts @private
col
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function createSyntaxError(state, message) { var c = col(state); var error = new SyntaxError(message + ' (char ' + c + ')'); error['char'] = c; return error; }
Create an error @param {string} message @return {SyntaxError} instantiated error @private
createSyntaxError
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function createError(state, message) { var c = col(state); var error = new SyntaxError(message + ' (char ' + c + ')'); error['char'] = c; return error; }
Create an error @param {string} message @return {Error} instantiated error @private
createError
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _sqrtNumber(x) { if (isNaN(x)) { return NaN; } else if (x >= 0 || config.predictable) { return Math.sqrt(x); } else { return new type.Complex(x, 0).sqrt(); } }
Calculate sqrt for a number @param {number} x @returns {number | Complex} Returns the square root of x @private
_sqrtNumber
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
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....
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
IndexError
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function DenseMatrix(data, datatype) { if (!(this instanceof DenseMatrix)) { throw new SyntaxError('Constructor must be called with the new operator'); } if (datatype && !isString(datatype)) { throw new Error('Invalid datatype: ' + datatype); } if (type.isMatrix(data)) { // check...
Dense Matrix implementation. A regular, dense matrix, supporting multi-dimensional matrices. This is the default matrix type. @class DenseMatrix
DenseMatrix
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _get(matrix, index) { if (!type.isIndex(index)) { throw new TypeError('Invalid index'); } var isScalar = index.isScalar(); if (isScalar) { // return a scalar return matrix.get(index.min()); } else { // validate dimensions var size = index.size(); if (s...
Get a submatrix of this matrix @memberof DenseMatrix @param {DenseMatrix} matrix @param {Index} index Zero-based index @private
_get
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _getSubmatrix(data, index, dims, dim) { var last = dim === dims - 1; var range = index.dimension(dim); if (last) { return range.map(function (i) { validateIndex(i, data.length); return data[i]; }).valueOf(); } else { return range.map(function (i) { val...
Recursively get a submatrix of a multi dimensional matrix. Index is not checked for correct number or length of dimensions. @memberof DenseMatrix @param {Array} data @param {Index} index @param {number} dims Total number of dimensions @param {number} dim Current dimension @return {Array} submatrix @private
_getSubmatrix
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _set(matrix, index, submatrix, defaultValue) { 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(); // calculate the size of the su...
Replace a submatrix in this matrix Indexes are zero-based. @memberof DenseMatrix @param {DenseMatrix} matrix @param {Index} index @param {DenseMatrix | Array | *} submatrix @param {*} defaultValue Default value, filled in on new entries when the matrix is resized. @return {Dens...
_set
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _setSubmatrix(data, index, submatrix, dims, dim) { var last = dim === dims - 1; var range = index.dimension(dim); if (last) { range.forEach(function (dataIndex, subIndex) { validateIndex(dataIndex); data[dataIndex] = submatrix[subIndex[0]]; }); } else { range....
Replace a submatrix of a multi dimensional matrix. @memberof DenseMatrix @param {Array} data @param {Index} index @param {Array} submatrix @param {number} dims Total number of dimensions @param {number} dim @private
_setSubmatrix
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _resize(matrix, size, defaultValue) { // check size if (size.length === 0) { // first value in matrix var v = matrix._data; // go deep while (isArray(v)) { v = v[0]; } return v; } // resize matrix matrix._size = size.slice(0); // copy the array mat...
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 DenseMatrix @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
function _fit(matrix, size, defaultValue) { var // copy the array newSize = matrix._size.slice(0); var changed = false; // add dimensions when needed while (newSize.length < size.length) { newSize.push(0); changed = true; } // enlarge size when needed for (var i = 0, ii = size.le...
Enlarge the matrix when it is smaller than given size. If the matrix is larger or equal sized, nothing is done. @memberof DenseMatrix @param {DenseMatrix} matrix The matrix to be resized @param {number[]} size @param {*} defaultValue Default value, filled in on new entries. @private
_fit
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
recurse = function recurse(value, index) { if (isArray(value)) { return value.map(function (child, i) { return recurse(child, index.concat(i)); }); } else { return callback(value, index, me); } }
Create a new matrix with the results of the callback function executed on each entry of the matrix. @memberof DenseMatrix @param {Function} callback The callback function is invoked with three parameters: the value of the element, the index of the element, and...
recurse
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
recurse = function recurse(value, index) { if (isArray(value)) { value.forEach(function (child, i) { recurse(child, index.concat(i)); }); } else { callback(value, index, me); } }
Execute a callback function on each entry of the matrix. @memberof DenseMatrix @param {Function} callback The callback function is invoked with three parameters: the value of the element, the index of the element, and the Matrix being traversed.
recurse
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function preprocess(data) { for (var i = 0, ii = data.length; i < ii; i++) { var elem = data[i]; if (isArray(elem)) { data[i] = preprocess(elem); } else if (elem && elem.isMatrix === true) { data[i] = preprocess(elem.valueOf()); } } return data; } // register this...
Preprocess data, which can be an Array or DenseMatrix with nested Arrays and Matrices. Replaces all nested Matrices with Arrays @memberof DenseMatrix @param {Array} data @return {Array} data
preprocess
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _identityVector(size, format) { switch (size.length) { case 0: return format ? matrix(format) : []; case 1: return _identity(size[0], size[0], format); case 2: return _identity(size[0], size[1], format); default: throw new Error('Vector containing ...
Create a 2-dimensional identity matrix with size m x n or n x n. The matrix has ones on the diagonal and zeros elsewhere. Syntax: math.identity(n) math.identity(n, format) math.identity(m, n) math.identity(m, n, format) math.identity([m, n]) math.identity([m, n], format) Examples: math.identity...
_identityVector
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _identity(rows, cols, format) { // BigNumber constructor with the right precision var Big = type.isBigNumber(rows) || type.isBigNumber(cols) ? type.BigNumber : null; if (type.isBigNumber(rows)) rows = rows.toNumber(); if (type.isBigNumber(cols)) cols = cols.toNumber(); if (!isInteger(rows)...
Create an identity matrix @param {number | BigNumber} rows @param {number | BigNumber} cols @param {string} [format] @returns {Matrix} @private
_identity
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function getPrecedence(_node, parenthesis) { var node = _node; if (parenthesis !== 'keep') { // ParenthesisNodes are only ignored when not in 'keep' mode node = _node.getContent(); } var identifier = node.getIdentifier(); for (var i = 0; i < properties.length; i++) { if (identifier in propertie...
Get the precedence of a Node. Higher number for higher precedence, starting with 0. Returns null if the precedence is undefined. @param {Node} @param {string} parenthesis @return {number|null}
getPrecedence
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function getAssociativity(_node, parenthesis) { var node = _node; if (parenthesis !== 'keep') { // ParenthesisNodes are only ignored when not in 'keep' mode node = _node.getContent(); } var identifier = node.getIdentifier(); var index = getPrecedence(node, parenthesis); if (index === null) { ...
Get the associativity of an operator (left or right). Returns a string containing 'left' or 'right' or null if the associativity is not defined. @param {Node} @param {string} parenthesis @return {string|null} @throws {Error}
getAssociativity
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function isAssociativeWith(nodeA, nodeB, parenthesis) { // ParenthesisNodes are only ignored when not in 'keep' mode var a = parenthesis !== 'keep' ? nodeA.getContent() : nodeA; var b = parenthesis !== 'keep' ? nodeA.getContent() : nodeB; var identifierA = a.getIdentifier(); var identifierB = b.getIdentifier(...
Check if an operator is associative with another operator. Returns either true or false or null if not defined. @param {Node} nodeA @param {Node} nodeB @param {string} parenthesis @return {bool|null}
isAssociativeWith
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function isValuelessUnit(name) { return type.Unit ? type.Unit.isValuelessUnit(name) : false; }
Check whether some name is a valueless unit like "inch". @param {string} name @return {boolean}
isValuelessUnit
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function SymbolNode(name) { if (!(this instanceof SymbolNode)) { throw new SyntaxError('Constructor must be called with the new operator'); } // validate input if (typeof name !== 'string') throw new TypeError('String expected for parameter "name"'); this.name = name; }
@constructor SymbolNode @extends {Node} A symbol node can hold and resolve a symbol @param {string} name @extends {Node}
SymbolNode
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function undef(name) { throw new Error('Undefined symbol ' + name); }
Throws an error 'Undefined symbol {name}' @param {string} name
undef
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
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 + ' (' + ...
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 coun...
ArgumentsError
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function ConstantNode(value) { if (!(this instanceof ConstantNode)) { throw new SyntaxError('Constructor must be called with the new operator'); } if (arguments.length === 2) { // TODO: remove deprecation error some day (created 2018-01-23) throw new SyntaxError('new ConstantNode(valueStr...
A ConstantNode holds a constant value like a number or string. Usage: new ConstantNode(2.3) new ConstantNode('hello') @param {*} value Value can be any type (number, BigNumber, string, ...) @constructor ConstantNode @extends {Node}
ConstantNode
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function OperatorNode(op, fn, args, implicit) { if (!(this instanceof OperatorNode)) { throw new SyntaxError('Constructor must be called with the new operator'); } // validate input if (typeof op !== 'string') { throw new TypeError('string expected for parameter "op"'); } if (typeof f...
@constructor OperatorNode @extends {Node} An operator with two arguments, like 2+3 @param {string} op Operator name, for example '+' @param {string} fn Function name, for example 'add' @param {Node[]} args Operator arguments @param {boolean} [implicit] Is this an implicit multiplication?
OperatorNode
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function calculateNecessaryParentheses(root, parenthesis, implicit, args, latex) { // precedence of the root OperatorNode var precedence = operators.getPrecedence(root, parenthesis); var associativity = operators.getAssociativity(root, parenthesis); if (parenthesis === 'all' || args.length > 2 && root....
Calculate which parentheses are necessary. Gets an OperatorNode (which is the root of the tree) and an Array of Nodes (this.args) and returns an array where 'true' means that an argument has to be enclosed in parentheses whereas 'false' means the opposite. @param {OperatorNode} root @param {string} parenthesis @param ...
calculateNecessaryParentheses
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
numeric = function numeric(value, outputType) { var inputType = getTypeOf(value); if (!(inputType in validInputTypes)) { throw new TypeError('Cannot convert ' + value + ' of type "' + inputType + '"; valid input types are ' + Object.keys(validInputTypes).join(', ')); } if (!(outputType in validO...
Convert a numeric value to a specific type: number, BigNumber, or Fraction @param {string | number | BigNumber | Fraction } value @param {'number' | 'BigNumber' | 'Fraction'} outputType @return {number | BigNumber | Fraction} Returns an instance of the numeric in the requested t...
numeric
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _round(value, decimals) { return parseFloat(toFixed(value, decimals)); }
round a number to the given number of decimals, or to zero if decimals is not provided @param {number} value @param {number} decimals number of decimals, between 0 and 15 (0 by default) @return {number} roundedValue @private
_round
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function ParenthesisNode(content) { if (!(this instanceof ParenthesisNode)) { throw new SyntaxError('Constructor must be called with the new operator'); } // validate input if (!type.isNode(content)) { throw new TypeError('Node expected for parameter "content"'); } this.content = cont...
@constructor ParenthesisNode @extends {Node} A parenthesis node describes manual parenthesis from the user input @param {Node} content @extends {Node}
ParenthesisNode
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function FunctionNode(fn, args) { if (!(this instanceof FunctionNode)) { throw new SyntaxError('Constructor must be called with the new operator'); } if (typeof fn === 'string') { fn = new SymbolNode(fn); } // validate input if (!type.isNode(fn)) throw new TypeError('Node expected as ...
@constructor FunctionNode @extends {./Node} invoke a list with arguments on a node @param {./Node | string} fn Node resolving with a function on which to invoke the arguments, typically a SymboNode or AccessorNode @param {./Node[]} args
FunctionNode
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
deprecated = function deprecated() { throw new Error('Property `FunctionNode.object` is deprecated, use `FunctionNode.fn` instead'); }
@constructor FunctionNode @extends {./Node} invoke a list with arguments on a node @param {./Node | string} fn Node resolving with a function on which to invoke the arguments, typically a SymboNode or AccessorNode @param {./Node[]} args
deprecated
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function expandTemplate(template, node, options) { var latex = ''; // Match everything of the form ${identifier} or ${identifier[2]} or $$ // while submatching identifier and 2 (in the second case) var regex = new RegExp('\\$(?:\\{([a-z_][a-z_0-9]*)(?:\\[([0-9]+)\\])?\\}|\\$)', 'ig'); var inputPos = 0;...
Get HTML representation @param {Object} options @return {string} str
expandTemplate
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _inv(mat, rows, cols) { var r, s, f, value, temp; if (rows === 1) { // this is a 1 x 1 matrix value = mat[0][0]; if (value === 0) { throw Error('Cannot calculate inverse, determinant is zero'); } return [[divideScalar(1, value)]]; } else if (rows === 2) { ...
Calculate the inverse of a square matrix @param {Array[]} mat A square matrix @param {number} rows Number of rows @param {number} cols Number of columns, must equal rows @return {Array[]} inv Inverse matrix @private
_inv
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _denseTranspose(m, rows, columns) { // matrix array var data = m._data; // transposed matrix data var transposed = []; var transposedRow; // loop columns for (var j = 0; j < columns; j++) { // initialize row transposedRow = transposed[j] = []; // loop rows for (var i = ...
Transpose a matrix. All values of the matrix are reflected over its main diagonal. Only applicable to two dimensional matrices containing a vector (i.e. having size `[1,n]` or `[n,1]`). One dimensional vectors and scalars return the input unchanged. Syntax: math.transpose(x) Examples: const A = [[1, 2, 3], ...
_denseTranspose
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _sparseTranspose(m, rows, columns) { // matrix arrays var values = m._values; var index = m._index; var ptr = m._ptr; // result matrices var cvalues = values ? [] : undefined; var cindex = []; var cptr = []; // row counts var w = []; for (var x = 0; x < rows; x++) { ...
Transpose a matrix. All values of the matrix are reflected over its main diagonal. Only applicable to two dimensional matrices containing a vector (i.e. having size `[1,n]` or `[n,1]`). One dimensional vectors and scalars return the input unchanged. Syntax: math.transpose(x) Examples: const A = [[1, 2, 3], ...
_sparseTranspose
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function isPositiveInteger(n) { return n.isInteger() && n.gte(0); }
Test whether BigNumber n is a positive integer @param {BigNumber} n @returns {boolean} isPositiveInteger
isPositiveInteger
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _out(arr) { return config.matrix === 'Array' ? arr : matrix(arr); }
Create an array from a range. By default, the range end is excluded. This can be customized by providing an extra parameter `includeEnd`. Syntax: math.range(str [, includeEnd]) // Create a range from a string, // where the string contains the ...
_out
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _strRange(str, includeEnd) { var r = _parse(str); if (!r) { throw new SyntaxError('String "' + str + '" is no valid range'); } var fn; if (config.number === 'BigNumber') { fn = includeEnd ? _bigRangeInc : _bigRangeEx; return _out(fn(new type.BigNumber(r.start), new type...
Create an array from a range. By default, the range end is excluded. This can be customized by providing an extra parameter `includeEnd`. Syntax: math.range(str [, includeEnd]) // Create a range from a string, // where the string contains the ...
_strRange
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _rangeEx(start, end, step) { var array = []; var x = start; if (step > 0) { while (smaller(x, end)) { array.push(x); x += step; } } else if (step < 0) { while (larger(x, end)) { array.push(x); x += step; } } return array; }
Create a range with numbers. End is excluded @param {number} start @param {number} end @param {number} step @returns {Array} range @private
_rangeEx
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _rangeInc(start, end, step) { var array = []; var x = start; if (step > 0) { while (smallerEq(x, end)) { array.push(x); x += step; } } else if (step < 0) { while (largerEq(x, end)) { array.push(x); x += step; } } return array; ...
Create a range with numbers. End is included @param {number} start @param {number} end @param {number} step @returns {Array} range @private
_rangeInc
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _bigRangeEx(start, end, step) { var array = []; var x = start; if (step.gt(ZERO)) { while (smaller(x, end)) { array.push(x); x = x.plus(step); } } else if (step.lt(ZERO)) { while (larger(x, end)) { array.push(x); x = x.plus(step); } }...
Create a range with big numbers. End is excluded @param {BigNumber} start @param {BigNumber} end @param {BigNumber} step @returns {Array} range @private
_bigRangeEx
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _bigRangeInc(start, end, step) { var array = []; var x = start; if (step.gt(ZERO)) { while (smallerEq(x, end)) { array.push(x); x = x.plus(step); } } else if (step.lt(ZERO)) { while (largerEq(x, end)) { array.push(x); x = x.plus(step); } ...
Create a range with big numbers. End is included @param {BigNumber} start @param {BigNumber} end @param {BigNumber} step @returns {Array} range @private
_bigRangeInc
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _parse(str) { var args = str.split(':'); // number var nums = args.map(function (arg) { // use Number and not parseFloat as Number returns NaN on invalid garbage in the string return Number(arg); }); var invalid = nums.some(function (num) { return isNaN(num); }); if ...
Parse a string into a range, The string contains the start, optional step, and end, separated by a colon. If the string does not contain a valid range, null is returned. For example str='0:2:11'. @param {string} str @return {{start: number, end: number, step: number} | null} range Object containing properties start, en...
_parse
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _concat(a, b, concatDim, dim) { if (dim < concatDim) { // recurse into next dimension if (a.length !== b.length) { throw new DimensionError(a.length, b.length); } var c = []; for (var i = 0; i < a.length; i++) { c[i] = _concat(a[i], b[i], concatDim, dim + 1); } retu...
Recursively concatenate two matrices. The contents of the matrices is not cloned. @param {Array} a Multi dimensional array @param {Array} b Multi dimensional array @param {number} concatDim The dimension on which to concatenate (zero-based) @param {number} dim The current dim (zero-b...
_concat
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _reduce(mat, dim, callback) { var i, ret, val, tran; if (dim <= 0) { if (!Array.isArray(mat[0])) { val = mat[0]; for (i = 1; i < mat.length; i++) { val = callback(val, mat[i]); } return val; } else { tran = _switch(mat); ret = []; for (i = 0; i ...
Recursively reduce a matrix @param {Array} mat @param {number} dim @param {Function} callback @returns {Array} ret @private
_reduce
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _switch(mat) { var I = mat.length; var J = mat[0].length; var i, j; var ret = []; for (j = 0; j < J; j++) { var tmp = []; for (i = 0; i < I; i++) { tmp.push(mat[i][j]); } ret.push(tmp); } return ret; }
Transpose a matrix @param {Array} mat @returns {Array} ret @private
_switch
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function Matrix() { if (!(this instanceof Matrix)) { throw new SyntaxError('Constructor must be called with the new operator'); } }
@constructor Matrix A Matrix is a wrapper around an Array. A matrix can hold a multi dimensional array. A matrix can be constructed as: let matrix = math.matrix(data) Matrix contains the functions to resize, get and set values, get the size, clone the matrix and to convert the matrix to a vector, array, or scala...
Matrix
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function removeParens(node) { return node.transform(function (node, path, parent) { return type.isParenthesisNode(node) ? node.content : node; }); } // All constants that are allowed in rules
Simplify an expression tree. A list of rules are applied to an expression, repeating over the list until no further changes are made. It's possible to pass a custom set of rules to the function as second argument. A rule can be specified as an object, string, or function: const rules = [ { l: 'n1*n3 + n2*n3...
removeParens
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _buildRules(rules) { // Array of rules to be used to simplify expressions var ruleSet = []; for (var i = 0; i < rules.length; i++) { var rule = rules[i]; var newRule = void 0; var ruleType = _typeof(rule); switch (ruleType) { case 'string': var lr = rule...
Parse the string array of rules into nodes Example syntax for rules: Position constants to the left in a product: { l: 'n1 * c1', r: 'c1 * n1' } n1 is any Node, and c1 is a ConstantNode. Apply difference of squares formula: { l: '(n1 - n2) * (n1 + n2)', r: 'n1^2 - n2^2' } n1, n2 mean any Node. Short hand notation: ...
_buildRules
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _getExpandPlaceholderSymbol() { return new SymbolNode('_p' + _lastsym++); }
Parse the string array of rules into nodes Example syntax for rules: Position constants to the left in a product: { l: 'n1 * c1', r: 'c1 * n1' } n1 is any Node, and c1 is a ConstantNode. Apply difference of squares formula: { l: '(n1 - n2) * (n1 + n2)', r: 'n1^2 - n2^2' } n1, n2 mean any Node. Short hand notation: ...
_getExpandPlaceholderSymbol
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
_transform = function _transform(node) { if (node.isSymbolNode && matches.placeholders.hasOwnProperty(node.name)) { return matches.placeholders[node.name].clone(); } else { return node.map(_transform); } }
Returns a simplfied form of node, or the original node if no simplification was possible. @param {ConstantNode | SymbolNode | ParenthesisNode | FunctionNode | OperatorNode} node @return {ConstantNode | SymbolNode | ParenthesisNode | FunctionNode | OperatorNode} The simplified form of `expr`, or the original node if n...
_transform
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function getSplits(node, context) { var res = []; var right, rightArgs; var makeNode = createMakeNodeFunction(node); if (isCommutative(node, context)) { for (var i = 0; i < node.args.length; i++) { rightArgs = node.args.slice(0); rightArgs.splice(i, 1); right = rightArgs.l...
Get (binary) combinations of a flattened binary node e.g. +(node1, node2, node3) -> [ +(node1, +(node2, node3)), +(node2, +(node1, node3)), +(node3, +(node1, node2))]
getSplits
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function mergeMatch(match1, match2) { var res = { placeholders: {} // Some matches may not have placeholders; this is OK }; if (!match1.placeholders && !match2.placeholders) { return res; } else if (!match1.placeholders) { return match2; } else if (!match2.placeholders) { r...
Returns the set union of two match-placeholders or null if there is a conflict.
mergeMatch
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function combineChildMatches(list1, list2) { var res = []; if (list1.length === 0 || list2.length === 0) { return res; } var merged; for (var i1 = 0; i1 < list1.length; i1++) { for (var i2 = 0; i2 < list2.length; i2++) { merged = mergeMatch(list1[i1], list2[i2]); if (...
Combine two lists of matches by applying mergeMatch to the cartesian product of two lists of matches. Each list represents matches found in one child of a node.
combineChildMatches
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function mergeChildMatches(childMatches) { if (childMatches.length === 0) { return childMatches; } var sets = childMatches.reduce(combineChildMatches); var uniqueSets = []; var unique = {}; for (var i = 0; i < sets.length; i++) { var s = JSON.stringify(sets[i]); if (!unique[...
Combine multiple lists of matches by applying mergeMatch to the cartesian product of two lists of matches. Each list represents matches found in one child of a node. Returns a list of unique matches.
mergeChildMatches
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _ruleMatch(rule, node, isSplit) { // console.log('Entering _ruleMatch(' + JSON.stringify(rule) + ', ' + JSON.stringify(node) + ')') // console.log('rule = ' + rule) // console.log('node = ' + node) // console.log('Entering _ruleMatch(' + rule.toString() + ', ' + node.toString() + ')...
Determines whether node matches rule. @param {ConstantNode | SymbolNode | ParenthesisNode | FunctionNode | OperatorNode} rule @param {ConstantNode | SymbolNode | ParenthesisNode | FunctionNode | OperatorNode} node @return {Object} Information about the match, if it exists.
_ruleMatch
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _exactMatch(p, q) { if (p instanceof ConstantNode && q instanceof ConstantNode) { if (!equal(p.value, q.value)) { return false; } } else if (p instanceof SymbolNode && q instanceof SymbolNode) { if (p.name !== q.name) { return false; } } else if (p instanceof...
Determines whether p and q (and all their children nodes) are identical. @param {ConstantNode | SymbolNode | ParenthesisNode | FunctionNode | OperatorNode} p @param {ConstantNode | SymbolNode | ParenthesisNode | FunctionNode | OperatorNode} q @return {Object} Information about the match, if it exists.
_exactMatch
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _denseLUP(m) { // rows & columns var rows = m._size[0]; var columns = m._size[1]; // minimum rows and columns var n = Math.min(rows, columns); // matrix array, clone original data var data = object.clone(m._data); // l matrix arrays var ldata = []; var lsize = [rows, n]; // u mat...
Calculate the Matrix LU decomposition with partial pivoting. Matrix `A` is decomposed in two matrices (`L`, `U`) and a row permutation vector `p` where `A[p,:] = L * U` Syntax: math.lup(A) Example: const m = [[2, 1], [1, 4]] const r = math.lup(m) // r = { // L: [[1, 0], [0.5, 1]], // U: [[2, 1...
_denseLUP
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _sparseLUP(m) { // rows & columns var rows = m._size[0]; var columns = m._size[1]; // minimum rows and columns var n = Math.min(rows, columns); // matrix arrays (will not be modified, thanks to permutation vector) var values = m._values; var index = m._index; var ptr = m._ptr; // ...
Calculate the Matrix LU decomposition with partial pivoting. Matrix `A` is decomposed in two matrices (`L`, `U`) and a row permutation vector `p` where `A[p,:] = L * U` Syntax: math.lup(A) Example: const m = [[2, 1], [1, 4]] const r = math.lup(m) // r = { // L: [[1, 0], [0.5, 1]], // U: [[2, 1...
_sparseLUP
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
swapIndeces = function swapIndeces(x, y) { // find pv indeces getting data from x and y var kx = pvOc[x]; var ky = pvOc[y]; // update permutation vector current -> original pvCo[kx] = y; pvCo[ky] = x; // update permutation vector original -> current pvOc[x] = ky; pvOc[y] = kx...
Calculate the Matrix LU decomposition with partial pivoting. Matrix `A` is decomposed in two matrices (`L`, `U`) and a row permutation vector `p` where `A[p,:] = L * U` Syntax: math.lup(A) Example: const m = [[2, 1], [1, 4]] const r = math.lup(m) // r = { // L: [[1, 0], [0.5, 1]], // U: [[2, 1...
swapIndeces
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
_loop = function _loop() { // sparse accumulator var spa = new Spa(); // check lower triangular matrix has a value @ column j if (j < rows) { // update ptr lptr.push(lvalues.length); // first value in j column for lower triangular matrix lvalues.push(1); lindex.push(j...
Calculate the Matrix LU decomposition with partial pivoting. Matrix `A` is decomposed in two matrices (`L`, `U`) and a row permutation vector `p` where `A[p,:] = L * U` Syntax: math.lup(A) Example: const m = [[2, 1], [1, 4]] const r = math.lup(m) // r = { // L: [[1, 0], [0.5, 1]], // U: [[2, 1...
_loop
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
csFlip = function csFlip(i) { // flip the value return -i - 2; }
This function "flips" its input about the integer -1. @param {Number} i The value to flip Reference: http://faculty.cse.tamu.edu/davis/publications.html
csFlip
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
solveValidation = function solveValidation(m, b, copy) { // matrix size var size = m.size(); // validate matrix dimensions if (size.length !== 2) { throw new RangeError('Matrix must be two dimensional (size: ' + string.format(size) + ')'); } // rows & columns var rows = size[0]; var col...
Validates matrix and column vector b for backward/forward substitution algorithms. @param {Matrix} m An N x N matrix @param {Array | Matrix} b A column vector @param {Boolean} copy Return a copy of vector b @return {DenseMatrix} Dense column vector b
solveValidation
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function decCoefficientToBinaryString(x) { // Convert to string var a = x.d; // array with digits var r = a[0] + ''; for (var i = 1; i < a.length; ++i) { var s = a[i] + ''; for (var z = 7 - s.length; z--;) { s = '0' + s; } r += s; } var j = r.length; while (r.charAt(j) === '0')...
Applies bitwise function to numbers @param {BigNumber} x @param {BigNumber} y @param {function (a, b)} func @return {BigNumber}
decCoefficientToBinaryString
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function product(i, n) { var half; if (n < i) { return 1; } if (n === i) { return n; } half = n + i >> 1; // divide (n + i) by 2 and truncate to integer return product(i, half) * product(half + 1, n); }
@param {integer} i @param {integer} n @returns : product of i to n
product
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _apply(mat, dim, callback) { var i, ret, tran; if (dim <= 0) { if (!Array.isArray(mat[0])) { return callback(mat); } else { tran = _switch(mat); ret = []; for (i = 0; i < tran.length; i++) { ret[i] = _apply(tran[i], dim - 1, callback); } return ret; ...
Recursively reduce a matrix @param {Array} mat @param {number} dim @param {Function} callback @returns {Array} ret @private
_apply
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _switch(mat) { var I = mat.length; var J = mat[0].length; var i, j; var ret = []; for (j = 0; j < J; j++) { var tmp = []; for (i = 0; i < I; i++) { tmp.push(mat[i][j]); } ret.push(tmp); } return ret; }
Transpose a matrix @param {Array} mat @returns {Array} ret @private
_switch
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _partitionSelect(x, k, compare) { if (!isInteger(k) || k < 0) { throw new Error('k must be a non-negative integer'); } if (type.isMatrix(x)) { var size = x.size(); if (size.length > 1) { throw new Error('Only one dimensional matrices supported'); } return qu...
Partition-based selection of an array or 1D matrix. Will find the kth smallest value, and mutates the input array. Uses Quickselect. Syntax: math.partitionSelect(x, k) math.partitionSelect(x, k, compare) Examples: math.partitionSelect([5, 10, 1], 2) // returns 10 math.partitionSelect(['C', 'B'...
_partitionSelect
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function quickSelect(arr, k, compare) { if (k >= arr.length) { throw new Error('k out of bounds'); } // check for NaN values since these can cause an infinite while loop for (var i = 0; i < arr.length; i++) { if (isNumeric(arr[i]) && isNaN(arr[i])) { return arr[i]; // return NaN ...
Quickselect algorithm. Code adapted from: https://blog.teamleadnet.com/2012/07/quick-select-algorithm-find-kth-element.html @param {Array} arr @param {Number} k @param {Function} compare @private
quickSelect
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _largest(x, y) { try { return larger(x, y) ? x : y; } catch (err) { throw improveErrorMessage(err, 'max', y); } }
Return the largest of two values @param {*} x @param {*} y @returns {*} Returns x when x is largest, or y when y is largest @private
_largest
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _max(array) { var max; deepForEach(array, function (value) { try { if (isNaN(value) && typeof value === 'number') { max = NaN; } else if (max === undefined || larger(value, max)) { max = value; } } catch (err) { throw improveErrorMessage(e...
Recursively calculate the maximum value in an n-dimensional array @param {Array} array @return {number} max @private
_max
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _sum(array) { var sum; deepForEach(array, function (value) { try { sum = sum === undefined ? value : add(sum, value); } catch (err) { throw improveErrorMessage(err, 'sum', value); } }); if (sum === undefined) { switch (config.number) { case 'numb...
Recursively calculate the sum of an n-dimensional array @param {Array} array @return {number} sum @private
_sum
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _nsumDim(array, dim) { try { var _sum2 = reduce(array, dim, add); return _sum2; } catch (err) { throw improveErrorMessage(err, 'sum'); } }
Recursively calculate the sum of an n-dimensional array @param {Array} array @return {number} sum @private
_nsumDim
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function distribution(name) { if (!distributions.hasOwnProperty(name)) { throw new Error('Unknown distribution ' + name); } var args = Array.prototype.slice.call(arguments, 1); var distribution = distributions[name].apply(this, args); return function (distribution) { // This is the publ...
Create a distribution object with a set of random functions for given random distribution. Syntax: math.distribution(name) Examples: const normalDist = math.distribution('normal') // create a normal distribution normalDist.random(0, 10) // get a random value between 0 and 10 See als...
distribution
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _pickRandom(possibles, number, weights) { var single = typeof number === 'undefined'; if (single) { number = 1; } if (type.isMatrix(possibles)) { possibles = possibles.valueOf(); // get Array } else if (!Array.isArray(possibles)) { throw n...
Create a distribution object with a set of random functions for given random distribution. Syntax: math.distribution(name) Examples: const normalDist = math.distribution('normal') // create a normal distribution normalDist.random(0, 10) // get a random value between 0 and 10 See als...
_pickRandom
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _random(min, max) { return min + distribution() * (max - min); }
Create a distribution object with a set of random functions for given random distribution. Syntax: math.distribution(name) Examples: const normalDist = math.distribution('normal') // create a normal distribution normalDist.random(0, 10) // get a random value between 0 and 10 See als...
_random
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _randomInt(min, max) { return Math.floor(min + distribution() * (max - min)); } // This is a function for generating a random matrix recursively.
Create a distribution object with a set of random functions for given random distribution. Syntax: math.distribution(name) Examples: const normalDist = math.distribution('normal') // create a normal distribution normalDist.random(0, 10) // get a random value between 0 and 10 See als...
_randomInt
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _randomDataForMatrix(size, min, max, randFunc) { var data = []; size = size.slice(0); if (size.length > 1) { for (var i = 0, length = size.shift(); i < length; i++) { data.push(_randomDataForMatrix(size, min, max, randFunc)); } } else { ...
Create a distribution object with a set of random functions for given random distribution. Syntax: math.distribution(name) Examples: const normalDist = math.distribution('normal') // create a normal distribution normalDist.random(0, 10) // get a random value between 0 and 10 See als...
_randomDataForMatrix
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _var(array, normalization) { var sum = 0; var num = 0; if (array.length === 0) { throw new SyntaxError('Function var requires one or more parameters (0 provided)'); } // calculate the mean and number of elements deepForEach(array, function (value) { try { sum = add(su...
Recursively calculate the variance of an n-dimensional array @param {Array} array @param {string} normalization Determines how to normalize the variance: - 'unbiased' The sum of squared errors is divided by (n - 1) - 'uncorrected' The sum of square...
_var
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _varDim(array, dim, normalization) { try { if (array.length === 0) { throw new SyntaxError('Function var requires one or more parameters (0 provided)'); } return apply(array, dim, function (x) { return _var(x, normalization); }); } catch (err) { throw impr...
Recursively calculate the variance of an n-dimensional array @param {Array} array @param {string} normalization Determines how to normalize the variance: - 'unbiased' The sum of squared errors is divided by (n - 1) - 'uncorrected' The sum of square...
_varDim
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function Range(start, end, step) { if (!(this instanceof Range)) { throw new SyntaxError('Constructor must be called with the new operator'); } var hasStart = start !== null && start !== undefined; var hasEnd = end !== null && end !== undefined; var hasStep = step !== null && step !== undefin...
Create a range. A range has a start, step, and end, and contains functions to iterate over the range. A range can be constructed as: const range = new Range(start, end) const range = new Range(start, end, step) To get the result of the range: range.forEach(function (x) { console.log(x) }) ...
Range
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function ResultSet(entries) { if (!(this instanceof ResultSet)) { throw new SyntaxError('Constructor must be called with the new operator'); } this.entries = entries || []; }
A ResultSet contains a list or results @class ResultSet @param {Array} entries @constructor ResultSet
ResultSet
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT