UNPKG

1.87 MBJavaScriptView Raw
1/**
2 * math.js
3 * https://github.com/josdejong/mathjs
4 *
5 * Math.js is an extensive math library for JavaScript and Node.js,
6 * It features real and complex numbers, units, matrices, a large set of
7 * mathematical functions, and a flexible expression parser.
8 *
9 * @version 6.2.3
10 * @date 2019-10-06
11 *
12 * @license
13 * Copyright (C) 2013-2019 Jos de Jong <wjosdejong@gmail.com>
14 *
15 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
16 * use this file except in compliance with the License. You may obtain a copy
17 * of the License at
18 *
19 * https://www.apache.org/licenses/LICENSE-2.0
20 *
21 * Unless required by applicable law or agreed to in writing, software
22 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
23 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
24 * License for the specific language governing permissions and limitations under
25 * the License.
26 */
27
28(function webpackUniversalModuleDefinition(root, factory) {
29 if(typeof exports === 'object' && typeof module === 'object')
30 module.exports = factory();
31 else if(typeof define === 'function' && define.amd)
32 define([], factory);
33 else if(typeof exports === 'object')
34 exports["math"] = factory();
35 else
36 root["math"] = factory();
37})(this, function() {
38return /******/ (function(modules) { // webpackBootstrap
39/******/ // The module cache
40/******/ var installedModules = {};
41/******/
42/******/ // The require function
43/******/ function __webpack_require__(moduleId) {
44/******/
45/******/ // Check if module is in cache
46/******/ if(installedModules[moduleId]) {
47/******/ return installedModules[moduleId].exports;
48/******/ }
49/******/ // Create a new module (and put it into the cache)
50/******/ var module = installedModules[moduleId] = {
51/******/ i: moduleId,
52/******/ l: false,
53/******/ exports: {}
54/******/ };
55/******/
56/******/ // Execute the module function
57/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
58/******/
59/******/ // Flag the module as loaded
60/******/ module.l = true;
61/******/
62/******/ // Return the exports of the module
63/******/ return module.exports;
64/******/ }
65/******/
66/******/
67/******/ // expose the modules object (__webpack_modules__)
68/******/ __webpack_require__.m = modules;
69/******/
70/******/ // expose the module cache
71/******/ __webpack_require__.c = installedModules;
72/******/
73/******/ // define getter function for harmony exports
74/******/ __webpack_require__.d = function(exports, name, getter) {
75/******/ if(!__webpack_require__.o(exports, name)) {
76/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
77/******/ }
78/******/ };
79/******/
80/******/ // define __esModule on exports
81/******/ __webpack_require__.r = function(exports) {
82/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
83/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
84/******/ }
85/******/ Object.defineProperty(exports, '__esModule', { value: true });
86/******/ };
87/******/
88/******/ // create a fake namespace object
89/******/ // mode & 1: value is a module id, require it
90/******/ // mode & 2: merge all properties of value into the ns
91/******/ // mode & 4: return value when already ns object
92/******/ // mode & 8|1: behave like require
93/******/ __webpack_require__.t = function(value, mode) {
94/******/ if(mode & 1) value = __webpack_require__(value);
95/******/ if(mode & 8) return value;
96/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
97/******/ var ns = Object.create(null);
98/******/ __webpack_require__.r(ns);
99/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
100/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
101/******/ return ns;
102/******/ };
103/******/
104/******/ // getDefaultExport function for compatibility with non-harmony modules
105/******/ __webpack_require__.n = function(module) {
106/******/ var getter = module && module.__esModule ?
107/******/ function getDefault() { return module['default']; } :
108/******/ function getModuleExports() { return module; };
109/******/ __webpack_require__.d(getter, 'a', getter);
110/******/ return getter;
111/******/ };
112/******/
113/******/ // Object.prototype.hasOwnProperty.call
114/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
115/******/
116/******/ // __webpack_public_path__
117/******/ __webpack_require__.p = "";
118/******/
119/******/
120/******/ // Load entry module and return exports
121/******/ return __webpack_require__(__webpack_require__.s = 19);
122/******/ })
123/************************************************************************/
124/******/ ([
125/* 0 */
126/***/ (function(module, __webpack_exports__, __webpack_require__) {
127
128"use strict";
129/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return factory; });
130/* unused harmony export sortFactories */
131/* unused harmony export create */
132/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return isFactory; });
133/* unused harmony export assertDependencies */
134/* unused harmony export isOptionalDependency */
135/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return stripOptionalNotation; });
136/* harmony import */ var _array__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(2);
137/* harmony import */ var _object__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
138
139
140/**
141 * Create a factory function, which can be used to inject dependencies.
142 *
143 * The created functions are memoized, a consecutive call of the factory
144 * with the exact same inputs will return the same function instance.
145 * The memoized cache is exposed on `factory.cache` and can be cleared
146 * if needed.
147 *
148 * Example:
149 *
150 * const name = 'log'
151 * const dependencies = ['config', 'typed', 'divideScalar', 'Complex']
152 *
153 * export const createLog = factory(name, dependencies, ({ typed, config, divideScalar, Complex }) => {
154 * // ... create the function log here and return it
155 * }
156 *
157 * @param {string} name Name of the function to be created
158 * @param {string[]} dependencies The names of all required dependencies
159 * @param {function} create Callback function called with an object with all dependencies
160 * @param {Object} [meta] Optional object with meta information that will be attached
161 * to the created factory function as property `meta`.
162 * @returns {function}
163 */
164
165function factory(name, dependencies, create, meta) {
166 function assertAndCreate(scope) {
167 // we only pass the requested dependencies to the factory function
168 // to prevent functions to rely on dependencies that are not explicitly
169 // requested.
170 var deps = Object(_object__WEBPACK_IMPORTED_MODULE_1__[/* pickShallow */ "j"])(scope, dependencies.map(stripOptionalNotation));
171 assertDependencies(name, dependencies, scope);
172 return create(deps);
173 }
174
175 assertAndCreate.isFactory = true;
176 assertAndCreate.fn = name;
177 assertAndCreate.dependencies = dependencies.slice().sort();
178
179 if (meta) {
180 assertAndCreate.meta = meta;
181 }
182
183 return assertAndCreate;
184}
185/**
186 * Sort all factories such that when loading in order, the dependencies are resolved.
187 *
188 * @param {Array} factories
189 * @returns {Array} Returns a new array with the sorted factories.
190 */
191
192function sortFactories(factories) {
193 var factoriesByName = {};
194 factories.forEach(function (factory) {
195 factoriesByName[factory.fn] = factory;
196 });
197
198 function containsDependency(factory, dependency) {
199 // TODO: detect circular references
200 if (isFactory(factory)) {
201 if (Object(_array__WEBPACK_IMPORTED_MODULE_0__[/* contains */ "b"])(factory.dependencies, dependency.fn || dependency.name)) {
202 return true;
203 }
204
205 if (factory.dependencies.some(function (d) {
206 return containsDependency(factoriesByName[d], dependency);
207 })) {
208 return true;
209 }
210 }
211
212 return false;
213 }
214
215 var sorted = [];
216
217 function addFactory(factory) {
218 var index = 0;
219
220 while (index < sorted.length && !containsDependency(sorted[index], factory)) {
221 index++;
222 }
223
224 sorted.splice(index, 0, factory);
225 } // sort regular factory functions
226
227
228 factories.filter(isFactory).forEach(addFactory); // sort legacy factory functions AFTER the regular factory functions
229
230 factories.filter(function (factory) {
231 return !isFactory(factory);
232 }).forEach(addFactory);
233 return sorted;
234} // TODO: comment or cleanup if unused in the end
235
236function create(factories) {
237 var scope = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
238 sortFactories(factories).forEach(function (factory) {
239 return factory(scope);
240 });
241 return scope;
242}
243/**
244 * Test whether an object is a factory. This is the case when it has
245 * properties name, dependencies, and a function create.
246 * @param {*} obj
247 * @returns {boolean}
248 */
249
250function isFactory(obj) {
251 return typeof obj === 'function' && typeof obj.fn === 'string' && Array.isArray(obj.dependencies);
252}
253/**
254 * Assert that all dependencies of a list with dependencies are available in the provided scope.
255 *
256 * Will throw an exception when there are dependencies missing.
257 *
258 * @param {string} name Name for the function to be created. Used to generate a useful error message
259 * @param {string[]} dependencies
260 * @param {Object} scope
261 */
262
263function assertDependencies(name, dependencies, scope) {
264 var allDefined = dependencies.filter(function (dependency) {
265 return !isOptionalDependency(dependency);
266 }) // filter optionals
267 .every(function (dependency) {
268 return scope[dependency] !== undefined;
269 });
270
271 if (!allDefined) {
272 var missingDependencies = dependencies.filter(function (dependency) {
273 return scope[dependency] === undefined;
274 }); // TODO: create a custom error class for this, a MathjsError or something like that
275
276 throw new Error("Cannot create function \"".concat(name, "\", ") + "some dependencies are missing: ".concat(missingDependencies.map(function (d) {
277 return "\"".concat(d, "\"");
278 }).join(', '), "."));
279 }
280}
281function isOptionalDependency(dependency) {
282 return dependency && dependency[0] === '?';
283}
284function stripOptionalNotation(dependency) {
285 return dependency && dependency[0] === '?' ? dependency.slice(1) : dependency;
286}
287
288/***/ }),
289/* 1 */
290/***/ (function(module, __webpack_exports__, __webpack_require__) {
291
292"use strict";
293/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "y", function() { return isNumber; });
294/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return isBigNumber; });
295/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "j", function() { return isComplex; });
296/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "o", function() { return isFraction; });
297/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "L", function() { return isUnit; });
298/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "I", function() { return isString; });
299/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return isArray; });
300/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "v", function() { return isMatrix; });
301/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "i", function() { return isCollection; });
302/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "n", function() { return isDenseMatrix; });
303/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "H", function() { return isSparseMatrix; });
304/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "D", function() { return isRange; });
305/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "t", function() { return isIndex; });
306/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "g", function() { return isBoolean; });
307/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "G", function() { return isResultSet; });
308/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "s", function() { return isHelp; });
309/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "p", function() { return isFunction; });
310/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "m", function() { return isDate; });
311/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "F", function() { return isRegExp; });
312/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "z", function() { return isObject; });
313/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "x", function() { return isNull; });
314/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "K", function() { return isUndefined; });
315/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return isAccessorNode; });
316/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return isArrayNode; });
317/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return isAssignmentNode; });
318/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "f", function() { return isBlockNode; });
319/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "k", function() { return isConditionalNode; });
320/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "l", function() { return isConstantNode; });
321/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "q", function() { return isFunctionAssignmentNode; });
322/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "r", function() { return isFunctionNode; });
323/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "u", function() { return isIndexNode; });
324/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "w", function() { return isNode; });
325/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "A", function() { return isObjectNode; });
326/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "B", function() { return isOperatorNode; });
327/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "C", function() { return isParenthesisNode; });
328/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "E", function() { return isRangeNode; });
329/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "J", function() { return isSymbolNode; });
330/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "h", function() { return isChain; });
331/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "M", function() { return typeOf; });
332function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
333
334// type checks for all known types
335//
336// note that:
337//
338// - check by duck-typing on a property like `isUnit`, instead of checking instanceof.
339// instanceof cannot be used because that would not allow to pass data from
340// one instance of math.js to another since each has it's own instance of Unit.
341// - check the `isUnit` property via the constructor, so there will be no
342// matches for "fake" instances like plain objects with a property `isUnit`.
343// That is important for security reasons.
344// - It must not be possible to override the type checks used internally,
345// for security reasons, so these functions are not exposed in the expression
346// parser.
347function isNumber(x) {
348 return typeof x === 'number';
349}
350function isBigNumber(x) {
351 return x && x.constructor.prototype.isBigNumber === true || false;
352}
353function isComplex(x) {
354 return x && _typeof(x) === 'object' && Object.getPrototypeOf(x).isComplex === true || false;
355}
356function isFraction(x) {
357 return x && _typeof(x) === 'object' && Object.getPrototypeOf(x).isFraction === true || false;
358}
359function isUnit(x) {
360 return x && x.constructor.prototype.isUnit === true || false;
361}
362function isString(x) {
363 return typeof x === 'string';
364}
365var isArray = Array.isArray;
366function isMatrix(x) {
367 return x && x.constructor.prototype.isMatrix === true || false;
368}
369/**
370 * Test whether a value is a collection: an Array or Matrix
371 * @param {*} x
372 * @returns {boolean} isCollection
373 */
374
375function isCollection(x) {
376 return Array.isArray(x) || isMatrix(x);
377}
378function isDenseMatrix(x) {
379 return x && x.isDenseMatrix && x.constructor.prototype.isMatrix === true || false;
380}
381function isSparseMatrix(x) {
382 return x && x.isSparseMatrix && x.constructor.prototype.isMatrix === true || false;
383}
384function isRange(x) {
385 return x && x.constructor.prototype.isRange === true || false;
386}
387function isIndex(x) {
388 return x && x.constructor.prototype.isIndex === true || false;
389}
390function isBoolean(x) {
391 return typeof x === 'boolean';
392}
393function isResultSet(x) {
394 return x && x.constructor.prototype.isResultSet === true || false;
395}
396function isHelp(x) {
397 return x && x.constructor.prototype.isHelp === true || false;
398}
399function isFunction(x) {
400 return typeof x === 'function';
401}
402function isDate(x) {
403 return x instanceof Date;
404}
405function isRegExp(x) {
406 return x instanceof RegExp;
407}
408function isObject(x) {
409 return !!(x && _typeof(x) === 'object' && x.constructor === Object && !isComplex(x) && !isFraction(x));
410}
411function isNull(x) {
412 return x === null;
413}
414function isUndefined(x) {
415 return x === undefined;
416}
417function isAccessorNode(x) {
418 return x && x.isAccessorNode === true && x.constructor.prototype.isNode === true || false;
419}
420function isArrayNode(x) {
421 return x && x.isArrayNode === true && x.constructor.prototype.isNode === true || false;
422}
423function isAssignmentNode(x) {
424 return x && x.isAssignmentNode === true && x.constructor.prototype.isNode === true || false;
425}
426function isBlockNode(x) {
427 return x && x.isBlockNode === true && x.constructor.prototype.isNode === true || false;
428}
429function isConditionalNode(x) {
430 return x && x.isConditionalNode === true && x.constructor.prototype.isNode === true || false;
431}
432function isConstantNode(x) {
433 return x && x.isConstantNode === true && x.constructor.prototype.isNode === true || false;
434}
435function isFunctionAssignmentNode(x) {
436 return x && x.isFunctionAssignmentNode === true && x.constructor.prototype.isNode === true || false;
437}
438function isFunctionNode(x) {
439 return x && x.isFunctionNode === true && x.constructor.prototype.isNode === true || false;
440}
441function isIndexNode(x) {
442 return x && x.isIndexNode === true && x.constructor.prototype.isNode === true || false;
443}
444function isNode(x) {
445 return x && x.isNode === true && x.constructor.prototype.isNode === true || false;
446}
447function isObjectNode(x) {
448 return x && x.isObjectNode === true && x.constructor.prototype.isNode === true || false;
449}
450function isOperatorNode(x) {
451 return x && x.isOperatorNode === true && x.constructor.prototype.isNode === true || false;
452}
453function isParenthesisNode(x) {
454 return x && x.isParenthesisNode === true && x.constructor.prototype.isNode === true || false;
455}
456function isRangeNode(x) {
457 return x && x.isRangeNode === true && x.constructor.prototype.isNode === true || false;
458}
459function isSymbolNode(x) {
460 return x && x.isSymbolNode === true && x.constructor.prototype.isNode === true || false;
461}
462function isChain(x) {
463 return x && x.constructor.prototype.isChain === true || false;
464}
465function typeOf(x) {
466 var t = _typeof(x);
467
468 if (t === 'object') {
469 // JavaScript types
470 if (x === null) return 'null';
471 if (Array.isArray(x)) return 'Array';
472 if (x instanceof Date) return 'Date';
473 if (x instanceof RegExp) return 'RegExp'; // math.js types
474
475 if (isBigNumber(x)) return 'BigNumber';
476 if (isComplex(x)) return 'Complex';
477 if (isFraction(x)) return 'Fraction';
478 if (isMatrix(x)) return 'Matrix';
479 if (isUnit(x)) return 'Unit';
480 if (isIndex(x)) return 'Index';
481 if (isRange(x)) return 'Range';
482 if (isResultSet(x)) return 'ResultSet';
483 if (isNode(x)) return x.type;
484 if (isChain(x)) return 'Chain';
485 if (isHelp(x)) return 'Help';
486 return 'Object';
487 }
488
489 if (t === 'function') return 'Function';
490 return t; // can be 'string', 'number', 'boolean', ...
491}
492
493/***/ }),
494/* 2 */
495/***/ (function(module, __webpack_exports__, __webpack_require__) {
496
497"use strict";
498/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return arraySize; });
499/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "r", function() { return validate; });
500/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "s", function() { return validateIndex; });
501/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "o", function() { return resize; });
502/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "n", function() { return reshape; });
503/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "p", function() { return squeeze; });
504/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "q", function() { return unsqueeze; });
505/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return flatten; });
506/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "m", function() { return map; });
507/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "f", function() { return forEach; });
508/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return filter; });
509/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return filterRegExp; });
510/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "k", function() { return join; });
511/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "i", function() { return identify; });
512/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "g", function() { return generalize; });
513/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "h", function() { return getArrayDataType; });
514/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "l", function() { return last; });
515/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "j", function() { return initial; });
516/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return contains; });
517/* harmony import */ var _number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(4);
518/* harmony import */ var _is__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1);
519/* harmony import */ var _string__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(5);
520/* harmony import */ var _error_DimensionError__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(6);
521/* harmony import */ var _error_IndexError__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(10);
522
523
524
525
526
527/**
528 * Calculate the size of a multi dimensional array.
529 * This function checks the size of the first entry, it does not validate
530 * whether all dimensions match. (use function `validate` for that)
531 * @param {Array} x
532 * @Return {Number[]} size
533 */
534
535function arraySize(x) {
536 var s = [];
537
538 while (Array.isArray(x)) {
539 s.push(x.length);
540 x = x[0];
541 }
542
543 return s;
544}
545/**
546 * Recursively validate whether each element in a multi dimensional array
547 * has a size corresponding to the provided size array.
548 * @param {Array} array Array to be validated
549 * @param {number[]} size Array with the size of each dimension
550 * @param {number} dim Current dimension
551 * @throws DimensionError
552 * @private
553 */
554
555function _validate(array, size, dim) {
556 var i;
557 var len = array.length;
558
559 if (len !== size[dim]) {
560 throw new _error_DimensionError__WEBPACK_IMPORTED_MODULE_3__[/* DimensionError */ "a"](len, size[dim]);
561 }
562
563 if (dim < size.length - 1) {
564 // recursively validate each child array
565 var dimNext = dim + 1;
566
567 for (i = 0; i < len; i++) {
568 var child = array[i];
569
570 if (!Array.isArray(child)) {
571 throw new _error_DimensionError__WEBPACK_IMPORTED_MODULE_3__[/* DimensionError */ "a"](size.length - 1, size.length, '<');
572 }
573
574 _validate(array[i], size, dimNext);
575 }
576 } else {
577 // last dimension. none of the childs may be an array
578 for (i = 0; i < len; i++) {
579 if (Array.isArray(array[i])) {
580 throw new _error_DimensionError__WEBPACK_IMPORTED_MODULE_3__[/* DimensionError */ "a"](size.length + 1, size.length, '>');
581 }
582 }
583 }
584}
585/**
586 * Validate whether each element in a multi dimensional array has
587 * a size corresponding to the provided size array.
588 * @param {Array} array Array to be validated
589 * @param {number[]} size Array with the size of each dimension
590 * @throws DimensionError
591 */
592
593
594function validate(array, size) {
595 var isScalar = size.length === 0;
596
597 if (isScalar) {
598 // scalar
599 if (Array.isArray(array)) {
600 throw new _error_DimensionError__WEBPACK_IMPORTED_MODULE_3__[/* DimensionError */ "a"](array.length, 0);
601 }
602 } else {
603 // array
604 _validate(array, size, 0);
605 }
606}
607/**
608 * Test whether index is an integer number with index >= 0 and index < length
609 * when length is provided
610 * @param {number} index Zero-based index
611 * @param {number} [length] Length of the array
612 */
613
614function validateIndex(index, length) {
615 if (!Object(_is__WEBPACK_IMPORTED_MODULE_1__[/* isNumber */ "y"])(index) || !Object(_number__WEBPACK_IMPORTED_MODULE_0__[/* isInteger */ "i"])(index)) {
616 throw new TypeError('Index must be an integer (value: ' + index + ')');
617 }
618
619 if (index < 0 || typeof length === 'number' && index >= length) {
620 throw new _error_IndexError__WEBPACK_IMPORTED_MODULE_4__[/* IndexError */ "a"](index, length);
621 }
622}
623/**
624 * Resize a multi dimensional array. The resized array is returned.
625 * @param {Array} array Array to be resized
626 * @param {Array.<number>} size Array with the size of each dimension
627 * @param {*} [defaultValue=0] Value to be filled in in new entries,
628 * zero by default. Specify for example `null`,
629 * to clearly see entries that are not explicitly
630 * set.
631 * @return {Array} array The resized array
632 */
633
634function resize(array, size, defaultValue) {
635 // TODO: add support for scalars, having size=[] ?
636 // check the type of the arguments
637 if (!Array.isArray(array) || !Array.isArray(size)) {
638 throw new TypeError('Array expected');
639 }
640
641 if (size.length === 0) {
642 throw new Error('Resizing to scalar is not supported');
643 } // check whether size contains positive integers
644
645
646 size.forEach(function (value) {
647 if (!Object(_is__WEBPACK_IMPORTED_MODULE_1__[/* isNumber */ "y"])(value) || !Object(_number__WEBPACK_IMPORTED_MODULE_0__[/* isInteger */ "i"])(value) || value < 0) {
648 throw new TypeError('Invalid size, must contain positive integers ' + '(size: ' + Object(_string__WEBPACK_IMPORTED_MODULE_2__[/* format */ "d"])(size) + ')');
649 }
650 }); // recursively resize the array
651
652 var _defaultValue = defaultValue !== undefined ? defaultValue : 0;
653
654 _resize(array, size, 0, _defaultValue);
655
656 return array;
657}
658/**
659 * Recursively resize a multi dimensional array
660 * @param {Array} array Array to be resized
661 * @param {number[]} size Array with the size of each dimension
662 * @param {number} dim Current dimension
663 * @param {*} [defaultValue] Value to be filled in in new entries,
664 * undefined by default.
665 * @private
666 */
667
668function _resize(array, size, dim, defaultValue) {
669 var i;
670 var elem;
671 var oldLen = array.length;
672 var newLen = size[dim];
673 var minLen = Math.min(oldLen, newLen); // apply new length
674
675 array.length = newLen;
676
677 if (dim < size.length - 1) {
678 // non-last dimension
679 var dimNext = dim + 1; // resize existing child arrays
680
681 for (i = 0; i < minLen; i++) {
682 // resize child array
683 elem = array[i];
684
685 if (!Array.isArray(elem)) {
686 elem = [elem]; // add a dimension
687
688 array[i] = elem;
689 }
690
691 _resize(elem, size, dimNext, defaultValue);
692 } // create new child arrays
693
694
695 for (i = minLen; i < newLen; i++) {
696 // get child array
697 elem = [];
698 array[i] = elem; // resize new child array
699
700 _resize(elem, size, dimNext, defaultValue);
701 }
702 } else {
703 // last dimension
704 // remove dimensions of existing values
705 for (i = 0; i < minLen; i++) {
706 while (Array.isArray(array[i])) {
707 array[i] = array[i][0];
708 }
709 } // fill new elements with the default value
710
711
712 for (i = minLen; i < newLen; i++) {
713 array[i] = defaultValue;
714 }
715 }
716}
717/**
718 * Re-shape a multi dimensional array to fit the specified dimensions
719 * @param {Array} array Array to be reshaped
720 * @param {Array.<number>} sizes List of sizes for each dimension
721 * @returns {Array} Array whose data has been formatted to fit the
722 * specified dimensions
723 *
724 * @throws {DimensionError} If the product of the new dimension sizes does
725 * not equal that of the old ones
726 */
727
728
729function reshape(array, sizes) {
730 var flatArray = flatten(array);
731 var newArray;
732
733 function product(arr) {
734 return arr.reduce(function (prev, curr) {
735 return prev * curr;
736 });
737 }
738
739 if (!Array.isArray(array) || !Array.isArray(sizes)) {
740 throw new TypeError('Array expected');
741 }
742
743 if (sizes.length === 0) {
744 throw new _error_DimensionError__WEBPACK_IMPORTED_MODULE_3__[/* DimensionError */ "a"](0, product(arraySize(array)), '!=');
745 }
746
747 var totalSize = 1;
748
749 for (var sizeIndex = 0; sizeIndex < sizes.length; sizeIndex++) {
750 totalSize *= sizes[sizeIndex];
751 }
752
753 if (flatArray.length !== totalSize) {
754 throw new _error_DimensionError__WEBPACK_IMPORTED_MODULE_3__[/* DimensionError */ "a"](product(sizes), product(arraySize(array)), '!=');
755 }
756
757 try {
758 newArray = _reshape(flatArray, sizes);
759 } catch (e) {
760 if (e instanceof _error_DimensionError__WEBPACK_IMPORTED_MODULE_3__[/* DimensionError */ "a"]) {
761 throw new _error_DimensionError__WEBPACK_IMPORTED_MODULE_3__[/* DimensionError */ "a"](product(sizes), product(arraySize(array)), '!=');
762 }
763
764 throw e;
765 }
766
767 return newArray;
768}
769/**
770 * Iteratively re-shape a multi dimensional array to fit the specified dimensions
771 * @param {Array} array Array to be reshaped
772 * @param {Array.<number>} sizes List of sizes for each dimension
773 * @returns {Array} Array whose data has been formatted to fit the
774 * specified dimensions
775 */
776
777function _reshape(array, sizes) {
778 // testing if there are enough elements for the requested shape
779 var tmpArray = array;
780 var tmpArray2; // for each dimensions starting by the last one and ignoring the first one
781
782 for (var sizeIndex = sizes.length - 1; sizeIndex > 0; sizeIndex--) {
783 var size = sizes[sizeIndex];
784 tmpArray2 = []; // aggregate the elements of the current tmpArray in elements of the requested size
785
786 var length = tmpArray.length / size;
787
788 for (var i = 0; i < length; i++) {
789 tmpArray2.push(tmpArray.slice(i * size, (i + 1) * size));
790 } // set it as the new tmpArray for the next loop turn or for return
791
792
793 tmpArray = tmpArray2;
794 }
795
796 return tmpArray;
797}
798/**
799 * Squeeze a multi dimensional array
800 * @param {Array} array
801 * @param {Array} [size]
802 * @returns {Array} returns the array itself
803 */
804
805
806function squeeze(array, size) {
807 var s = size || arraySize(array); // squeeze outer dimensions
808
809 while (Array.isArray(array) && array.length === 1) {
810 array = array[0];
811 s.shift();
812 } // find the first dimension to be squeezed
813
814
815 var dims = s.length;
816
817 while (s[dims - 1] === 1) {
818 dims--;
819 } // squeeze inner dimensions
820
821
822 if (dims < s.length) {
823 array = _squeeze(array, dims, 0);
824 s.length = dims;
825 }
826
827 return array;
828}
829/**
830 * Recursively squeeze a multi dimensional array
831 * @param {Array} array
832 * @param {number} dims Required number of dimensions
833 * @param {number} dim Current dimension
834 * @returns {Array | *} Returns the squeezed array
835 * @private
836 */
837
838function _squeeze(array, dims, dim) {
839 var i, ii;
840
841 if (dim < dims) {
842 var next = dim + 1;
843
844 for (i = 0, ii = array.length; i < ii; i++) {
845 array[i] = _squeeze(array[i], dims, next);
846 }
847 } else {
848 while (Array.isArray(array)) {
849 array = array[0];
850 }
851 }
852
853 return array;
854}
855/**
856 * Unsqueeze a multi dimensional array: add dimensions when missing
857 *
858 * Paramter `size` will be mutated to match the new, unqueezed matrix size.
859 *
860 * @param {Array} array
861 * @param {number} dims Desired number of dimensions of the array
862 * @param {number} [outer] Number of outer dimensions to be added
863 * @param {Array} [size] Current size of array.
864 * @returns {Array} returns the array itself
865 * @private
866 */
867
868
869function unsqueeze(array, dims, outer, size) {
870 var s = size || arraySize(array); // unsqueeze outer dimensions
871
872 if (outer) {
873 for (var i = 0; i < outer; i++) {
874 array = [array];
875 s.unshift(1);
876 }
877 } // unsqueeze inner dimensions
878
879
880 array = _unsqueeze(array, dims, 0);
881
882 while (s.length < dims) {
883 s.push(1);
884 }
885
886 return array;
887}
888/**
889 * Recursively unsqueeze a multi dimensional array
890 * @param {Array} array
891 * @param {number} dims Required number of dimensions
892 * @param {number} dim Current dimension
893 * @returns {Array | *} Returns the squeezed array
894 * @private
895 */
896
897function _unsqueeze(array, dims, dim) {
898 var i, ii;
899
900 if (Array.isArray(array)) {
901 var next = dim + 1;
902
903 for (i = 0, ii = array.length; i < ii; i++) {
904 array[i] = _unsqueeze(array[i], dims, next);
905 }
906 } else {
907 for (var d = dim; d < dims; d++) {
908 array = [array];
909 }
910 }
911
912 return array;
913}
914/**
915 * Flatten a multi dimensional array, put all elements in a one dimensional
916 * array
917 * @param {Array} array A multi dimensional array
918 * @return {Array} The flattened array (1 dimensional)
919 */
920
921
922function flatten(array) {
923 if (!Array.isArray(array)) {
924 // if not an array, return as is
925 return array;
926 }
927
928 var flat = [];
929 array.forEach(function callback(value) {
930 if (Array.isArray(value)) {
931 value.forEach(callback); // traverse through sub-arrays recursively
932 } else {
933 flat.push(value);
934 }
935 });
936 return flat;
937}
938/**
939 * A safe map
940 * @param {Array} array
941 * @param {function} callback
942 */
943
944function map(array, callback) {
945 return Array.prototype.map.call(array, callback);
946}
947/**
948 * A safe forEach
949 * @param {Array} array
950 * @param {function} callback
951 */
952
953function forEach(array, callback) {
954 Array.prototype.forEach.call(array, callback);
955}
956/**
957 * A safe filter
958 * @param {Array} array
959 * @param {function} callback
960 */
961
962function filter(array, callback) {
963 if (arraySize(array).length !== 1) {
964 throw new Error('Only one dimensional matrices supported');
965 }
966
967 return Array.prototype.filter.call(array, callback);
968}
969/**
970 * Filter values in a callback given a regular expression
971 * @param {Array} array
972 * @param {RegExp} regexp
973 * @return {Array} Returns the filtered array
974 * @private
975 */
976
977function filterRegExp(array, regexp) {
978 if (arraySize(array).length !== 1) {
979 throw new Error('Only one dimensional matrices supported');
980 }
981
982 return Array.prototype.filter.call(array, function (entry) {
983 return regexp.test(entry);
984 });
985}
986/**
987 * A safe join
988 * @param {Array} array
989 * @param {string} separator
990 */
991
992function join(array, separator) {
993 return Array.prototype.join.call(array, separator);
994}
995/**
996 * Assign a numeric identifier to every element of a sorted array
997 * @param {Array} a An array
998 * @return {Array} An array of objects containing the original value and its identifier
999 */
1000
1001function identify(a) {
1002 if (!Array.isArray(a)) {
1003 throw new TypeError('Array input expected');
1004 }
1005
1006 if (a.length === 0) {
1007 return a;
1008 }
1009
1010 var b = [];
1011 var count = 0;
1012 b[0] = {
1013 value: a[0],
1014 identifier: 0
1015 };
1016
1017 for (var i = 1; i < a.length; i++) {
1018 if (a[i] === a[i - 1]) {
1019 count++;
1020 } else {
1021 count = 0;
1022 }
1023
1024 b.push({
1025 value: a[i],
1026 identifier: count
1027 });
1028 }
1029
1030 return b;
1031}
1032/**
1033 * Remove the numeric identifier from the elements
1034 * @param {array} a An array
1035 * @return {array} An array of values without identifiers
1036 */
1037
1038function generalize(a) {
1039 if (!Array.isArray(a)) {
1040 throw new TypeError('Array input expected');
1041 }
1042
1043 if (a.length === 0) {
1044 return a;
1045 }
1046
1047 var b = [];
1048
1049 for (var i = 0; i < a.length; i++) {
1050 b.push(a[i].value);
1051 }
1052
1053 return b;
1054}
1055/**
1056 * Check the datatype of a given object
1057 * This is a low level implementation that should only be used by
1058 * parent Matrix classes such as SparseMatrix or DenseMatrix
1059 * This method does not validate Array Matrix shape
1060 * @param {Array} array
1061 * @param {function} typeOf Callback function to use to determine the type of a value
1062 * @return string
1063 */
1064
1065function getArrayDataType(array, typeOf) {
1066 var type; // to hold type info
1067
1068 var length = 0; // to hold length value to ensure it has consistent sizes
1069
1070 for (var i = 0; i < array.length; i++) {
1071 var item = array[i];
1072 var isArray = Array.isArray(item); // Saving the target matrix row size
1073
1074 if (i === 0 && isArray) {
1075 length = item.length;
1076 } // If the current item is an array but the length does not equal the targetVectorSize
1077
1078
1079 if (isArray && item.length !== length) {
1080 return undefined;
1081 }
1082
1083 var itemType = isArray ? getArrayDataType(item, typeOf) // recurse into a nested array
1084 : typeOf(item);
1085
1086 if (type === undefined) {
1087 type = itemType; // first item
1088 } else if (type !== itemType) {
1089 return 'mixed';
1090 } else {// we're good, everything has the same type so far
1091 }
1092 }
1093
1094 return type;
1095}
1096/**
1097 * Return the last item from an array
1098 * @param array
1099 * @returns {*}
1100 */
1101
1102function last(array) {
1103 return array[array.length - 1];
1104}
1105/**
1106 * Get all but the last element of array.
1107 */
1108
1109function initial(array) {
1110 return array.slice(0, array.length - 1);
1111}
1112/**
1113 * Test whether an array or string contains an item
1114 * @param {Array | string} array
1115 * @param {*} item
1116 * @return {boolean}
1117 */
1118
1119function contains(array, item) {
1120 return array.indexOf(item) !== -1;
1121}
1122
1123/***/ }),
1124/* 3 */
1125/***/ (function(module, __webpack_exports__, __webpack_require__) {
1126
1127"use strict";
1128/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return clone; });
1129/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "i", function() { return mapObject; });
1130/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return extend; });
1131/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return deepExtend; });
1132/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return deepStrictEqual; });
1133/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return deepFlatten; });
1134/* unused harmony export canDefineProperty */
1135/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "h", function() { return lazy; });
1136/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "k", function() { return traverse; });
1137/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "f", function() { return hasOwnProperty; });
1138/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "g", function() { return isLegacyFactory; });
1139/* unused harmony export get */
1140/* unused harmony export set */
1141/* unused harmony export pick */
1142/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "j", function() { return pickShallow; });
1143/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "l", function() { return values; });
1144/* harmony import */ var _is__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1);
1145function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
1146
1147
1148/**
1149 * Clone an object
1150 *
1151 * clone(x)
1152 *
1153 * Can clone any primitive type, array, and object.
1154 * If x has a function clone, this function will be invoked to clone the object.
1155 *
1156 * @param {*} x
1157 * @return {*} clone
1158 */
1159
1160function clone(x) {
1161 var type = _typeof(x); // immutable primitive types
1162
1163
1164 if (type === 'number' || type === 'string' || type === 'boolean' || x === null || x === undefined) {
1165 return x;
1166 } // use clone function of the object when available
1167
1168
1169 if (typeof x.clone === 'function') {
1170 return x.clone();
1171 } // array
1172
1173
1174 if (Array.isArray(x)) {
1175 return x.map(function (value) {
1176 return clone(value);
1177 });
1178 }
1179
1180 if (x instanceof Date) return new Date(x.valueOf());
1181 if (Object(_is__WEBPACK_IMPORTED_MODULE_0__[/* isBigNumber */ "e"])(x)) return x; // bignumbers are immutable
1182
1183 if (x instanceof RegExp) throw new TypeError('Cannot clone ' + x); // TODO: clone a RegExp
1184 // object
1185
1186 return mapObject(x, clone);
1187}
1188/**
1189 * Apply map to all properties of an object
1190 * @param {Object} object
1191 * @param {function} callback
1192 * @return {Object} Returns a copy of the object with mapped properties
1193 */
1194
1195function mapObject(object, callback) {
1196 var clone = {};
1197
1198 for (var key in object) {
1199 if (hasOwnProperty(object, key)) {
1200 clone[key] = callback(object[key]);
1201 }
1202 }
1203
1204 return clone;
1205}
1206/**
1207 * Extend object a with the properties of object b
1208 * @param {Object} a
1209 * @param {Object} b
1210 * @return {Object} a
1211 */
1212
1213function extend(a, b) {
1214 for (var prop in b) {
1215 if (hasOwnProperty(b, prop)) {
1216 a[prop] = b[prop];
1217 }
1218 }
1219
1220 return a;
1221}
1222/**
1223 * Deep extend an object a with the properties of object b
1224 * @param {Object} a
1225 * @param {Object} b
1226 * @returns {Object}
1227 */
1228
1229function deepExtend(a, b) {
1230 // TODO: add support for Arrays to deepExtend
1231 if (Array.isArray(b)) {
1232 throw new TypeError('Arrays are not supported by deepExtend');
1233 }
1234
1235 for (var prop in b) {
1236 if (hasOwnProperty(b, prop)) {
1237 if (b[prop] && b[prop].constructor === Object) {
1238 if (a[prop] === undefined) {
1239 a[prop] = {};
1240 }
1241
1242 if (a[prop] && a[prop].constructor === Object) {
1243 deepExtend(a[prop], b[prop]);
1244 } else {
1245 a[prop] = b[prop];
1246 }
1247 } else if (Array.isArray(b[prop])) {
1248 throw new TypeError('Arrays are not supported by deepExtend');
1249 } else {
1250 a[prop] = b[prop];
1251 }
1252 }
1253 }
1254
1255 return a;
1256}
1257/**
1258 * Deep test equality of all fields in two pairs of arrays or objects.
1259 * Compares values and functions strictly (ie. 2 is not the same as '2').
1260 * @param {Array | Object} a
1261 * @param {Array | Object} b
1262 * @returns {boolean}
1263 */
1264
1265function deepStrictEqual(a, b) {
1266 var prop, i, len;
1267
1268 if (Array.isArray(a)) {
1269 if (!Array.isArray(b)) {
1270 return false;
1271 }
1272
1273 if (a.length !== b.length) {
1274 return false;
1275 }
1276
1277 for (i = 0, len = a.length; i < len; i++) {
1278 if (!deepStrictEqual(a[i], b[i])) {
1279 return false;
1280 }
1281 }
1282
1283 return true;
1284 } else if (typeof a === 'function') {
1285 return a === b;
1286 } else if (a instanceof Object) {
1287 if (Array.isArray(b) || !(b instanceof Object)) {
1288 return false;
1289 }
1290
1291 for (prop in a) {
1292 // noinspection JSUnfilteredForInLoop
1293 if (!(prop in b) || !deepStrictEqual(a[prop], b[prop])) {
1294 return false;
1295 }
1296 }
1297
1298 for (prop in b) {
1299 // noinspection JSUnfilteredForInLoop
1300 if (!(prop in a) || !deepStrictEqual(a[prop], b[prop])) {
1301 return false;
1302 }
1303 }
1304
1305 return true;
1306 } else {
1307 return a === b;
1308 }
1309}
1310/**
1311 * Recursively flatten a nested object.
1312 * @param {Object} nestedObject
1313 * @return {Object} Returns the flattened object
1314 */
1315
1316function deepFlatten(nestedObject) {
1317 var flattenedObject = {};
1318
1319 _deepFlatten(nestedObject, flattenedObject);
1320
1321 return flattenedObject;
1322} // helper function used by deepFlatten
1323
1324function _deepFlatten(nestedObject, flattenedObject) {
1325 for (var prop in nestedObject) {
1326 if (hasOwnProperty(nestedObject, prop)) {
1327 var value = nestedObject[prop];
1328
1329 if (_typeof(value) === 'object' && value !== null) {
1330 _deepFlatten(value, flattenedObject);
1331 } else {
1332 flattenedObject[prop] = value;
1333 }
1334 }
1335 }
1336}
1337/**
1338 * Test whether the current JavaScript engine supports Object.defineProperty
1339 * @returns {boolean} returns true if supported
1340 */
1341
1342
1343function canDefineProperty() {
1344 // test needed for broken IE8 implementation
1345 try {
1346 if (Object.defineProperty) {
1347 Object.defineProperty({}, 'x', {
1348 get: function get() {}
1349 });
1350 return true;
1351 }
1352 } catch (e) {}
1353
1354 return false;
1355}
1356/**
1357 * Attach a lazy loading property to a constant.
1358 * The given function `fn` is called once when the property is first requested.
1359 *
1360 * @param {Object} object Object where to add the property
1361 * @param {string} prop Property name
1362 * @param {Function} valueResolver Function returning the property value. Called
1363 * without arguments.
1364 */
1365
1366function lazy(object, prop, valueResolver) {
1367 var _uninitialized = true;
1368
1369 var _value;
1370
1371 Object.defineProperty(object, prop, {
1372 get: function get() {
1373 if (_uninitialized) {
1374 _value = valueResolver();
1375 _uninitialized = false;
1376 }
1377
1378 return _value;
1379 },
1380 set: function set(value) {
1381 _value = value;
1382 _uninitialized = false;
1383 },
1384 configurable: true,
1385 enumerable: true
1386 });
1387}
1388/**
1389 * Traverse a path into an object.
1390 * When a namespace is missing, it will be created
1391 * @param {Object} object
1392 * @param {string | string[]} path A dot separated string like 'name.space'
1393 * @return {Object} Returns the object at the end of the path
1394 */
1395
1396function traverse(object, path) {
1397 if (path && typeof path === 'string') {
1398 return traverse(object, path.split('.'));
1399 }
1400
1401 var obj = object;
1402
1403 if (path) {
1404 for (var i = 0; i < path.length; i++) {
1405 var key = path[i];
1406
1407 if (!(key in obj)) {
1408 obj[key] = {};
1409 }
1410
1411 obj = obj[key];
1412 }
1413 }
1414
1415 return obj;
1416}
1417/**
1418 * A safe hasOwnProperty
1419 * @param {Object} object
1420 * @param {string} property
1421 */
1422
1423function hasOwnProperty(object, property) {
1424 return object && Object.hasOwnProperty.call(object, property);
1425}
1426/**
1427 * Test whether an object is a factory. a factory has fields:
1428 *
1429 * - factory: function (type: Object, config: Object, load: function, typed: function [, math: Object]) (required)
1430 * - name: string (optional)
1431 * - path: string A dot separated path (optional)
1432 * - math: boolean If true (false by default), the math namespace is passed
1433 * as fifth argument of the factory function
1434 *
1435 * @param {*} object
1436 * @returns {boolean}
1437 */
1438
1439function isLegacyFactory(object) {
1440 return object && typeof object.factory === 'function';
1441}
1442/**
1443 * Get a nested property from an object
1444 * @param {Object} object
1445 * @param {string | string[]} path
1446 * @returns {Object}
1447 */
1448
1449function get(object, path) {
1450 if (typeof path === 'string') {
1451 if (isPath(path)) {
1452 return get(object, path.split('.'));
1453 } else {
1454 return object[path];
1455 }
1456 }
1457
1458 var child = object;
1459
1460 for (var i = 0; i < path.length; i++) {
1461 var key = path[i];
1462 child = child ? child[key] : undefined;
1463 }
1464
1465 return child;
1466}
1467/**
1468 * Set a nested property in an object
1469 * Mutates the object itself
1470 * If the path doesn't exist, it will be created
1471 * @param {Object} object
1472 * @param {string | string[]} path
1473 * @param {*} value
1474 * @returns {Object}
1475 */
1476
1477function set(object, path, value) {
1478 if (typeof path === 'string') {
1479 if (isPath(path)) {
1480 return set(object, path.split('.'), value);
1481 } else {
1482 object[path] = value;
1483 return object;
1484 }
1485 }
1486
1487 var child = object;
1488
1489 for (var i = 0; i < path.length - 1; i++) {
1490 var key = path[i];
1491
1492 if (child[key] === undefined) {
1493 child[key] = {};
1494 }
1495
1496 child = child[key];
1497 }
1498
1499 if (path.length > 0) {
1500 var lastKey = path[path.length - 1];
1501 child[lastKey] = value;
1502 }
1503
1504 return object;
1505}
1506/**
1507 * Create an object composed of the picked object properties
1508 * @param {Object} object
1509 * @param {string[]} properties
1510 * @param {function} [transform] Optional value to transform a value when picking it
1511 * @return {Object}
1512 */
1513
1514function pick(object, properties, transform) {
1515 var copy = {};
1516
1517 for (var i = 0; i < properties.length; i++) {
1518 var key = properties[i];
1519 var value = get(object, key);
1520
1521 if (value !== undefined) {
1522 set(copy, key, transform ? transform(value, key) : value);
1523 }
1524 }
1525
1526 return copy;
1527}
1528/**
1529 * Shallow version of pick, creating an object composed of the picked object properties
1530 * but not for nested properties
1531 * @param {Object} object
1532 * @param {string[]} properties
1533 * @return {Object}
1534 */
1535
1536function pickShallow(object, properties) {
1537 var copy = {};
1538
1539 for (var i = 0; i < properties.length; i++) {
1540 var key = properties[i];
1541 var value = object[key];
1542
1543 if (value !== undefined) {
1544 copy[key] = value;
1545 }
1546 }
1547
1548 return copy;
1549}
1550function values(object) {
1551 return Object.keys(object).map(function (key) {
1552 return object[key];
1553 });
1554} // helper function to test whether a string contains a path like 'user.name'
1555
1556function isPath(str) {
1557 return str.indexOf('.') !== -1;
1558}
1559
1560/***/ }),
1561/* 4 */
1562/***/ (function(module, __webpack_exports__, __webpack_require__) {
1563
1564"use strict";
1565/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "i", function() { return isInteger; });
1566/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "n", function() { return sign; });
1567/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "l", function() { return log2; });
1568/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "j", function() { return log10; });
1569/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "k", function() { return log1p; });
1570/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return cbrt; });
1571/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "g", function() { return expm1; });
1572/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "h", function() { return format; });
1573/* unused harmony export splitNumber */
1574/* unused harmony export toEngineering */
1575/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "q", function() { return toFixed; });
1576/* unused harmony export toExponential */
1577/* unused harmony export toPrecision */
1578/* unused harmony export roundDigits */
1579/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "f", function() { return digits; });
1580/* unused harmony export DBL_EPSILON */
1581/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "m", function() { return nearlyEqual; });
1582/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return acosh; });
1583/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return asinh; });
1584/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return atanh; });
1585/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return cosh; });
1586/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "o", function() { return sinh; });
1587/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "p", function() { return tanh; });
1588/* harmony import */ var _object__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(3);
1589/* harmony import */ var _is__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1);
1590
1591
1592/**
1593 * @typedef {{sign: '+' | '-' | '', coefficients: number[], exponent: number}} SplitValue
1594 */
1595
1596/**
1597 * Check if a number is integer
1598 * @param {number | boolean} value
1599 * @return {boolean} isInteger
1600 */
1601
1602function isInteger(value) {
1603 if (typeof value === 'boolean') {
1604 return true;
1605 }
1606
1607 return isFinite(value) ? value === Math.round(value) : false; // Note: we use ==, not ===, as we can have Booleans as well
1608}
1609/**
1610 * Calculate the sign of a number
1611 * @param {number} x
1612 * @returns {number}
1613 */
1614
1615var sign =
1616/* #__PURE__ */
1617Math.sign || function (x) {
1618 if (x > 0) {
1619 return 1;
1620 } else if (x < 0) {
1621 return -1;
1622 } else {
1623 return 0;
1624 }
1625};
1626/**
1627 * Calculate the base-2 logarithm of a number
1628 * @param {number} x
1629 * @returns {number}
1630 */
1631
1632var log2 =
1633/* #__PURE__ */
1634Math.log2 || function log2(x) {
1635 return Math.log(x) / Math.LN2;
1636};
1637/**
1638 * Calculate the base-10 logarithm of a number
1639 * @param {number} x
1640 * @returns {number}
1641 */
1642
1643var log10 =
1644/* #__PURE__ */
1645Math.log10 || function log10(x) {
1646 return Math.log(x) / Math.LN10;
1647};
1648/**
1649 * Calculate the natural logarithm of a number + 1
1650 * @param {number} x
1651 * @returns {number}
1652 */
1653
1654var log1p =
1655/* #__PURE__ */
1656Math.log1p || function (x) {
1657 return Math.log(x + 1);
1658};
1659/**
1660 * Calculate cubic root for a number
1661 *
1662 * Code from es6-shim.js:
1663 * https://github.com/paulmillr/es6-shim/blob/master/es6-shim.js#L1564-L1577
1664 *
1665 * @param {number} x
1666 * @returns {number} Returns the cubic root of x
1667 */
1668
1669var cbrt =
1670/* #__PURE__ */
1671Math.cbrt || function cbrt(x) {
1672 if (x === 0) {
1673 return x;
1674 }
1675
1676 var negate = x < 0;
1677 var result;
1678
1679 if (negate) {
1680 x = -x;
1681 }
1682
1683 if (isFinite(x)) {
1684 result = Math.exp(Math.log(x) / 3); // from https://en.wikipedia.org/wiki/Cube_root#Numerical_methods
1685
1686 result = (x / (result * result) + 2 * result) / 3;
1687 } else {
1688 result = x;
1689 }
1690
1691 return negate ? -result : result;
1692};
1693/**
1694 * Calculates exponentiation minus 1
1695 * @param {number} x
1696 * @return {number} res
1697 */
1698
1699var expm1 =
1700/* #__PURE__ */
1701Math.expm1 || function expm1(x) {
1702 return x >= 2e-4 || x <= -2e-4 ? Math.exp(x) - 1 : x + x * x / 2 + x * x * x / 6;
1703};
1704/**
1705 * Convert a number to a formatted string representation.
1706 *
1707 * Syntax:
1708 *
1709 * format(value)
1710 * format(value, options)
1711 * format(value, precision)
1712 * format(value, fn)
1713 *
1714 * Where:
1715 *
1716 * {number} value The value to be formatted
1717 * {Object} options An object with formatting options. Available options:
1718 * {string} notation
1719 * Number notation. Choose from:
1720 * 'fixed' Always use regular number notation.
1721 * For example '123.40' and '14000000'
1722 * 'exponential' Always use exponential notation.
1723 * For example '1.234e+2' and '1.4e+7'
1724 * 'engineering' Always use engineering notation.
1725 * For example '123.4e+0' and '14.0e+6'
1726 * 'auto' (default) Regular number notation for numbers
1727 * having an absolute value between
1728 * `lowerExp` and `upperExp` bounds, and
1729 * uses exponential notation elsewhere.
1730 * Lower bound is included, upper bound
1731 * is excluded.
1732 * For example '123.4' and '1.4e7'.
1733 * {number} precision A number between 0 and 16 to round
1734 * the digits of the number.
1735 * In case of notations 'exponential',
1736 * 'engineering', and 'auto',
1737 * `precision` defines the total
1738 * number of significant digits returned.
1739 * In case of notation 'fixed',
1740 * `precision` defines the number of
1741 * significant digits after the decimal
1742 * point.
1743 * `precision` is undefined by default,
1744 * not rounding any digits.
1745 * {number} lowerExp Exponent determining the lower boundary
1746 * for formatting a value with an exponent
1747 * when `notation='auto`.
1748 * Default value is `-3`.
1749 * {number} upperExp Exponent determining the upper boundary
1750 * for formatting a value with an exponent
1751 * when `notation='auto`.
1752 * Default value is `5`.
1753 * {Function} fn A custom formatting function. Can be used to override the
1754 * built-in notations. Function `fn` is called with `value` as
1755 * parameter and must return a string. Is useful for example to
1756 * format all values inside a matrix in a particular way.
1757 *
1758 * Examples:
1759 *
1760 * format(6.4) // '6.4'
1761 * format(1240000) // '1.24e6'
1762 * format(1/3) // '0.3333333333333333'
1763 * format(1/3, 3) // '0.333'
1764 * format(21385, 2) // '21000'
1765 * format(12.071, {notation: 'fixed'}) // '12'
1766 * format(2.3, {notation: 'fixed', precision: 2}) // '2.30'
1767 * format(52.8, {notation: 'exponential'}) // '5.28e+1'
1768 * format(12345678, {notation: 'engineering'}) // '12.345678e+6'
1769 *
1770 * @param {number} value
1771 * @param {Object | Function | number} [options]
1772 * @return {string} str The formatted value
1773 */
1774
1775function format(value, options) {
1776 if (typeof options === 'function') {
1777 // handle format(value, fn)
1778 return options(value);
1779 } // handle special cases
1780
1781
1782 if (value === Infinity) {
1783 return 'Infinity';
1784 } else if (value === -Infinity) {
1785 return '-Infinity';
1786 } else if (isNaN(value)) {
1787 return 'NaN';
1788 } // default values for options
1789
1790
1791 var notation = 'auto';
1792 var precision;
1793
1794 if (options) {
1795 // determine notation from options
1796 if (options.notation) {
1797 notation = options.notation;
1798 } // determine precision from options
1799
1800
1801 if (Object(_is__WEBPACK_IMPORTED_MODULE_1__[/* isNumber */ "y"])(options)) {
1802 precision = options;
1803 } else if (Object(_is__WEBPACK_IMPORTED_MODULE_1__[/* isNumber */ "y"])(options.precision)) {
1804 precision = options.precision;
1805 }
1806 } // handle the various notations
1807
1808
1809 switch (notation) {
1810 case 'fixed':
1811 return toFixed(value, precision);
1812
1813 case 'exponential':
1814 return toExponential(value, precision);
1815
1816 case 'engineering':
1817 return toEngineering(value, precision);
1818
1819 case 'auto':
1820 // TODO: clean up some day. Deprecated since: 2018-01-24
1821 // @deprecated upper and lower are replaced with upperExp and lowerExp since v4.0.0
1822 if (options && options.exponential && (options.exponential.lower !== undefined || options.exponential.upper !== undefined)) {
1823 var fixedOptions = Object(_object__WEBPACK_IMPORTED_MODULE_0__[/* mapObject */ "i"])(options, function (x) {
1824 return x;
1825 });
1826 fixedOptions.exponential = undefined;
1827
1828 if (options.exponential.lower !== undefined) {
1829 fixedOptions.lowerExp = Math.round(Math.log(options.exponential.lower) / Math.LN10);
1830 }
1831
1832 if (options.exponential.upper !== undefined) {
1833 fixedOptions.upperExp = Math.round(Math.log(options.exponential.upper) / Math.LN10);
1834 }
1835
1836 console.warn('Deprecation warning: Formatting options exponential.lower and exponential.upper ' + '(minimum and maximum value) ' + 'are replaced with exponential.lowerExp and exponential.upperExp ' + '(minimum and maximum exponent) since version 4.0.0. ' + 'Replace ' + JSON.stringify(options) + ' with ' + JSON.stringify(fixedOptions));
1837 return toPrecision(value, precision, fixedOptions);
1838 } // remove trailing zeros after the decimal point
1839
1840
1841 return toPrecision(value, precision, options && options).replace(/((\.\d*?)(0+))($|e)/, function () {
1842 var digits = arguments[2];
1843 var e = arguments[4];
1844 return digits !== '.' ? digits + e : e;
1845 });
1846
1847 default:
1848 throw new Error('Unknown notation "' + notation + '". ' + 'Choose "auto", "exponential", or "fixed".');
1849 }
1850}
1851/**
1852 * Split a number into sign, coefficients, and exponent
1853 * @param {number | string} value
1854 * @return {SplitValue}
1855 * Returns an object containing sign, coefficients, and exponent
1856 */
1857
1858function splitNumber(value) {
1859 // parse the input value
1860 var match = String(value).toLowerCase().match(/^0*?(-?)(\d+\.?\d*)(e([+-]?\d+))?$/);
1861
1862 if (!match) {
1863 throw new SyntaxError('Invalid number ' + value);
1864 }
1865
1866 var sign = match[1];
1867 var digits = match[2];
1868 var exponent = parseFloat(match[4] || '0');
1869 var dot = digits.indexOf('.');
1870 exponent += dot !== -1 ? dot - 1 : digits.length - 1;
1871 var coefficients = digits.replace('.', '') // remove the dot (must be removed before removing leading zeros)
1872 .replace(/^0*/, function (zeros) {
1873 // remove leading zeros, add their count to the exponent
1874 exponent -= zeros.length;
1875 return '';
1876 }).replace(/0*$/, '') // remove trailing zeros
1877 .split('').map(function (d) {
1878 return parseInt(d);
1879 });
1880
1881 if (coefficients.length === 0) {
1882 coefficients.push(0);
1883 exponent++;
1884 }
1885
1886 return {
1887 sign: sign,
1888 coefficients: coefficients,
1889 exponent: exponent
1890 };
1891}
1892/**
1893 * Format a number in engineering notation. Like '1.23e+6', '2.3e+0', '3.500e-3'
1894 * @param {number | string} value
1895 * @param {number} [precision] Optional number of significant figures to return.
1896 */
1897
1898function toEngineering(value, precision) {
1899 if (isNaN(value) || !isFinite(value)) {
1900 return String(value);
1901 }
1902
1903 var rounded = roundDigits(splitNumber(value), precision);
1904 var e = rounded.exponent;
1905 var c = rounded.coefficients; // find nearest lower multiple of 3 for exponent
1906
1907 var newExp = e % 3 === 0 ? e : e < 0 ? e - 3 - e % 3 : e - e % 3;
1908
1909 if (Object(_is__WEBPACK_IMPORTED_MODULE_1__[/* isNumber */ "y"])(precision)) {
1910 // add zeroes to give correct sig figs
1911 while (precision > c.length || e - newExp + 1 > c.length) {
1912 c.push(0);
1913 }
1914 } else {
1915 // concatenate coefficients with necessary zeros
1916 var significandsDiff = e >= 0 ? e : Math.abs(newExp); // add zeros if necessary (for ex: 1e+8)
1917
1918 while (c.length - 1 < significandsDiff) {
1919 c.push(0);
1920 }
1921 } // find difference in exponents
1922
1923
1924 var expDiff = Math.abs(e - newExp);
1925 var decimalIdx = 1; // push decimal index over by expDiff times
1926
1927 while (expDiff > 0) {
1928 decimalIdx++;
1929 expDiff--;
1930 } // if all coefficient values are zero after the decimal point and precision is unset, don't add a decimal value.
1931 // otherwise concat with the rest of the coefficients
1932
1933
1934 var decimals = c.slice(decimalIdx).join('');
1935 var decimalVal = Object(_is__WEBPACK_IMPORTED_MODULE_1__[/* isNumber */ "y"])(precision) && decimals.length || decimals.match(/[1-9]/) ? '.' + decimals : '';
1936 var str = c.slice(0, decimalIdx).join('') + decimalVal + 'e' + (e >= 0 ? '+' : '') + newExp.toString();
1937 return rounded.sign + str;
1938}
1939/**
1940 * Format a number with fixed notation.
1941 * @param {number | string} value
1942 * @param {number} [precision=undefined] Optional number of decimals after the
1943 * decimal point. null by default.
1944 */
1945
1946function toFixed(value, precision) {
1947 if (isNaN(value) || !isFinite(value)) {
1948 return String(value);
1949 }
1950
1951 var splitValue = splitNumber(value);
1952 var rounded = typeof precision === 'number' ? roundDigits(splitValue, splitValue.exponent + 1 + precision) : splitValue;
1953 var c = rounded.coefficients;
1954 var p = rounded.exponent + 1; // exponent may have changed
1955 // append zeros if needed
1956
1957 var pp = p + (precision || 0);
1958
1959 if (c.length < pp) {
1960 c = c.concat(zeros(pp - c.length));
1961 } // prepend zeros if needed
1962
1963
1964 if (p < 0) {
1965 c = zeros(-p + 1).concat(c);
1966 p = 1;
1967 } // insert a dot if needed
1968
1969
1970 if (p < c.length) {
1971 c.splice(p, 0, p === 0 ? '0.' : '.');
1972 }
1973
1974 return rounded.sign + c.join('');
1975}
1976/**
1977 * Format a number in exponential notation. Like '1.23e+5', '2.3e+0', '3.500e-3'
1978 * @param {number | string} value
1979 * @param {number} [precision] Number of digits in formatted output.
1980 * If not provided, the maximum available digits
1981 * is used.
1982 */
1983
1984function toExponential(value, precision) {
1985 if (isNaN(value) || !isFinite(value)) {
1986 return String(value);
1987 } // round if needed, else create a clone
1988
1989
1990 var split = splitNumber(value);
1991 var rounded = precision ? roundDigits(split, precision) : split;
1992 var c = rounded.coefficients;
1993 var e = rounded.exponent; // append zeros if needed
1994
1995 if (c.length < precision) {
1996 c = c.concat(zeros(precision - c.length));
1997 } // format as `C.CCCe+EEE` or `C.CCCe-EEE`
1998
1999
2000 var first = c.shift();
2001 return rounded.sign + first + (c.length > 0 ? '.' + c.join('') : '') + 'e' + (e >= 0 ? '+' : '') + e;
2002}
2003/**
2004 * Format a number with a certain precision
2005 * @param {number | string} value
2006 * @param {number} [precision=undefined] Optional number of digits.
2007 * @param {{lowerExp: number | undefined, upperExp: number | undefined}} [options]
2008 * By default:
2009 * lowerExp = -3 (incl)
2010 * upper = +5 (excl)
2011 * @return {string}
2012 */
2013
2014function toPrecision(value, precision, options) {
2015 if (isNaN(value) || !isFinite(value)) {
2016 return String(value);
2017 } // determine lower and upper bound for exponential notation.
2018
2019
2020 var lowerExp = options && options.lowerExp !== undefined ? options.lowerExp : -3;
2021 var upperExp = options && options.upperExp !== undefined ? options.upperExp : 5;
2022 var split = splitNumber(value);
2023 var rounded = precision ? roundDigits(split, precision) : split;
2024
2025 if (rounded.exponent < lowerExp || rounded.exponent >= upperExp) {
2026 // exponential notation
2027 return toExponential(value, precision);
2028 } else {
2029 var c = rounded.coefficients;
2030 var e = rounded.exponent; // append trailing zeros
2031
2032 if (c.length < precision) {
2033 c = c.concat(zeros(precision - c.length));
2034 } // append trailing zeros
2035 // TODO: simplify the next statement
2036
2037
2038 c = c.concat(zeros(e - c.length + 1 + (c.length < precision ? precision - c.length : 0))); // prepend zeros
2039
2040 c = zeros(-e).concat(c);
2041 var dot = e > 0 ? e : 0;
2042
2043 if (dot < c.length - 1) {
2044 c.splice(dot + 1, 0, '.');
2045 }
2046
2047 return rounded.sign + c.join('');
2048 }
2049}
2050/**
2051 * Round the number of digits of a number *
2052 * @param {SplitValue} split A value split with .splitNumber(value)
2053 * @param {number} precision A positive integer
2054 * @return {SplitValue}
2055 * Returns an object containing sign, coefficients, and exponent
2056 * with rounded digits
2057 */
2058
2059function roundDigits(split, precision) {
2060 // create a clone
2061 var rounded = {
2062 sign: split.sign,
2063 coefficients: split.coefficients,
2064 exponent: split.exponent
2065 };
2066 var c = rounded.coefficients; // prepend zeros if needed
2067
2068 while (precision <= 0) {
2069 c.unshift(0);
2070 rounded.exponent++;
2071 precision++;
2072 }
2073
2074 if (c.length > precision) {
2075 var removed = c.splice(precision, c.length - precision);
2076
2077 if (removed[0] >= 5) {
2078 var i = precision - 1;
2079 c[i]++;
2080
2081 while (c[i] === 10) {
2082 c.pop();
2083
2084 if (i === 0) {
2085 c.unshift(0);
2086 rounded.exponent++;
2087 i++;
2088 }
2089
2090 i--;
2091 c[i]++;
2092 }
2093 }
2094 }
2095
2096 return rounded;
2097}
2098/**
2099 * Create an array filled with zeros.
2100 * @param {number} length
2101 * @return {Array}
2102 */
2103
2104function zeros(length) {
2105 var arr = [];
2106
2107 for (var i = 0; i < length; i++) {
2108 arr.push(0);
2109 }
2110
2111 return arr;
2112}
2113/**
2114 * Count the number of significant digits of a number.
2115 *
2116 * For example:
2117 * 2.34 returns 3
2118 * 0.0034 returns 2
2119 * 120.5e+30 returns 4
2120 *
2121 * @param {number} value
2122 * @return {number} digits Number of significant digits
2123 */
2124
2125
2126function digits(value) {
2127 return value.toExponential().replace(/e.*$/, '') // remove exponential notation
2128 .replace(/^0\.?0*|\./, '') // remove decimal point and leading zeros
2129 .length;
2130}
2131/**
2132 * Minimum number added to one that makes the result different than one
2133 */
2134
2135var DBL_EPSILON = Number.EPSILON || 2.2204460492503130808472633361816E-16;
2136/**
2137 * Compares two floating point numbers.
2138 * @param {number} x First value to compare
2139 * @param {number} y Second value to compare
2140 * @param {number} [epsilon] The maximum relative difference between x and y
2141 * If epsilon is undefined or null, the function will
2142 * test whether x and y are exactly equal.
2143 * @return {boolean} whether the two numbers are nearly equal
2144*/
2145
2146function nearlyEqual(x, y, epsilon) {
2147 // if epsilon is null or undefined, test whether x and y are exactly equal
2148 if (epsilon === null || epsilon === undefined) {
2149 return x === y;
2150 }
2151
2152 if (x === y) {
2153 return true;
2154 } // NaN
2155
2156
2157 if (isNaN(x) || isNaN(y)) {
2158 return false;
2159 } // at this point x and y should be finite
2160
2161
2162 if (isFinite(x) && isFinite(y)) {
2163 // check numbers are very close, needed when comparing numbers near zero
2164 var diff = Math.abs(x - y);
2165
2166 if (diff < DBL_EPSILON) {
2167 return true;
2168 } else {
2169 // use relative error
2170 return diff <= Math.max(Math.abs(x), Math.abs(y)) * epsilon;
2171 }
2172 } // Infinite and Number or negative Infinite and positive Infinite cases
2173
2174
2175 return false;
2176}
2177/**
2178 * Calculate the hyperbolic arccos of a number
2179 * @param {number} x
2180 * @return {number}
2181 */
2182
2183var acosh = Math.acosh || function (x) {
2184 return Math.log(Math.sqrt(x * x - 1) + x);
2185};
2186var asinh = Math.asinh || function (x) {
2187 return Math.log(Math.sqrt(x * x + 1) + x);
2188};
2189/**
2190 * Calculate the hyperbolic arctangent of a number
2191 * @param {number} x
2192 * @return {number}
2193 */
2194
2195var atanh = Math.atanh || function (x) {
2196 return Math.log((1 + x) / (1 - x)) / 2;
2197};
2198/**
2199 * Calculate the hyperbolic cosine of a number
2200 * @param {number} x
2201 * @returns {number}
2202 */
2203
2204var cosh = Math.cosh || function (x) {
2205 return (Math.exp(x) + Math.exp(-x)) / 2;
2206};
2207/**
2208 * Calculate the hyperbolic sine of a number
2209 * @param {number} x
2210 * @returns {number}
2211 */
2212
2213var sinh = Math.sinh || function (x) {
2214 return (Math.exp(x) - Math.exp(-x)) / 2;
2215};
2216/**
2217 * Calculate the hyperbolic tangent of a number
2218 * @param {number} x
2219 * @returns {number}
2220 */
2221
2222var tanh = Math.tanh || function (x) {
2223 var e = Math.exp(2 * x);
2224 return (e - 1) / (e + 1);
2225};
2226
2227/***/ }),
2228/* 5 */
2229/***/ (function(module, __webpack_exports__, __webpack_require__) {
2230
2231"use strict";
2232
2233// EXTERNAL MODULE: ./src/utils/is.js
2234var is = __webpack_require__(1);
2235
2236// EXTERNAL MODULE: ./src/utils/number.js
2237var number = __webpack_require__(4);
2238
2239// EXTERNAL MODULE: ./src/utils/object.js
2240var object = __webpack_require__(3);
2241
2242// CONCATENATED MODULE: ./src/utils/bignumber/formatter.js
2243
2244/**
2245 * Convert a BigNumber to a formatted string representation.
2246 *
2247 * Syntax:
2248 *
2249 * format(value)
2250 * format(value, options)
2251 * format(value, precision)
2252 * format(value, fn)
2253 *
2254 * Where:
2255 *
2256 * {number} value The value to be formatted
2257 * {Object} options An object with formatting options. Available options:
2258 * {string} notation
2259 * Number notation. Choose from:
2260 * 'fixed' Always use regular number notation.
2261 * For example '123.40' and '14000000'
2262 * 'exponential' Always use exponential notation.
2263 * For example '1.234e+2' and '1.4e+7'
2264 * 'auto' (default) Regular number notation for numbers
2265 * having an absolute value between
2266 * `lower` and `upper` bounds, and uses
2267 * exponential notation elsewhere.
2268 * Lower bound is included, upper bound
2269 * is excluded.
2270 * For example '123.4' and '1.4e7'.
2271 * {number} precision A number between 0 and 16 to round
2272 * the digits of the number.
2273 * In case of notations 'exponential',
2274 * 'engineering', and 'auto',
2275 * `precision` defines the total
2276 * number of significant digits returned.
2277 * In case of notation 'fixed',
2278 * `precision` defines the number of
2279 * significant digits after the decimal
2280 * point.
2281 * `precision` is undefined by default.
2282 * {number} lowerExp Exponent determining the lower boundary
2283 * for formatting a value with an exponent
2284 * when `notation='auto`.
2285 * Default value is `-3`.
2286 * {number} upperExp Exponent determining the upper boundary
2287 * for formatting a value with an exponent
2288 * when `notation='auto`.
2289 * Default value is `5`.
2290 * {Function} fn A custom formatting function. Can be used to override the
2291 * built-in notations. Function `fn` is called with `value` as
2292 * parameter and must return a string. Is useful for example to
2293 * format all values inside a matrix in a particular way.
2294 *
2295 * Examples:
2296 *
2297 * format(6.4) // '6.4'
2298 * format(1240000) // '1.24e6'
2299 * format(1/3) // '0.3333333333333333'
2300 * format(1/3, 3) // '0.333'
2301 * format(21385, 2) // '21000'
2302 * format(12e8, {notation: 'fixed'}) // returns '1200000000'
2303 * format(2.3, {notation: 'fixed', precision: 4}) // returns '2.3000'
2304 * format(52.8, {notation: 'exponential'}) // returns '5.28e+1'
2305 * format(12400, {notation: 'engineering'}) // returns '12.400e+3'
2306 *
2307 * @param {BigNumber} value
2308 * @param {Object | Function | number} [options]
2309 * @return {string} str The formatted value
2310 */
2311
2312function format(value, options) {
2313 if (typeof options === 'function') {
2314 // handle format(value, fn)
2315 return options(value);
2316 } // handle special cases
2317
2318
2319 if (!value.isFinite()) {
2320 return value.isNaN() ? 'NaN' : value.gt(0) ? 'Infinity' : '-Infinity';
2321 } // default values for options
2322
2323
2324 var notation = 'auto';
2325 var precision;
2326
2327 if (options !== undefined) {
2328 // determine notation from options
2329 if (options.notation) {
2330 notation = options.notation;
2331 } // determine precision from options
2332
2333
2334 if (typeof options === 'number') {
2335 precision = options;
2336 } else if (options.precision) {
2337 precision = options.precision;
2338 }
2339 } // handle the various notations
2340
2341
2342 switch (notation) {
2343 case 'fixed':
2344 return toFixed(value, precision);
2345
2346 case 'exponential':
2347 return toExponential(value, precision);
2348
2349 case 'engineering':
2350 return toEngineering(value, precision);
2351
2352 case 'auto':
2353 {
2354 // TODO: clean up some day. Deprecated since: 2018-01-24
2355 // @deprecated upper and lower are replaced with upperExp and lowerExp since v4.0.0
2356 if (options && options.exponential && (options.exponential.lower !== undefined || options.exponential.upper !== undefined)) {
2357 var fixedOptions = Object(object["i" /* mapObject */])(options, function (x) {
2358 return x;
2359 });
2360 fixedOptions.exponential = undefined;
2361
2362 if (options.exponential.lower !== undefined) {
2363 fixedOptions.lowerExp = Math.round(Math.log(options.exponential.lower) / Math.LN10);
2364 }
2365
2366 if (options.exponential.upper !== undefined) {
2367 fixedOptions.upperExp = Math.round(Math.log(options.exponential.upper) / Math.LN10);
2368 }
2369
2370 console.warn('Deprecation warning: Formatting options exponential.lower and exponential.upper ' + '(minimum and maximum value) ' + 'are replaced with exponential.lowerExp and exponential.upperExp ' + '(minimum and maximum exponent) since version 4.0.0. ' + 'Replace ' + JSON.stringify(options) + ' with ' + JSON.stringify(fixedOptions));
2371 return format(value, fixedOptions);
2372 } // determine lower and upper bound for exponential notation.
2373 // TODO: implement support for upper and lower to be BigNumbers themselves
2374
2375
2376 var lowerExp = options && options.lowerExp !== undefined ? options.lowerExp : -3;
2377 var upperExp = options && options.upperExp !== undefined ? options.upperExp : 5; // handle special case zero
2378
2379 if (value.isZero()) return '0'; // determine whether or not to output exponential notation
2380
2381 var str;
2382 var rounded = value.toSignificantDigits(precision);
2383 var exp = rounded.e;
2384
2385 if (exp >= lowerExp && exp < upperExp) {
2386 // normal number notation
2387 str = rounded.toFixed();
2388 } else {
2389 // exponential notation
2390 str = toExponential(value, precision);
2391 } // remove trailing zeros after the decimal point
2392
2393
2394 return str.replace(/((\.\d*?)(0+))($|e)/, function () {
2395 var digits = arguments[2];
2396 var e = arguments[4];
2397 return digits !== '.' ? digits + e : e;
2398 });
2399 }
2400
2401 default:
2402 throw new Error('Unknown notation "' + notation + '". ' + 'Choose "auto", "exponential", or "fixed".');
2403 }
2404}
2405/**
2406 * Format a BigNumber in engineering notation. Like '1.23e+6', '2.3e+0', '3.500e-3'
2407 * @param {BigNumber | string} value
2408 * @param {number} [precision] Optional number of significant figures to return.
2409 */
2410
2411function toEngineering(value, precision) {
2412 // find nearest lower multiple of 3 for exponent
2413 var e = value.e;
2414 var newExp = e % 3 === 0 ? e : e < 0 ? e - 3 - e % 3 : e - e % 3; // find difference in exponents, and calculate the value without exponent
2415
2416 var valueWithoutExp = value.mul(Math.pow(10, -newExp));
2417 var valueStr = valueWithoutExp.toPrecision(precision);
2418
2419 if (valueStr.indexOf('e') !== -1) {
2420 valueStr = valueWithoutExp.toString();
2421 }
2422
2423 return valueStr + 'e' + (e >= 0 ? '+' : '') + newExp.toString();
2424}
2425/**
2426 * Format a number in exponential notation. Like '1.23e+5', '2.3e+0', '3.500e-3'
2427 * @param {BigNumber} value
2428 * @param {number} [precision] Number of digits in formatted output.
2429 * If not provided, the maximum available digits
2430 * is used.
2431 * @returns {string} str
2432 */
2433
2434function toExponential(value, precision) {
2435 if (precision !== undefined) {
2436 return value.toExponential(precision - 1); // Note the offset of one
2437 } else {
2438 return value.toExponential();
2439 }
2440}
2441/**
2442 * Format a number with fixed notation.
2443 * @param {BigNumber} value
2444 * @param {number} [precision=undefined] Optional number of decimals after the
2445 * decimal point. Undefined by default.
2446 */
2447
2448function toFixed(value, precision) {
2449 return value.toFixed(precision);
2450}
2451// CONCATENATED MODULE: ./src/utils/string.js
2452/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return endsWith; });
2453/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return string_format; });
2454/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return stringify; });
2455/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return string_escape; });
2456/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return compareText; });
2457function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
2458
2459
2460
2461
2462/**
2463 * Check if a text ends with a certain string.
2464 * @param {string} text
2465 * @param {string} search
2466 */
2467
2468function endsWith(text, search) {
2469 var start = text.length - search.length;
2470 var end = text.length;
2471 return text.substring(start, end) === search;
2472}
2473/**
2474 * Format a value of any type into a string.
2475 *
2476 * Usage:
2477 * math.format(value)
2478 * math.format(value, precision)
2479 *
2480 * When value is a function:
2481 *
2482 * - When the function has a property `syntax`, it returns this
2483 * syntax description.
2484 * - In other cases, a string `'function'` is returned.
2485 *
2486 * When `value` is an Object:
2487 *
2488 * - When the object contains a property `format` being a function, this
2489 * function is invoked as `value.format(options)` and the result is returned.
2490 * - When the object has its own `toString` method, this method is invoked
2491 * and the result is returned.
2492 * - In other cases the function will loop over all object properties and
2493 * return JSON object notation like '{"a": 2, "b": 3}'.
2494 *
2495 * Example usage:
2496 * math.format(2/7) // '0.2857142857142857'
2497 * math.format(math.pi, 3) // '3.14'
2498 * math.format(new Complex(2, 3)) // '2 + 3i'
2499 * math.format('hello') // '"hello"'
2500 *
2501 * @param {*} value Value to be stringified
2502 * @param {Object | number | Function} [options] Formatting options. See
2503 * lib/utils/number:format for a
2504 * description of the available
2505 * options.
2506 * @return {string} str
2507 */
2508
2509function string_format(value, options) {
2510 if (typeof value === 'number') {
2511 return Object(number["h" /* format */])(value, options);
2512 }
2513
2514 if (Object(is["e" /* isBigNumber */])(value)) {
2515 return format(value, options);
2516 } // note: we use unsafe duck-typing here to check for Fractions, this is
2517 // ok here since we're only invoking toString or concatenating its values
2518
2519
2520 if (looksLikeFraction(value)) {
2521 if (!options || options.fraction !== 'decimal') {
2522 // output as ratio, like '1/3'
2523 return value.s * value.n + '/' + value.d;
2524 } else {
2525 // output as decimal, like '0.(3)'
2526 return value.toString();
2527 }
2528 }
2529
2530 if (Array.isArray(value)) {
2531 return formatArray(value, options);
2532 }
2533
2534 if (Object(is["I" /* isString */])(value)) {
2535 return '"' + value + '"';
2536 }
2537
2538 if (typeof value === 'function') {
2539 return value.syntax ? String(value.syntax) : 'function';
2540 }
2541
2542 if (value && _typeof(value) === 'object') {
2543 if (typeof value.format === 'function') {
2544 return value.format(options);
2545 } else if (value && value.toString(options) !== {}.toString()) {
2546 // this object has a non-native toString method, use that one
2547 return value.toString(options);
2548 } else {
2549 var entries = Object.keys(value).map(function (key) {
2550 return '"' + key + '": ' + string_format(value[key], options);
2551 });
2552 return '{' + entries.join(', ') + '}';
2553 }
2554 }
2555
2556 return String(value);
2557}
2558/**
2559 * Stringify a value into a string enclosed in double quotes.
2560 * Unescaped double quotes and backslashes inside the value are escaped.
2561 * @param {*} value
2562 * @return {string}
2563 */
2564
2565function stringify(value) {
2566 var text = String(value);
2567 var escaped = '';
2568 var i = 0;
2569
2570 while (i < text.length) {
2571 var c = text.charAt(i);
2572
2573 if (c === '\\') {
2574 escaped += c;
2575 i++;
2576 c = text.charAt(i);
2577
2578 if (c === '' || '"\\/bfnrtu'.indexOf(c) === -1) {
2579 escaped += '\\'; // no valid escape character -> escape it
2580 }
2581
2582 escaped += c;
2583 } else if (c === '"') {
2584 escaped += '\\"';
2585 } else {
2586 escaped += c;
2587 }
2588
2589 i++;
2590 }
2591
2592 return '"' + escaped + '"';
2593}
2594/**
2595 * Escape special HTML characters
2596 * @param {*} value
2597 * @return {string}
2598 */
2599
2600function string_escape(value) {
2601 var text = String(value);
2602 text = text.replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/'/g, '&#39;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
2603 return text;
2604}
2605/**
2606 * Recursively format an n-dimensional matrix
2607 * Example output: "[[1, 2], [3, 4]]"
2608 * @param {Array} array
2609 * @param {Object | number | Function} [options] Formatting options. See
2610 * lib/utils/number:format for a
2611 * description of the available
2612 * options.
2613 * @returns {string} str
2614 */
2615
2616function formatArray(array, options) {
2617 if (Array.isArray(array)) {
2618 var str = '[';
2619 var len = array.length;
2620
2621 for (var i = 0; i < len; i++) {
2622 if (i !== 0) {
2623 str += ', ';
2624 }
2625
2626 str += formatArray(array[i], options);
2627 }
2628
2629 str += ']';
2630 return str;
2631 } else {
2632 return string_format(array, options);
2633 }
2634}
2635/**
2636 * Check whether a value looks like a Fraction (unsafe duck-type check)
2637 * @param {*} value
2638 * @return {boolean}
2639 */
2640
2641
2642function looksLikeFraction(value) {
2643 return value && _typeof(value) === 'object' && typeof value.s === 'number' && typeof value.n === 'number' && typeof value.d === 'number' || false;
2644}
2645/**
2646 * Compare two strings
2647 * @param {string} x
2648 * @param {string} y
2649 * @returns {number}
2650 */
2651
2652
2653function compareText(x, y) {
2654 // we don't want to convert numbers to string, only accept string input
2655 if (!Object(is["I" /* isString */])(x)) {
2656 throw new TypeError('Unexpected type of argument in function compareText ' + '(expected: string or Array or Matrix, actual: ' + Object(is["M" /* typeOf */])(x) + ', index: 0)');
2657 }
2658
2659 if (!Object(is["I" /* isString */])(y)) {
2660 throw new TypeError('Unexpected type of argument in function compareText ' + '(expected: string or Array or Matrix, actual: ' + Object(is["M" /* typeOf */])(y) + ', index: 1)');
2661 }
2662
2663 return x === y ? 0 : x > y ? 1 : -1;
2664}
2665
2666/***/ }),
2667/* 6 */
2668/***/ (function(module, __webpack_exports__, __webpack_require__) {
2669
2670"use strict";
2671/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return DimensionError; });
2672/**
2673 * Create a range error with the message:
2674 * 'Dimension mismatch (<actual size> != <expected size>)'
2675 * @param {number | number[]} actual The actual size
2676 * @param {number | number[]} expected The expected size
2677 * @param {string} [relation='!='] Optional relation between actual
2678 * and expected size: '!=', '<', etc.
2679 * @extends RangeError
2680 */
2681function DimensionError(actual, expected, relation) {
2682 if (!(this instanceof DimensionError)) {
2683 throw new SyntaxError('Constructor must be called with the new operator');
2684 }
2685
2686 this.actual = actual;
2687 this.expected = expected;
2688 this.relation = relation;
2689 this.message = 'Dimension mismatch (' + (Array.isArray(actual) ? '[' + actual.join(', ') + ']' : actual) + ' ' + (this.relation || '!=') + ' ' + (Array.isArray(expected) ? '[' + expected.join(', ') + ']' : expected) + ')';
2690 this.stack = new Error().stack;
2691}
2692DimensionError.prototype = new RangeError();
2693DimensionError.prototype.constructor = RangeError;
2694DimensionError.prototype.name = 'DimensionError';
2695DimensionError.prototype.isDimensionError = true;
2696
2697/***/ }),
2698/* 7 */,
2699/* 8 */
2700/***/ (function(module, __webpack_exports__, __webpack_require__) {
2701
2702"use strict";
2703/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return warnOnce; });
2704/**
2705 * Log a console.warn message only once
2706 */
2707var warnOnce = function () {
2708 var messages = {};
2709 return function warnOnce() {
2710 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
2711 args[_key] = arguments[_key];
2712 }
2713
2714 var message = args.join(', ');
2715
2716 if (!messages[message]) {
2717 var _console;
2718
2719 messages[message] = true;
2720
2721 (_console = console).warn.apply(_console, ['Warning:'].concat(args));
2722 }
2723 };
2724}();
2725
2726/***/ }),
2727/* 9 */
2728/***/ (function(module, exports, __webpack_require__) {
2729
2730var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/**
2731 * @license Complex.js v2.0.11 11/02/2016
2732 *
2733 * Copyright (c) 2016, Robert Eisele (robert@xarg.org)
2734 * Dual licensed under the MIT or GPL Version 2 licenses.
2735 **/
2736
2737/**
2738 *
2739 * This class allows the manipulation of complex numbers.
2740 * You can pass a complex number in different formats. Either as object, double, string or two integer parameters.
2741 *
2742 * Object form
2743 * { re: <real>, im: <imaginary> }
2744 * { arg: <angle>, abs: <radius> }
2745 * { phi: <angle>, r: <radius> }
2746 *
2747 * Array / Vector form
2748 * [ real, imaginary ]
2749 *
2750 * Double form
2751 * 99.3 - Single double value
2752 *
2753 * String form
2754 * '23.1337' - Simple real number
2755 * '15+3i' - a simple complex number
2756 * '3-i' - a simple complex number
2757 *
2758 * Example:
2759 *
2760 * var c = new Complex('99.3+8i');
2761 * c.mul({r: 3, i: 9}).div(4.9).sub(3, 2);
2762 *
2763 */
2764
2765(function(root) {
2766
2767 'use strict';
2768
2769 var cosh = function(x) {
2770 return (Math.exp(x) + Math.exp(-x)) * 0.5;
2771 };
2772
2773 var sinh = function(x) {
2774 return (Math.exp(x) - Math.exp(-x)) * 0.5;
2775 };
2776
2777 /**
2778 * Calculates cos(x) - 1 using Taylor series if x is small.
2779 *
2780 * @param {number} x
2781 * @returns {number} cos(x) - 1
2782 */
2783
2784 var cosm1 = function(x) {
2785 var limit = Math.PI/4;
2786 if (x < -limit || x > limit) {
2787 return (Math.cos(x) - 1.0);
2788 }
2789
2790 var xx = x * x;
2791 return xx *
2792 (-0.5 + xx *
2793 (1/24 + xx *
2794 (-1/720 + xx *
2795 (1/40320 + xx *
2796 (-1/3628800 + xx *
2797 (1/4790014600 + xx *
2798 (-1/87178291200 + xx *
2799 (1/20922789888000)
2800 )
2801 )
2802 )
2803 )
2804 )
2805 )
2806 )
2807 };
2808
2809 var hypot = function(x, y) {
2810
2811 var a = Math.abs(x);
2812 var b = Math.abs(y);
2813
2814 if (a < 3000 && b < 3000) {
2815 return Math.sqrt(a * a + b * b);
2816 }
2817
2818 if (a < b) {
2819 a = b;
2820 b = x / y;
2821 } else {
2822 b = y / x;
2823 }
2824 return a * Math.sqrt(1 + b * b);
2825 };
2826
2827 var parser_exit = function() {
2828 throw SyntaxError('Invalid Param');
2829 };
2830
2831 /**
2832 * Calculates log(sqrt(a^2+b^2)) in a way to avoid overflows
2833 *
2834 * @param {number} a
2835 * @param {number} b
2836 * @returns {number}
2837 */
2838 function logHypot(a, b) {
2839
2840 var _a = Math.abs(a);
2841 var _b = Math.abs(b);
2842
2843 if (a === 0) {
2844 return Math.log(_b);
2845 }
2846
2847 if (b === 0) {
2848 return Math.log(_a);
2849 }
2850
2851 if (_a < 3000 && _b < 3000) {
2852 return Math.log(a * a + b * b) * 0.5;
2853 }
2854
2855 /* I got 4 ideas to compute this property without overflow:
2856 *
2857 * Testing 1000000 times with random samples for a,b ∈ [1, 1000000000] against a big decimal library to get an error estimate
2858 *
2859 * 1. Only eliminate the square root: (OVERALL ERROR: 3.9122483030951116e-11)
2860
2861 Math.log(a * a + b * b) / 2
2862
2863 *
2864 *
2865 * 2. Try to use the non-overflowing pythagoras: (OVERALL ERROR: 8.889760039210159e-10)
2866
2867 var fn = function(a, b) {
2868 a = Math.abs(a);
2869 b = Math.abs(b);
2870 var t = Math.min(a, b);
2871 a = Math.max(a, b);
2872 t = t / a;
2873
2874 return Math.log(a) + Math.log(1 + t * t) / 2;
2875 };
2876
2877 * 3. Abuse the identity cos(atan(y/x) = x / sqrt(x^2+y^2): (OVERALL ERROR: 3.4780178737037204e-10)
2878
2879 Math.log(a / Math.cos(Math.atan2(b, a)))
2880
2881 * 4. Use 3. and apply log rules: (OVERALL ERROR: 1.2014087502620896e-9)
2882
2883 Math.log(a) - Math.log(Math.cos(Math.atan2(b, a)))
2884
2885 */
2886
2887 return Math.log(a / Math.cos(Math.atan2(b, a)));
2888 }
2889
2890 var parse = function(a, b) {
2891
2892 var z = {'re': 0, 'im': 0};
2893
2894 if (a === undefined || a === null) {
2895 z['re'] =
2896 z['im'] = 0;
2897 } else if (b !== undefined) {
2898 z['re'] = a;
2899 z['im'] = b;
2900 } else
2901 switch (typeof a) {
2902
2903 case 'object':
2904
2905 if ('im' in a && 're' in a) {
2906 z['re'] = a['re'];
2907 z['im'] = a['im'];
2908 } else if ('abs' in a && 'arg' in a) {
2909 if (!Number.isFinite(a['abs']) && Number.isFinite(a['arg'])) {
2910 return Complex['INFINITY'];
2911 }
2912 z['re'] = a['abs'] * Math.cos(a['arg']);
2913 z['im'] = a['abs'] * Math.sin(a['arg']);
2914 } else if ('r' in a && 'phi' in a) {
2915 if (!Number.isFinite(a['r']) && Number.isFinite(a['phi'])) {
2916 return Complex['INFINITY'];
2917 }
2918 z['re'] = a['r'] * Math.cos(a['phi']);
2919 z['im'] = a['r'] * Math.sin(a['phi']);
2920 } else if (a.length === 2) { // Quick array check
2921 z['re'] = a[0];
2922 z['im'] = a[1];
2923 } else {
2924 parser_exit();
2925 }
2926 break;
2927
2928 case 'string':
2929
2930 z['im'] = /* void */
2931 z['re'] = 0;
2932
2933 var tokens = a.match(/\d+\.?\d*e[+-]?\d+|\d+\.?\d*|\.\d+|./g);
2934 var plus = 1;
2935 var minus = 0;
2936
2937 if (tokens === null) {
2938 parser_exit();
2939 }
2940
2941 for (var i = 0; i < tokens.length; i++) {
2942
2943 var c = tokens[i];
2944
2945 if (c === ' ' || c === '\t' || c === '\n') {
2946 /* void */
2947 } else if (c === '+') {
2948 plus++;
2949 } else if (c === '-') {
2950 minus++;
2951 } else if (c === 'i' || c === 'I') {
2952
2953 if (plus + minus === 0) {
2954 parser_exit();
2955 }
2956
2957 if (tokens[i + 1] !== ' ' && !isNaN(tokens[i + 1])) {
2958 z['im'] += parseFloat((minus % 2 ? '-' : '') + tokens[i + 1]);
2959 i++;
2960 } else {
2961 z['im'] += parseFloat((minus % 2 ? '-' : '') + '1');
2962 }
2963 plus = minus = 0;
2964
2965 } else {
2966
2967 if (plus + minus === 0 || isNaN(c)) {
2968 parser_exit();
2969 }
2970
2971 if (tokens[i + 1] === 'i' || tokens[i + 1] === 'I') {
2972 z['im'] += parseFloat((minus % 2 ? '-' : '') + c);
2973 i++;
2974 } else {
2975 z['re'] += parseFloat((minus % 2 ? '-' : '') + c);
2976 }
2977 plus = minus = 0;
2978 }
2979 }
2980
2981 // Still something on the stack
2982 if (plus + minus > 0) {
2983 parser_exit();
2984 }
2985 break;
2986
2987 case 'number':
2988 z['im'] = 0;
2989 z['re'] = a;
2990 break;
2991
2992 default:
2993 parser_exit();
2994 }
2995
2996 if (isNaN(z['re']) || isNaN(z['im'])) {
2997 // If a calculation is NaN, we treat it as NaN and don't throw
2998 //parser_exit();
2999 }
3000
3001 return z;
3002 };
3003
3004 /**
3005 * @constructor
3006 * @returns {Complex}
3007 */
3008 function Complex(a, b) {
3009
3010 if (!(this instanceof Complex)) {
3011 return new Complex(a, b);
3012 }
3013
3014 var z = parse(a, b);
3015
3016 this['re'] = z['re'];
3017 this['im'] = z['im'];
3018 }
3019
3020 Complex.prototype = {
3021
3022 're': 0,
3023 'im': 0,
3024
3025 /**
3026 * Calculates the sign of a complex number, which is a normalized complex
3027 *
3028 * @returns {Complex}
3029 */
3030 'sign': function() {
3031
3032 var abs = this['abs']();
3033
3034 return new Complex(
3035 this['re'] / abs,
3036 this['im'] / abs);
3037 },
3038
3039 /**
3040 * Adds two complex numbers
3041 *
3042 * @returns {Complex}
3043 */
3044 'add': function(a, b) {
3045
3046 var z = new Complex(a, b);
3047
3048 // Infinity + Infinity = NaN
3049 if (this['isInfinite']() && z['isInfinite']()) {
3050 return Complex['NAN'];
3051 }
3052
3053 // Infinity + z = Infinity { where z != Infinity }
3054 if (this['isInfinite']() || z['isInfinite']()) {
3055 return Complex['INFINITY'];
3056 }
3057
3058 return new Complex(
3059 this['re'] + z['re'],
3060 this['im'] + z['im']);
3061 },
3062
3063 /**
3064 * Subtracts two complex numbers
3065 *
3066 * @returns {Complex}
3067 */
3068 'sub': function(a, b) {
3069
3070 var z = new Complex(a, b);
3071
3072 // Infinity - Infinity = NaN
3073 if (this['isInfinite']() && z['isInfinite']()) {
3074 return Complex['NAN'];
3075 }
3076
3077 // Infinity - z = Infinity { where z != Infinity }
3078 if (this['isInfinite']() || z['isInfinite']()) {
3079 return Complex['INFINITY'];
3080 }
3081
3082 return new Complex(
3083 this['re'] - z['re'],
3084 this['im'] - z['im']);
3085 },
3086
3087 /**
3088 * Multiplies two complex numbers
3089 *
3090 * @returns {Complex}
3091 */
3092 'mul': function(a, b) {
3093
3094 var z = new Complex(a, b);
3095
3096 // Infinity * 0 = NaN
3097 if ((this['isInfinite']() && z['isZero']()) || (this['isZero']() && z['isInfinite']())) {
3098 return Complex['NAN'];
3099 }
3100
3101 // Infinity * z = Infinity { where z != 0 }
3102 if (this['isInfinite']() || z['isInfinite']()) {
3103 return Complex['INFINITY'];
3104 }
3105
3106 // Short circuit for real values
3107 if (z['im'] === 0 && this['im'] === 0) {
3108 return new Complex(this['re'] * z['re'], 0);
3109 }
3110
3111 return new Complex(
3112 this['re'] * z['re'] - this['im'] * z['im'],
3113 this['re'] * z['im'] + this['im'] * z['re']);
3114 },
3115
3116 /**
3117 * Divides two complex numbers
3118 *
3119 * @returns {Complex}
3120 */
3121 'div': function(a, b) {
3122
3123 var z = new Complex(a, b);
3124
3125 // 0 / 0 = NaN and Infinity / Infinity = NaN
3126 if ((this['isZero']() && z['isZero']()) || (this['isInfinite']() && z['isInfinite']())) {
3127 return Complex['NAN'];
3128 }
3129
3130 // Infinity / 0 = Infinity
3131 if (this['isInfinite']() || z['isZero']()) {
3132 return Complex['INFINITY'];
3133 }
3134
3135 // 0 / Infinity = 0
3136 if (this['isZero']() || z['isInfinite']()) {
3137 return Complex['ZERO'];
3138 }
3139
3140 a = this['re'];
3141 b = this['im'];
3142
3143 var c = z['re'];
3144 var d = z['im'];
3145 var t, x;
3146
3147 if (0 === d) {
3148 // Divisor is real
3149 return new Complex(a / c, b / c);
3150 }
3151
3152 if (Math.abs(c) < Math.abs(d)) {
3153
3154 x = c / d;
3155 t = c * x + d;
3156
3157 return new Complex(
3158 (a * x + b) / t,
3159 (b * x - a) / t);
3160
3161 } else {
3162
3163 x = d / c;
3164 t = d * x + c;
3165
3166 return new Complex(
3167 (a + b * x) / t,
3168 (b - a * x) / t);
3169 }
3170 },
3171
3172 /**
3173 * Calculate the power of two complex numbers
3174 *
3175 * @returns {Complex}
3176 */
3177 'pow': function(a, b) {
3178
3179 var z = new Complex(a, b);
3180
3181 a = this['re'];
3182 b = this['im'];
3183
3184 if (z['isZero']()) {
3185 return Complex['ONE'];
3186 }
3187
3188 // If the exponent is real
3189 if (z['im'] === 0) {
3190
3191 if (b === 0 && a >= 0) {
3192
3193 return new Complex(Math.pow(a, z['re']), 0);
3194
3195 } else if (a === 0) { // If base is fully imaginary
3196
3197 switch ((z['re'] % 4 + 4) % 4) {
3198 case 0:
3199 return new Complex(Math.pow(b, z['re']), 0);
3200 case 1:
3201 return new Complex(0, Math.pow(b, z['re']));
3202 case 2:
3203 return new Complex(-Math.pow(b, z['re']), 0);
3204 case 3:
3205 return new Complex(0, -Math.pow(b, z['re']));
3206 }
3207 }
3208 }
3209
3210 /* I couldn't find a good formula, so here is a derivation and optimization
3211 *
3212 * z_1^z_2 = (a + bi)^(c + di)
3213 * = exp((c + di) * log(a + bi)
3214 * = pow(a^2 + b^2, (c + di) / 2) * exp(i(c + di)atan2(b, a))
3215 * =>...
3216 * Re = (pow(a^2 + b^2, c / 2) * exp(-d * atan2(b, a))) * cos(d * log(a^2 + b^2) / 2 + c * atan2(b, a))
3217 * Im = (pow(a^2 + b^2, c / 2) * exp(-d * atan2(b, a))) * sin(d * log(a^2 + b^2) / 2 + c * atan2(b, a))
3218 *
3219 * =>...
3220 * Re = exp(c * log(sqrt(a^2 + b^2)) - d * atan2(b, a)) * cos(d * log(sqrt(a^2 + b^2)) + c * atan2(b, a))
3221 * Im = exp(c * log(sqrt(a^2 + b^2)) - d * atan2(b, a)) * sin(d * log(sqrt(a^2 + b^2)) + c * atan2(b, a))
3222 *
3223 * =>
3224 * Re = exp(c * logsq2 - d * arg(z_1)) * cos(d * logsq2 + c * arg(z_1))
3225 * Im = exp(c * logsq2 - d * arg(z_1)) * sin(d * logsq2 + c * arg(z_1))
3226 *
3227 */
3228
3229 if (a === 0 && b === 0 && z['re'] > 0 && z['im'] >= 0) {
3230 return Complex['ZERO'];
3231 }
3232
3233 var arg = Math.atan2(b, a);
3234 var loh = logHypot(a, b);
3235
3236 a = Math.exp(z['re'] * loh - z['im'] * arg);
3237 b = z['im'] * loh + z['re'] * arg;
3238 return new Complex(
3239 a * Math.cos(b),
3240 a * Math.sin(b));
3241 },
3242
3243 /**
3244 * Calculate the complex square root
3245 *
3246 * @returns {Complex}
3247 */
3248 'sqrt': function() {
3249
3250 var a = this['re'];
3251 var b = this['im'];
3252 var r = this['abs']();
3253
3254 var re, im;
3255
3256 if (a >= 0) {
3257
3258 if (b === 0) {
3259 return new Complex(Math.sqrt(a), 0);
3260 }
3261
3262 re = 0.5 * Math.sqrt(2.0 * (r + a));
3263 } else {
3264 re = Math.abs(b) / Math.sqrt(2 * (r - a));
3265 }
3266
3267 if (a <= 0) {
3268 im = 0.5 * Math.sqrt(2.0 * (r - a));
3269 } else {
3270 im = Math.abs(b) / Math.sqrt(2 * (r + a));
3271 }
3272
3273 return new Complex(re, b < 0 ? -im : im);
3274 },
3275
3276 /**
3277 * Calculate the complex exponent
3278 *
3279 * @returns {Complex}
3280 */
3281 'exp': function() {
3282
3283 var tmp = Math.exp(this['re']);
3284
3285 if (this['im'] === 0) {
3286 //return new Complex(tmp, 0);
3287 }
3288 return new Complex(
3289 tmp * Math.cos(this['im']),
3290 tmp * Math.sin(this['im']));
3291 },
3292
3293 /**
3294 * Calculate the complex exponent and subtracts one.
3295 *
3296 * This may be more accurate than `Complex(x).exp().sub(1)` if
3297 * `x` is small.
3298 *
3299 * @returns {Complex}
3300 */
3301 'expm1': function() {
3302
3303 /**
3304 * exp(a + i*b) - 1
3305 = exp(a) * (cos(b) + j*sin(b)) - 1
3306 = expm1(a)*cos(b) + cosm1(b) + j*exp(a)*sin(b)
3307 */
3308
3309 var a = this['re'];
3310 var b = this['im'];
3311
3312 return new Complex(
3313 Math.expm1(a) * Math.cos(b) + cosm1(b),
3314 Math.exp(a) * Math.sin(b));
3315 },
3316
3317 /**
3318 * Calculate the natural log
3319 *
3320 * @returns {Complex}
3321 */
3322 'log': function() {
3323
3324 var a = this['re'];
3325 var b = this['im'];
3326
3327 if (b === 0 && a > 0) {
3328 //return new Complex(Math.log(a), 0);
3329 }
3330
3331 return new Complex(
3332 logHypot(a, b),
3333 Math.atan2(b, a));
3334 },
3335
3336 /**
3337 * Calculate the magnitude of the complex number
3338 *
3339 * @returns {number}
3340 */
3341 'abs': function() {
3342
3343 return hypot(this['re'], this['im']);
3344 },
3345
3346 /**
3347 * Calculate the angle of the complex number
3348 *
3349 * @returns {number}
3350 */
3351 'arg': function() {
3352
3353 return Math.atan2(this['im'], this['re']);
3354 },
3355
3356 /**
3357 * Calculate the sine of the complex number
3358 *
3359 * @returns {Complex}
3360 */
3361 'sin': function() {
3362
3363 // sin(c) = (e^b - e^(-b)) / (2i)
3364
3365 var a = this['re'];
3366 var b = this['im'];
3367
3368 return new Complex(
3369 Math.sin(a) * cosh(b),
3370 Math.cos(a) * sinh(b));
3371 },
3372
3373 /**
3374 * Calculate the cosine
3375 *
3376 * @returns {Complex}
3377 */
3378 'cos': function() {
3379
3380 // cos(z) = (e^b + e^(-b)) / 2
3381
3382 var a = this['re'];
3383 var b = this['im'];
3384
3385 return new Complex(
3386 Math.cos(a) * cosh(b),
3387 -Math.sin(a) * sinh(b));
3388 },
3389
3390 /**
3391 * Calculate the tangent
3392 *
3393 * @returns {Complex}
3394 */
3395 'tan': function() {
3396
3397 // tan(c) = (e^(ci) - e^(-ci)) / (i(e^(ci) + e^(-ci)))
3398
3399 var a = 2 * this['re'];
3400 var b = 2 * this['im'];
3401 var d = Math.cos(a) + cosh(b);
3402
3403 return new Complex(
3404 Math.sin(a) / d,
3405 sinh(b) / d);
3406 },
3407
3408 /**
3409 * Calculate the cotangent
3410 *
3411 * @returns {Complex}
3412 */
3413 'cot': function() {
3414
3415 // cot(c) = i(e^(ci) + e^(-ci)) / (e^(ci) - e^(-ci))
3416
3417 var a = 2 * this['re'];
3418 var b = 2 * this['im'];
3419 var d = Math.cos(a) - cosh(b);
3420
3421 return new Complex(
3422 -Math.sin(a) / d,
3423 sinh(b) / d);
3424 },
3425
3426 /**
3427 * Calculate the secant
3428 *
3429 * @returns {Complex}
3430 */
3431 'sec': function() {
3432
3433 // sec(c) = 2 / (e^(ci) + e^(-ci))
3434
3435 var a = this['re'];
3436 var b = this['im'];
3437 var d = 0.5 * cosh(2 * b) + 0.5 * Math.cos(2 * a);
3438
3439 return new Complex(
3440 Math.cos(a) * cosh(b) / d,
3441 Math.sin(a) * sinh(b) / d);
3442 },
3443
3444 /**
3445 * Calculate the cosecans
3446 *
3447 * @returns {Complex}
3448 */
3449 'csc': function() {
3450
3451 // csc(c) = 2i / (e^(ci) - e^(-ci))
3452
3453 var a = this['re'];
3454 var b = this['im'];
3455 var d = 0.5 * cosh(2 * b) - 0.5 * Math.cos(2 * a);
3456
3457 return new Complex(
3458 Math.sin(a) * cosh(b) / d,
3459 -Math.cos(a) * sinh(b) / d);
3460 },
3461
3462 /**
3463 * Calculate the complex arcus sinus
3464 *
3465 * @returns {Complex}
3466 */
3467 'asin': function() {
3468
3469 // asin(c) = -i * log(ci + sqrt(1 - c^2))
3470
3471 var a = this['re'];
3472 var b = this['im'];
3473
3474 var t1 = new Complex(
3475 b * b - a * a + 1,
3476 -2 * a * b)['sqrt']();
3477
3478 var t2 = new Complex(
3479 t1['re'] - b,
3480 t1['im'] + a)['log']();
3481
3482 return new Complex(t2['im'], -t2['re']);
3483 },
3484
3485 /**
3486 * Calculate the complex arcus cosinus
3487 *
3488 * @returns {Complex}
3489 */
3490 'acos': function() {
3491
3492 // acos(c) = i * log(c - i * sqrt(1 - c^2))
3493
3494 var a = this['re'];
3495 var b = this['im'];
3496
3497 var t1 = new Complex(
3498 b * b - a * a + 1,
3499 -2 * a * b)['sqrt']();
3500
3501 var t2 = new Complex(
3502 t1['re'] - b,
3503 t1['im'] + a)['log']();
3504
3505 return new Complex(Math.PI / 2 - t2['im'], t2['re']);
3506 },
3507
3508 /**
3509 * Calculate the complex arcus tangent
3510 *
3511 * @returns {Complex}
3512 */
3513 'atan': function() {
3514
3515 // atan(c) = i / 2 log((i + x) / (i - x))
3516
3517 var a = this['re'];
3518 var b = this['im'];
3519
3520 if (a === 0) {
3521
3522 if (b === 1) {
3523 return new Complex(0, Infinity);
3524 }
3525
3526 if (b === -1) {
3527 return new Complex(0, -Infinity);
3528 }
3529 }
3530
3531 var d = a * a + (1.0 - b) * (1.0 - b);
3532
3533 var t1 = new Complex(
3534 (1 - b * b - a * a) / d,
3535 -2 * a / d).log();
3536
3537 return new Complex(-0.5 * t1['im'], 0.5 * t1['re']);
3538 },
3539
3540 /**
3541 * Calculate the complex arcus cotangent
3542 *
3543 * @returns {Complex}
3544 */
3545 'acot': function() {
3546
3547 // acot(c) = i / 2 log((c - i) / (c + i))
3548
3549 var a = this['re'];
3550 var b = this['im'];
3551
3552 if (b === 0) {
3553 return new Complex(Math.atan2(1, a), 0);
3554 }
3555
3556 var d = a * a + b * b;
3557 return (d !== 0)
3558 ? new Complex(
3559 a / d,
3560 -b / d).atan()
3561 : new Complex(
3562 (a !== 0) ? a / 0 : 0,
3563 (b !== 0) ? -b / 0 : 0).atan();
3564 },
3565
3566 /**
3567 * Calculate the complex arcus secant
3568 *
3569 * @returns {Complex}
3570 */
3571 'asec': function() {
3572
3573 // asec(c) = -i * log(1 / c + sqrt(1 - i / c^2))
3574
3575 var a = this['re'];
3576 var b = this['im'];
3577
3578 if (a === 0 && b === 0) {
3579 return new Complex(0, Infinity);
3580 }
3581
3582 var d = a * a + b * b;
3583 return (d !== 0)
3584 ? new Complex(
3585 a / d,
3586 -b / d).acos()
3587 : new Complex(
3588 (a !== 0) ? a / 0 : 0,
3589 (b !== 0) ? -b / 0 : 0).acos();
3590 },
3591
3592 /**
3593 * Calculate the complex arcus cosecans
3594 *
3595 * @returns {Complex}
3596 */
3597 'acsc': function() {
3598
3599 // acsc(c) = -i * log(i / c + sqrt(1 - 1 / c^2))
3600
3601 var a = this['re'];
3602 var b = this['im'];
3603
3604 if (a === 0 && b === 0) {
3605 return new Complex(Math.PI / 2, Infinity);
3606 }
3607
3608 var d = a * a + b * b;
3609 return (d !== 0)
3610 ? new Complex(
3611 a / d,
3612 -b / d).asin()
3613 : new Complex(
3614 (a !== 0) ? a / 0 : 0,
3615 (b !== 0) ? -b / 0 : 0).asin();
3616 },
3617
3618 /**
3619 * Calculate the complex sinh
3620 *
3621 * @returns {Complex}
3622 */
3623 'sinh': function() {
3624
3625 // sinh(c) = (e^c - e^-c) / 2
3626
3627 var a = this['re'];
3628 var b = this['im'];
3629
3630 return new Complex(
3631 sinh(a) * Math.cos(b),
3632 cosh(a) * Math.sin(b));
3633 },
3634
3635 /**
3636 * Calculate the complex cosh
3637 *
3638 * @returns {Complex}
3639 */
3640 'cosh': function() {
3641
3642 // cosh(c) = (e^c + e^-c) / 2
3643
3644 var a = this['re'];
3645 var b = this['im'];
3646
3647 return new Complex(
3648 cosh(a) * Math.cos(b),
3649 sinh(a) * Math.sin(b));
3650 },
3651
3652 /**
3653 * Calculate the complex tanh
3654 *
3655 * @returns {Complex}
3656 */
3657 'tanh': function() {
3658
3659 // tanh(c) = (e^c - e^-c) / (e^c + e^-c)
3660
3661 var a = 2 * this['re'];
3662 var b = 2 * this['im'];
3663 var d = cosh(a) + Math.cos(b);
3664
3665 return new Complex(
3666 sinh(a) / d,
3667 Math.sin(b) / d);
3668 },
3669
3670 /**
3671 * Calculate the complex coth
3672 *
3673 * @returns {Complex}
3674 */
3675 'coth': function() {
3676
3677 // coth(c) = (e^c + e^-c) / (e^c - e^-c)
3678
3679 var a = 2 * this['re'];
3680 var b = 2 * this['im'];
3681 var d = cosh(a) - Math.cos(b);
3682
3683 return new Complex(
3684 sinh(a) / d,
3685 -Math.sin(b) / d);
3686 },
3687
3688 /**
3689 * Calculate the complex coth
3690 *
3691 * @returns {Complex}
3692 */
3693 'csch': function() {
3694
3695 // csch(c) = 2 / (e^c - e^-c)
3696
3697 var a = this['re'];
3698 var b = this['im'];
3699 var d = Math.cos(2 * b) - cosh(2 * a);
3700
3701 return new Complex(
3702 -2 * sinh(a) * Math.cos(b) / d,
3703 2 * cosh(a) * Math.sin(b) / d);
3704 },
3705
3706 /**
3707 * Calculate the complex sech
3708 *
3709 * @returns {Complex}
3710 */
3711 'sech': function() {
3712
3713 // sech(c) = 2 / (e^c + e^-c)
3714
3715 var a = this['re'];
3716 var b = this['im'];
3717 var d = Math.cos(2 * b) + cosh(2 * a);
3718
3719 return new Complex(
3720 2 * cosh(a) * Math.cos(b) / d,
3721 -2 * sinh(a) * Math.sin(b) / d);
3722 },
3723
3724 /**
3725 * Calculate the complex asinh
3726 *
3727 * @returns {Complex}
3728 */
3729 'asinh': function() {
3730
3731 // asinh(c) = log(c + sqrt(c^2 + 1))
3732
3733 var tmp = this['im'];
3734 this['im'] = -this['re'];
3735 this['re'] = tmp;
3736 var res = this['asin']();
3737
3738 this['re'] = -this['im'];
3739 this['im'] = tmp;
3740 tmp = res['re'];
3741
3742 res['re'] = -res['im'];
3743 res['im'] = tmp;
3744 return res;
3745 },
3746
3747 /**
3748 * Calculate the complex asinh
3749 *
3750 * @returns {Complex}
3751 */
3752 'acosh': function() {
3753
3754 // acosh(c) = log(c + sqrt(c^2 - 1))
3755
3756 var res = this['acos']();
3757 if (res['im'] <= 0) {
3758 var tmp = res['re'];
3759 res['re'] = -res['im'];
3760 res['im'] = tmp;
3761 } else {
3762 var tmp = res['im'];
3763 res['im'] = -res['re'];
3764 res['re'] = tmp;
3765 }
3766 return res;
3767 },
3768
3769 /**
3770 * Calculate the complex atanh
3771 *
3772 * @returns {Complex}
3773 */
3774 'atanh': function() {
3775
3776 // atanh(c) = log((1+c) / (1-c)) / 2
3777
3778 var a = this['re'];
3779 var b = this['im'];
3780
3781 var noIM = a > 1 && b === 0;
3782 var oneMinus = 1 - a;
3783 var onePlus = 1 + a;
3784 var d = oneMinus * oneMinus + b * b;
3785
3786 var x = (d !== 0)
3787 ? new Complex(
3788 (onePlus * oneMinus - b * b) / d,
3789 (b * oneMinus + onePlus * b) / d)
3790 : new Complex(
3791 (a !== -1) ? (a / 0) : 0,
3792 (b !== 0) ? (b / 0) : 0);
3793
3794 var temp = x['re'];
3795 x['re'] = logHypot(x['re'], x['im']) / 2;
3796 x['im'] = Math.atan2(x['im'], temp) / 2;
3797 if (noIM) {
3798 x['im'] = -x['im'];
3799 }
3800 return x;
3801 },
3802
3803 /**
3804 * Calculate the complex acoth
3805 *
3806 * @returns {Complex}
3807 */
3808 'acoth': function() {
3809
3810 // acoth(c) = log((c+1) / (c-1)) / 2
3811
3812 var a = this['re'];
3813 var b = this['im'];
3814
3815 if (a === 0 && b === 0) {
3816 return new Complex(0, Math.PI / 2);
3817 }
3818
3819 var d = a * a + b * b;
3820 return (d !== 0)
3821 ? new Complex(
3822 a / d,
3823 -b / d).atanh()
3824 : new Complex(
3825 (a !== 0) ? a / 0 : 0,
3826 (b !== 0) ? -b / 0 : 0).atanh();
3827 },
3828
3829 /**
3830 * Calculate the complex acsch
3831 *
3832 * @returns {Complex}
3833 */
3834 'acsch': function() {
3835
3836 // acsch(c) = log((1+sqrt(1+c^2))/c)
3837
3838 var a = this['re'];
3839 var b = this['im'];
3840
3841 if (b === 0) {
3842
3843 return new Complex(
3844 (a !== 0)
3845 ? Math.log(a + Math.sqrt(a * a + 1))
3846 : Infinity, 0);
3847 }
3848
3849 var d = a * a + b * b;
3850 return (d !== 0)
3851 ? new Complex(
3852 a / d,
3853 -b / d).asinh()
3854 : new Complex(
3855 (a !== 0) ? a / 0 : 0,
3856 (b !== 0) ? -b / 0 : 0).asinh();
3857 },
3858
3859 /**
3860 * Calculate the complex asech
3861 *
3862 * @returns {Complex}
3863 */
3864 'asech': function() {
3865
3866 // asech(c) = log((1+sqrt(1-c^2))/c)
3867
3868 var a = this['re'];
3869 var b = this['im'];
3870
3871 if (this['isZero']()) {
3872 return Complex['INFINITY'];
3873 }
3874
3875 var d = a * a + b * b;
3876 return (d !== 0)
3877 ? new Complex(
3878 a / d,
3879 -b / d).acosh()
3880 : new Complex(
3881 (a !== 0) ? a / 0 : 0,
3882 (b !== 0) ? -b / 0 : 0).acosh();
3883 },
3884
3885 /**
3886 * Calculate the complex inverse 1/z
3887 *
3888 * @returns {Complex}
3889 */
3890 'inverse': function() {
3891
3892 // 1 / 0 = Infinity and 1 / Infinity = 0
3893 if (this['isZero']()) {
3894 return Complex['INFINITY'];
3895 }
3896
3897 if (this['isInfinite']()) {
3898 return Complex['ZERO'];
3899 }
3900
3901 var a = this['re'];
3902 var b = this['im'];
3903
3904 var d = a * a + b * b;
3905
3906 return new Complex(a / d, -b / d);
3907 },
3908
3909 /**
3910 * Returns the complex conjugate
3911 *
3912 * @returns {Complex}
3913 */
3914 'conjugate': function() {
3915
3916 return new Complex(this['re'], -this['im']);
3917 },
3918
3919 /**
3920 * Gets the negated complex number
3921 *
3922 * @returns {Complex}
3923 */
3924 'neg': function() {
3925
3926 return new Complex(-this['re'], -this['im']);
3927 },
3928
3929 /**
3930 * Ceils the actual complex number
3931 *
3932 * @returns {Complex}
3933 */
3934 'ceil': function(places) {
3935
3936 places = Math.pow(10, places || 0);
3937
3938 return new Complex(
3939 Math.ceil(this['re'] * places) / places,
3940 Math.ceil(this['im'] * places) / places);
3941 },
3942
3943 /**
3944 * Floors the actual complex number
3945 *
3946 * @returns {Complex}
3947 */
3948 'floor': function(places) {
3949
3950 places = Math.pow(10, places || 0);
3951
3952 return new Complex(
3953 Math.floor(this['re'] * places) / places,
3954 Math.floor(this['im'] * places) / places);
3955 },
3956
3957 /**
3958 * Ceils the actual complex number
3959 *
3960 * @returns {Complex}
3961 */
3962 'round': function(places) {
3963
3964 places = Math.pow(10, places || 0);
3965
3966 return new Complex(
3967 Math.round(this['re'] * places) / places,
3968 Math.round(this['im'] * places) / places);
3969 },
3970
3971 /**
3972 * Compares two complex numbers
3973 *
3974 * **Note:** new Complex(Infinity).equals(Infinity) === false
3975 *
3976 * @returns {boolean}
3977 */
3978 'equals': function(a, b) {
3979
3980 var z = new Complex(a, b);
3981
3982 return Math.abs(z['re'] - this['re']) <= Complex['EPSILON'] &&
3983 Math.abs(z['im'] - this['im']) <= Complex['EPSILON'];
3984 },
3985
3986 /**
3987 * Clones the actual object
3988 *
3989 * @returns {Complex}
3990 */
3991 'clone': function() {
3992
3993 return new Complex(this['re'], this['im']);
3994 },
3995
3996 /**
3997 * Gets a string of the actual complex number
3998 *
3999 * @returns {string}
4000 */
4001 'toString': function() {
4002
4003 var a = this['re'];
4004 var b = this['im'];
4005 var ret = '';
4006
4007 if (this['isNaN']()) {
4008 return 'NaN';
4009 }
4010
4011 if (this['isZero']()) {
4012 return '0';
4013 }
4014
4015 if (this['isInfinite']()) {
4016 return 'Infinity';
4017 }
4018
4019 if (a !== 0) {
4020 ret += a;
4021 }
4022
4023 if (b !== 0) {
4024
4025 if (a !== 0) {
4026 ret += b < 0 ? ' - ' : ' + ';
4027 } else if (b < 0) {
4028 ret += '-';
4029 }
4030
4031 b = Math.abs(b);
4032
4033 if (1 !== b) {
4034 ret += b;
4035 }
4036 ret += 'i';
4037 }
4038
4039 if (!ret)
4040 return '0';
4041
4042 return ret;
4043 },
4044
4045 /**
4046 * Returns the actual number as a vector
4047 *
4048 * @returns {Array}
4049 */
4050 'toVector': function() {
4051
4052 return [this['re'], this['im']];
4053 },
4054
4055 /**
4056 * Returns the actual real value of the current object
4057 *
4058 * @returns {number|null}
4059 */
4060 'valueOf': function() {
4061
4062 if (this['im'] === 0) {
4063 return this['re'];
4064 }
4065 return null;
4066 },
4067
4068 /**
4069 * Determines whether a complex number is not on the Riemann sphere.
4070 *
4071 * @returns {boolean}
4072 */
4073 'isNaN': function() {
4074 return isNaN(this['re']) || isNaN(this['im']);
4075 },
4076
4077 /**
4078 * Determines whether or not a complex number is at the zero pole of the
4079 * Riemann sphere.
4080 *
4081 * @returns {boolean}
4082 */
4083 'isZero': function() {
4084 return (
4085 (this['re'] === 0 || this['re'] === -0) &&
4086 (this['im'] === 0 || this['im'] === -0)
4087 );
4088 },
4089
4090 /**
4091 * Determines whether a complex number is not at the infinity pole of the
4092 * Riemann sphere.
4093 *
4094 * @returns {boolean}
4095 */
4096 'isFinite': function() {
4097 return isFinite(this['re']) && isFinite(this['im']);
4098 },
4099
4100 /**
4101 * Determines whether or not a complex number is at the infinity pole of the
4102 * Riemann sphere.
4103 *
4104 * @returns {boolean}
4105 */
4106 'isInfinite': function() {
4107 return !(this['isNaN']() || this['isFinite']());
4108 }
4109 };
4110
4111 Complex['ZERO'] = new Complex(0, 0);
4112 Complex['ONE'] = new Complex(1, 0);
4113 Complex['I'] = new Complex(0, 1);
4114 Complex['PI'] = new Complex(Math.PI, 0);
4115 Complex['E'] = new Complex(Math.E, 0);
4116 Complex['INFINITY'] = new Complex(Infinity, Infinity);
4117 Complex['NAN'] = new Complex(NaN, NaN);
4118 Complex['EPSILON'] = 1e-16;
4119
4120 if (true) {
4121 !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = (function() {
4122 return Complex;
4123 }).apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__),
4124 __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
4125 } else {}
4126
4127})(this);
4128
4129
4130/***/ }),
4131/* 10 */
4132/***/ (function(module, __webpack_exports__, __webpack_require__) {
4133
4134"use strict";
4135/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return IndexError; });
4136/**
4137 * Create a range error with the message:
4138 * 'Index out of range (index < min)'
4139 * 'Index out of range (index < max)'
4140 *
4141 * @param {number} index The actual index
4142 * @param {number} [min=0] Minimum index (included)
4143 * @param {number} [max] Maximum index (excluded)
4144 * @extends RangeError
4145 */
4146function IndexError(index, min, max) {
4147 if (!(this instanceof IndexError)) {
4148 throw new SyntaxError('Constructor must be called with the new operator');
4149 }
4150
4151 this.index = index;
4152
4153 if (arguments.length < 3) {
4154 this.min = 0;
4155 this.max = min;
4156 } else {
4157 this.min = min;
4158 this.max = max;
4159 }
4160
4161 if (this.min !== undefined && this.index < this.min) {
4162 this.message = 'Index out of range (' + this.index + ' < ' + this.min + ')';
4163 } else if (this.max !== undefined && this.index >= this.max) {
4164 this.message = 'Index out of range (' + this.index + ' > ' + (this.max - 1) + ')';
4165 } else {
4166 this.message = 'Index out of range (' + this.index + ')';
4167 }
4168
4169 this.stack = new Error().stack;
4170}
4171IndexError.prototype = new RangeError();
4172IndexError.prototype.constructor = RangeError;
4173IndexError.prototype.name = 'IndexError';
4174IndexError.prototype.isIndexError = true;
4175
4176/***/ }),
4177/* 11 */
4178/***/ (function(module, exports, __webpack_require__) {
4179
4180var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/**
4181 * @license Fraction.js v4.0.12 09/09/2015
4182 * http://www.xarg.org/2014/03/rational-numbers-in-javascript/
4183 *
4184 * Copyright (c) 2015, Robert Eisele (robert@xarg.org)
4185 * Dual licensed under the MIT or GPL Version 2 licenses.
4186 **/
4187
4188
4189/**
4190 *
4191 * This class offers the possibility to calculate fractions.
4192 * You can pass a fraction in different formats. Either as array, as double, as string or as an integer.
4193 *
4194 * Array/Object form
4195 * [ 0 => <nominator>, 1 => <denominator> ]
4196 * [ n => <nominator>, d => <denominator> ]
4197 *
4198 * Integer form
4199 * - Single integer value
4200 *
4201 * Double form
4202 * - Single double value
4203 *
4204 * String form
4205 * 123.456 - a simple double
4206 * 123/456 - a string fraction
4207 * 123.'456' - a double with repeating decimal places
4208 * 123.(456) - synonym
4209 * 123.45'6' - a double with repeating last place
4210 * 123.45(6) - synonym
4211 *
4212 * Example:
4213 *
4214 * var f = new Fraction("9.4'31'");
4215 * f.mul([-4, 3]).div(4.9);
4216 *
4217 */
4218
4219(function(root) {
4220
4221 "use strict";
4222
4223 // Maximum search depth for cyclic rational numbers. 2000 should be more than enough.
4224 // Example: 1/7 = 0.(142857) has 6 repeating decimal places.
4225 // If MAX_CYCLE_LEN gets reduced, long cycles will not be detected and toString() only gets the first 10 digits
4226 var MAX_CYCLE_LEN = 2000;
4227
4228 // Parsed data to avoid calling "new" all the time
4229 var P = {
4230 "s": 1,
4231 "n": 0,
4232 "d": 1
4233 };
4234
4235 function createError(name) {
4236
4237 function errorConstructor() {
4238 var temp = Error.apply(this, arguments);
4239 temp['name'] = this['name'] = name;
4240 this['stack'] = temp['stack'];
4241 this['message'] = temp['message'];
4242 }
4243
4244 /**
4245 * Error constructor
4246 *
4247 * @constructor
4248 */
4249 function IntermediateInheritor() {}
4250 IntermediateInheritor.prototype = Error.prototype;
4251 errorConstructor.prototype = new IntermediateInheritor();
4252
4253 return errorConstructor;
4254 }
4255
4256 var DivisionByZero = Fraction['DivisionByZero'] = createError('DivisionByZero');
4257 var InvalidParameter = Fraction['InvalidParameter'] = createError('InvalidParameter');
4258
4259 function assign(n, s) {
4260
4261 if (isNaN(n = parseInt(n, 10))) {
4262 throwInvalidParam();
4263 }
4264 return n * s;
4265 }
4266
4267 function throwInvalidParam() {
4268 throw new InvalidParameter();
4269 }
4270
4271 var parse = function(p1, p2) {
4272
4273 var n = 0, d = 1, s = 1;
4274 var v = 0, w = 0, x = 0, y = 1, z = 1;
4275
4276 var A = 0, B = 1;
4277 var C = 1, D = 1;
4278
4279 var N = 10000000;
4280 var M;
4281
4282 if (p1 === undefined || p1 === null) {
4283 /* void */
4284 } else if (p2 !== undefined) {
4285 n = p1;
4286 d = p2;
4287 s = n * d;
4288 } else
4289 switch (typeof p1) {
4290
4291 case "object":
4292 {
4293 if ("d" in p1 && "n" in p1) {
4294 n = p1["n"];
4295 d = p1["d"];
4296 if ("s" in p1)
4297 n *= p1["s"];
4298 } else if (0 in p1) {
4299 n = p1[0];
4300 if (1 in p1)
4301 d = p1[1];
4302 } else {
4303 throwInvalidParam();
4304 }
4305 s = n * d;
4306 break;
4307 }
4308 case "number":
4309 {
4310 if (p1 < 0) {
4311 s = p1;
4312 p1 = -p1;
4313 }
4314
4315 if (p1 % 1 === 0) {
4316 n = p1;
4317 } else if (p1 > 0) { // check for != 0, scale would become NaN (log(0)), which converges really slow
4318
4319 if (p1 >= 1) {
4320 z = Math.pow(10, Math.floor(1 + Math.log(p1) / Math.LN10));
4321 p1 /= z;
4322 }
4323
4324 // Using Farey Sequences
4325 // http://www.johndcook.com/blog/2010/10/20/best-rational-approximation/
4326
4327 while (B <= N && D <= N) {
4328 M = (A + C) / (B + D);
4329
4330 if (p1 === M) {
4331 if (B + D <= N) {
4332 n = A + C;
4333 d = B + D;
4334 } else if (D > B) {
4335 n = C;
4336 d = D;
4337 } else {
4338 n = A;
4339 d = B;
4340 }
4341 break;
4342
4343 } else {
4344
4345 if (p1 > M) {
4346 A += C;
4347 B += D;
4348 } else {
4349 C += A;
4350 D += B;
4351 }
4352
4353 if (B > N) {
4354 n = C;
4355 d = D;
4356 } else {
4357 n = A;
4358 d = B;
4359 }
4360 }
4361 }
4362 n *= z;
4363 } else if (isNaN(p1) || isNaN(p2)) {
4364 d = n = NaN;
4365 }
4366 break;
4367 }
4368 case "string":
4369 {
4370 B = p1.match(/\d+|./g);
4371
4372 if (B === null)
4373 throwInvalidParam();
4374
4375 if (B[A] === '-') {// Check for minus sign at the beginning
4376 s = -1;
4377 A++;
4378 } else if (B[A] === '+') {// Check for plus sign at the beginning
4379 A++;
4380 }
4381
4382 if (B.length === A + 1) { // Check if it's just a simple number "1234"
4383 w = assign(B[A++], s);
4384 } else if (B[A + 1] === '.' || B[A] === '.') { // Check if it's a decimal number
4385
4386 if (B[A] !== '.') { // Handle 0.5 and .5
4387 v = assign(B[A++], s);
4388 }
4389 A++;
4390
4391 // Check for decimal places
4392 if (A + 1 === B.length || B[A + 1] === '(' && B[A + 3] === ')' || B[A + 1] === "'" && B[A + 3] === "'") {
4393 w = assign(B[A], s);
4394 y = Math.pow(10, B[A].length);
4395 A++;
4396 }
4397
4398 // Check for repeating places
4399 if (B[A] === '(' && B[A + 2] === ')' || B[A] === "'" && B[A + 2] === "'") {
4400 x = assign(B[A + 1], s);
4401 z = Math.pow(10, B[A + 1].length) - 1;
4402 A += 3;
4403 }
4404
4405 } else if (B[A + 1] === '/' || B[A + 1] === ':') { // Check for a simple fraction "123/456" or "123:456"
4406 w = assign(B[A], s);
4407 y = assign(B[A + 2], 1);
4408 A += 3;
4409 } else if (B[A + 3] === '/' && B[A + 1] === ' ') { // Check for a complex fraction "123 1/2"
4410 v = assign(B[A], s);
4411 w = assign(B[A + 2], s);
4412 y = assign(B[A + 4], 1);
4413 A += 5;
4414 }
4415
4416 if (B.length <= A) { // Check for more tokens on the stack
4417 d = y * z;
4418 s = /* void */
4419 n = x + d * v + z * w;
4420 break;
4421 }
4422
4423 /* Fall through on error */
4424 }
4425 default:
4426 throwInvalidParam();
4427 }
4428
4429 if (d === 0) {
4430 throw new DivisionByZero();
4431 }
4432
4433 P["s"] = s < 0 ? -1 : 1;
4434 P["n"] = Math.abs(n);
4435 P["d"] = Math.abs(d);
4436 };
4437
4438 function modpow(b, e, m) {
4439
4440 var r = 1;
4441 for (; e > 0; b = (b * b) % m, e >>= 1) {
4442
4443 if (e & 1) {
4444 r = (r * b) % m;
4445 }
4446 }
4447 return r;
4448 }
4449
4450
4451 function cycleLen(n, d) {
4452
4453 for (; d % 2 === 0;
4454 d /= 2) {
4455 }
4456
4457 for (; d % 5 === 0;
4458 d /= 5) {
4459 }
4460
4461 if (d === 1) // Catch non-cyclic numbers
4462 return 0;
4463
4464 // If we would like to compute really large numbers quicker, we could make use of Fermat's little theorem:
4465 // 10^(d-1) % d == 1
4466 // However, we don't need such large numbers and MAX_CYCLE_LEN should be the capstone,
4467 // as we want to translate the numbers to strings.
4468
4469 var rem = 10 % d;
4470 var t = 1;
4471
4472 for (; rem !== 1; t++) {
4473 rem = rem * 10 % d;
4474
4475 if (t > MAX_CYCLE_LEN)
4476 return 0; // Returning 0 here means that we don't print it as a cyclic number. It's likely that the answer is `d-1`
4477 }
4478 return t;
4479 }
4480
4481
4482 function cycleStart(n, d, len) {
4483
4484 var rem1 = 1;
4485 var rem2 = modpow(10, len, d);
4486
4487 for (var t = 0; t < 300; t++) { // s < ~log10(Number.MAX_VALUE)
4488 // Solve 10^s == 10^(s+t) (mod d)
4489
4490 if (rem1 === rem2)
4491 return t;
4492
4493 rem1 = rem1 * 10 % d;
4494 rem2 = rem2 * 10 % d;
4495 }
4496 return 0;
4497 }
4498
4499 function gcd(a, b) {
4500
4501 if (!a)
4502 return b;
4503 if (!b)
4504 return a;
4505
4506 while (1) {
4507 a %= b;
4508 if (!a)
4509 return b;
4510 b %= a;
4511 if (!b)
4512 return a;
4513 }
4514 };
4515
4516 /**
4517 * Module constructor
4518 *
4519 * @constructor
4520 * @param {number|Fraction=} a
4521 * @param {number=} b
4522 */
4523 function Fraction(a, b) {
4524
4525 if (!(this instanceof Fraction)) {
4526 return new Fraction(a, b);
4527 }
4528
4529 parse(a, b);
4530
4531 if (Fraction['REDUCE']) {
4532 a = gcd(P["d"], P["n"]); // Abuse a
4533 } else {
4534 a = 1;
4535 }
4536
4537 this["s"] = P["s"];
4538 this["n"] = P["n"] / a;
4539 this["d"] = P["d"] / a;
4540 }
4541
4542 /**
4543 * Boolean global variable to be able to disable automatic reduction of the fraction
4544 *
4545 */
4546 Fraction['REDUCE'] = 1;
4547
4548 Fraction.prototype = {
4549
4550 "s": 1,
4551 "n": 0,
4552 "d": 1,
4553
4554 /**
4555 * Calculates the absolute value
4556 *
4557 * Ex: new Fraction(-4).abs() => 4
4558 **/
4559 "abs": function() {
4560
4561 return new Fraction(this["n"], this["d"]);
4562 },
4563
4564 /**
4565 * Inverts the sign of the current fraction
4566 *
4567 * Ex: new Fraction(-4).neg() => 4
4568 **/
4569 "neg": function() {
4570
4571 return new Fraction(-this["s"] * this["n"], this["d"]);
4572 },
4573
4574 /**
4575 * Adds two rational numbers
4576 *
4577 * Ex: new Fraction({n: 2, d: 3}).add("14.9") => 467 / 30
4578 **/
4579 "add": function(a, b) {
4580
4581 parse(a, b);
4582 return new Fraction(
4583 this["s"] * this["n"] * P["d"] + P["s"] * this["d"] * P["n"],
4584 this["d"] * P["d"]
4585 );
4586 },
4587
4588 /**
4589 * Subtracts two rational numbers
4590 *
4591 * Ex: new Fraction({n: 2, d: 3}).add("14.9") => -427 / 30
4592 **/
4593 "sub": function(a, b) {
4594
4595 parse(a, b);
4596 return new Fraction(
4597 this["s"] * this["n"] * P["d"] - P["s"] * this["d"] * P["n"],
4598 this["d"] * P["d"]
4599 );
4600 },
4601
4602 /**
4603 * Multiplies two rational numbers
4604 *
4605 * Ex: new Fraction("-17.(345)").mul(3) => 5776 / 111
4606 **/
4607 "mul": function(a, b) {
4608
4609 parse(a, b);
4610 return new Fraction(
4611 this["s"] * P["s"] * this["n"] * P["n"],
4612 this["d"] * P["d"]
4613 );
4614 },
4615
4616 /**
4617 * Divides two rational numbers
4618 *
4619 * Ex: new Fraction("-17.(345)").inverse().div(3)
4620 **/
4621 "div": function(a, b) {
4622
4623 parse(a, b);
4624 return new Fraction(
4625 this["s"] * P["s"] * this["n"] * P["d"],
4626 this["d"] * P["n"]
4627 );
4628 },
4629
4630 /**
4631 * Clones the actual object
4632 *
4633 * Ex: new Fraction("-17.(345)").clone()
4634 **/
4635 "clone": function() {
4636 return new Fraction(this);
4637 },
4638
4639 /**
4640 * Calculates the modulo of two rational numbers - a more precise fmod
4641 *
4642 * Ex: new Fraction('4.(3)').mod([7, 8]) => (13/3) % (7/8) = (5/6)
4643 **/
4644 "mod": function(a, b) {
4645
4646 if (isNaN(this['n']) || isNaN(this['d'])) {
4647 return new Fraction(NaN);
4648 }
4649
4650 if (a === undefined) {
4651 return new Fraction(this["s"] * this["n"] % this["d"], 1);
4652 }
4653
4654 parse(a, b);
4655 if (0 === P["n"] && 0 === this["d"]) {
4656 Fraction(0, 0); // Throw DivisionByZero
4657 }
4658
4659 /*
4660 * First silly attempt, kinda slow
4661 *
4662 return that["sub"]({
4663 "n": num["n"] * Math.floor((this.n / this.d) / (num.n / num.d)),
4664 "d": num["d"],
4665 "s": this["s"]
4666 });*/
4667
4668 /*
4669 * New attempt: a1 / b1 = a2 / b2 * q + r
4670 * => b2 * a1 = a2 * b1 * q + b1 * b2 * r
4671 * => (b2 * a1 % a2 * b1) / (b1 * b2)
4672 */
4673 return new Fraction(
4674 this["s"] * (P["d"] * this["n"]) % (P["n"] * this["d"]),
4675 P["d"] * this["d"]
4676 );
4677 },
4678
4679 /**
4680 * Calculates the fractional gcd of two rational numbers
4681 *
4682 * Ex: new Fraction(5,8).gcd(3,7) => 1/56
4683 */
4684 "gcd": function(a, b) {
4685
4686 parse(a, b);
4687
4688 // gcd(a / b, c / d) = gcd(a, c) / lcm(b, d)
4689
4690 return new Fraction(gcd(P["n"], this["n"]) * gcd(P["d"], this["d"]), P["d"] * this["d"]);
4691 },
4692
4693 /**
4694 * Calculates the fractional lcm of two rational numbers
4695 *
4696 * Ex: new Fraction(5,8).lcm(3,7) => 15
4697 */
4698 "lcm": function(a, b) {
4699
4700 parse(a, b);
4701
4702 // lcm(a / b, c / d) = lcm(a, c) / gcd(b, d)
4703
4704 if (P["n"] === 0 && this["n"] === 0) {
4705 return new Fraction;
4706 }
4707 return new Fraction(P["n"] * this["n"], gcd(P["n"], this["n"]) * gcd(P["d"], this["d"]));
4708 },
4709
4710 /**
4711 * Calculates the ceil of a rational number
4712 *
4713 * Ex: new Fraction('4.(3)').ceil() => (5 / 1)
4714 **/
4715 "ceil": function(places) {
4716
4717 places = Math.pow(10, places || 0);
4718
4719 if (isNaN(this["n"]) || isNaN(this["d"])) {
4720 return new Fraction(NaN);
4721 }
4722 return new Fraction(Math.ceil(places * this["s"] * this["n"] / this["d"]), places);
4723 },
4724
4725 /**
4726 * Calculates the floor of a rational number
4727 *
4728 * Ex: new Fraction('4.(3)').floor() => (4 / 1)
4729 **/
4730 "floor": function(places) {
4731
4732 places = Math.pow(10, places || 0);
4733
4734 if (isNaN(this["n"]) || isNaN(this["d"])) {
4735 return new Fraction(NaN);
4736 }
4737 return new Fraction(Math.floor(places * this["s"] * this["n"] / this["d"]), places);
4738 },
4739
4740 /**
4741 * Rounds a rational numbers
4742 *
4743 * Ex: new Fraction('4.(3)').round() => (4 / 1)
4744 **/
4745 "round": function(places) {
4746
4747 places = Math.pow(10, places || 0);
4748
4749 if (isNaN(this["n"]) || isNaN(this["d"])) {
4750 return new Fraction(NaN);
4751 }
4752 return new Fraction(Math.round(places * this["s"] * this["n"] / this["d"]), places);
4753 },
4754
4755 /**
4756 * Gets the inverse of the fraction, means numerator and denumerator are exchanged
4757 *
4758 * Ex: new Fraction([-3, 4]).inverse() => -4 / 3
4759 **/
4760 "inverse": function() {
4761
4762 return new Fraction(this["s"] * this["d"], this["n"]);
4763 },
4764
4765 /**
4766 * Calculates the fraction to some integer exponent
4767 *
4768 * Ex: new Fraction(-1,2).pow(-3) => -8
4769 */
4770 "pow": function(m) {
4771
4772 if (m < 0) {
4773 return new Fraction(Math.pow(this['s'] * this["d"], -m), Math.pow(this["n"], -m));
4774 } else {
4775 return new Fraction(Math.pow(this['s'] * this["n"], m), Math.pow(this["d"], m));
4776 }
4777 },
4778
4779 /**
4780 * Check if two rational numbers are the same
4781 *
4782 * Ex: new Fraction(19.6).equals([98, 5]);
4783 **/
4784 "equals": function(a, b) {
4785
4786 parse(a, b);
4787 return this["s"] * this["n"] * P["d"] === P["s"] * P["n"] * this["d"]; // Same as compare() === 0
4788 },
4789
4790 /**
4791 * Check if two rational numbers are the same
4792 *
4793 * Ex: new Fraction(19.6).equals([98, 5]);
4794 **/
4795 "compare": function(a, b) {
4796
4797 parse(a, b);
4798 var t = (this["s"] * this["n"] * P["d"] - P["s"] * P["n"] * this["d"]);
4799 return (0 < t) - (t < 0);
4800 },
4801
4802 "simplify": function(eps) {
4803
4804 // First naive implementation, needs improvement
4805
4806 if (isNaN(this['n']) || isNaN(this['d'])) {
4807 return this;
4808 }
4809
4810 var cont = this['abs']()['toContinued']();
4811
4812 eps = eps || 0.001;
4813
4814 function rec(a) {
4815 if (a.length === 1)
4816 return new Fraction(a[0]);
4817 return rec(a.slice(1))['inverse']()['add'](a[0]);
4818 }
4819
4820 for (var i = 0; i < cont.length; i++) {
4821 var tmp = rec(cont.slice(0, i + 1));
4822 if (tmp['sub'](this['abs']())['abs']().valueOf() < eps) {
4823 return tmp['mul'](this['s']);
4824 }
4825 }
4826 return this;
4827 },
4828
4829 /**
4830 * Check if two rational numbers are divisible
4831 *
4832 * Ex: new Fraction(19.6).divisible(1.5);
4833 */
4834 "divisible": function(a, b) {
4835
4836 parse(a, b);
4837 return !(!(P["n"] * this["d"]) || ((this["n"] * P["d"]) % (P["n"] * this["d"])));
4838 },
4839
4840 /**
4841 * Returns a decimal representation of the fraction
4842 *
4843 * Ex: new Fraction("100.'91823'").valueOf() => 100.91823918239183
4844 **/
4845 'valueOf': function() {
4846
4847 return this["s"] * this["n"] / this["d"];
4848 },
4849
4850 /**
4851 * Returns a string-fraction representation of a Fraction object
4852 *
4853 * Ex: new Fraction("1.'3'").toFraction() => "4 1/3"
4854 **/
4855 'toFraction': function(excludeWhole) {
4856
4857 var whole, str = "";
4858 var n = this["n"];
4859 var d = this["d"];
4860 if (this["s"] < 0) {
4861 str += '-';
4862 }
4863
4864 if (d === 1) {
4865 str += n;
4866 } else {
4867
4868 if (excludeWhole && (whole = Math.floor(n / d)) > 0) {
4869 str += whole;
4870 str += " ";
4871 n %= d;
4872 }
4873
4874 str += n;
4875 str += '/';
4876 str += d;
4877 }
4878 return str;
4879 },
4880
4881 /**
4882 * Returns a latex representation of a Fraction object
4883 *
4884 * Ex: new Fraction("1.'3'").toLatex() => "\frac{4}{3}"
4885 **/
4886 'toLatex': function(excludeWhole) {
4887
4888 var whole, str = "";
4889 var n = this["n"];
4890 var d = this["d"];
4891 if (this["s"] < 0) {
4892 str += '-';
4893 }
4894
4895 if (d === 1) {
4896 str += n;
4897 } else {
4898
4899 if (excludeWhole && (whole = Math.floor(n / d)) > 0) {
4900 str += whole;
4901 n %= d;
4902 }
4903
4904 str += "\\frac{";
4905 str += n;
4906 str += '}{';
4907 str += d;
4908 str += '}';
4909 }
4910 return str;
4911 },
4912
4913 /**
4914 * Returns an array of continued fraction elements
4915 *
4916 * Ex: new Fraction("7/8").toContinued() => [0,1,7]
4917 */
4918 'toContinued': function() {
4919
4920 var t;
4921 var a = this['n'];
4922 var b = this['d'];
4923 var res = [];
4924
4925 if (isNaN(this['n']) || isNaN(this['d'])) {
4926 return res;
4927 }
4928
4929 do {
4930 res.push(Math.floor(a / b));
4931 t = a % b;
4932 a = b;
4933 b = t;
4934 } while (a !== 1);
4935
4936 return res;
4937 },
4938
4939 /**
4940 * Creates a string representation of a fraction with all digits
4941 *
4942 * Ex: new Fraction("100.'91823'").toString() => "100.(91823)"
4943 **/
4944 'toString': function(dec) {
4945
4946 var g;
4947 var N = this["n"];
4948 var D = this["d"];
4949
4950 if (isNaN(N) || isNaN(D)) {
4951 return "NaN";
4952 }
4953
4954 if (!Fraction['REDUCE']) {
4955 g = gcd(N, D);
4956 N /= g;
4957 D /= g;
4958 }
4959
4960 dec = dec || 15; // 15 = decimal places when no repitation
4961
4962 var cycLen = cycleLen(N, D); // Cycle length
4963 var cycOff = cycleStart(N, D, cycLen); // Cycle start
4964
4965 var str = this['s'] === -1 ? "-" : "";
4966
4967 str += N / D | 0;
4968
4969 N %= D;
4970 N *= 10;
4971
4972 if (N)
4973 str += ".";
4974
4975 if (cycLen) {
4976
4977 for (var i = cycOff; i--; ) {
4978 str += N / D | 0;
4979 N %= D;
4980 N *= 10;
4981 }
4982 str += "(";
4983 for (var i = cycLen; i--; ) {
4984 str += N / D | 0;
4985 N %= D;
4986 N *= 10;
4987 }
4988 str += ")";
4989 } else {
4990 for (var i = dec; N && i--; ) {
4991 str += N / D | 0;
4992 N %= D;
4993 N *= 10;
4994 }
4995 }
4996 return str;
4997 }
4998 };
4999
5000 if (true) {
5001 !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = (function() {
5002 return Fraction;
5003 }).apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__),
5004 __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
5005 } else {}
5006
5007})(this);
5008
5009
5010/***/ }),
5011/* 12 */
5012/***/ (function(module, exports) {
5013
5014/*
5015 * Natural Sort algorithm for Javascript - Version 0.7 - Released under MIT license
5016 * Author: Jim Palmer (based on chunking idea from Dave Koelle)
5017 */
5018/*jshint unused:false */
5019module.exports = function naturalSort (a, b) {
5020 "use strict";
5021 var re = /(^([+\-]?(?:0|[1-9]\d*)(?:\.\d*)?(?:[eE][+\-]?\d+)?)?$|^0x[0-9a-f]+$|\d+)/gi,
5022 sre = /(^[ ]*|[ ]*$)/g,
5023 dre = /(^([\w ]+,?[\w ]+)?[\w ]+,?[\w ]+\d+:\d+(:\d+)?[\w ]?|^\d{1,4}[\/\-]\d{1,4}[\/\-]\d{1,4}|^\w+, \w+ \d+, \d{4})/,
5024 hre = /^0x[0-9a-f]+$/i,
5025 ore = /^0/,
5026 i = function(s) { return naturalSort.insensitive && ('' + s).toLowerCase() || '' + s; },
5027 // convert all to strings strip whitespace
5028 x = i(a).replace(sre, '') || '',
5029 y = i(b).replace(sre, '') || '',
5030 // chunk/tokenize
5031 xN = x.replace(re, '\0$1\0').replace(/\0$/,'').replace(/^\0/,'').split('\0'),
5032 yN = y.replace(re, '\0$1\0').replace(/\0$/,'').replace(/^\0/,'').split('\0'),
5033 // numeric, hex or date detection
5034 xD = parseInt(x.match(hre), 16) || (xN.length !== 1 && x.match(dre) && Date.parse(x)),
5035 yD = parseInt(y.match(hre), 16) || xD && y.match(dre) && Date.parse(y) || null,
5036 oFxNcL, oFyNcL;
5037 // first try and sort Hex codes or Dates
5038 if (yD) {
5039 if ( xD < yD ) { return -1; }
5040 else if ( xD > yD ) { return 1; }
5041 }
5042 // natural sorting through split numeric strings and default strings
5043 for(var cLoc=0, numS=Math.max(xN.length, yN.length); cLoc < numS; cLoc++) {
5044 // find floats not starting with '0', string or 0 if not defined (Clint Priest)
5045 oFxNcL = !(xN[cLoc] || '').match(ore) && parseFloat(xN[cLoc]) || xN[cLoc] || 0;
5046 oFyNcL = !(yN[cLoc] || '').match(ore) && parseFloat(yN[cLoc]) || yN[cLoc] || 0;
5047 // handle numeric vs string comparison - number < string - (Kyle Adams)
5048 if (isNaN(oFxNcL) !== isNaN(oFyNcL)) { return (isNaN(oFxNcL)) ? 1 : -1; }
5049 // rely on string comparison if different types - i.e. '02' < 2 != '02' < '2'
5050 else if (typeof oFxNcL !== typeof oFyNcL) {
5051 oFxNcL += '';
5052 oFyNcL += '';
5053 }
5054 if (oFxNcL < oFyNcL) { return -1; }
5055 if (oFxNcL > oFyNcL) { return 1; }
5056 }
5057 return 0;
5058};
5059
5060
5061/***/ }),
5062/* 13 */
5063/***/ (function(module, __webpack_exports__, __webpack_require__) {
5064
5065"use strict";
5066/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return ArgumentsError; });
5067/**
5068 * Create a syntax error with the message:
5069 * 'Wrong number of arguments in function <fn> (<count> provided, <min>-<max> expected)'
5070 * @param {string} fn Function name
5071 * @param {number} count Actual argument count
5072 * @param {number} min Minimum required argument count
5073 * @param {number} [max] Maximum required argument count
5074 * @extends Error
5075 */
5076function ArgumentsError(fn, count, min, max) {
5077 if (!(this instanceof ArgumentsError)) {
5078 throw new SyntaxError('Constructor must be called with the new operator');
5079 }
5080
5081 this.fn = fn;
5082 this.count = count;
5083 this.min = min;
5084 this.max = max;
5085 this.message = 'Wrong number of arguments in function ' + fn + ' (' + count + ' provided, ' + min + (max !== undefined && max !== null ? '-' + max : '') + ' expected)';
5086 this.stack = new Error().stack;
5087}
5088ArgumentsError.prototype = new Error();
5089ArgumentsError.prototype.constructor = Error;
5090ArgumentsError.prototype.name = 'ArgumentsError';
5091ArgumentsError.prototype.isArgumentsError = true;
5092
5093/***/ }),
5094/* 14 */
5095/***/ (function(module, exports, __webpack_require__) {
5096
5097"use strict";
5098var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/**
5099 * typed-function
5100 *
5101 * Type checking for JavaScript functions
5102 *
5103 * https://github.com/josdejong/typed-function
5104 */
5105
5106
5107(function (root, factory) {
5108 if (true) {
5109 // AMD. Register as an anonymous module.
5110 !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory),
5111 __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
5112 (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__),
5113 __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
5114 } else {}
5115}(this, function () {
5116
5117 function ok () {
5118 return true;
5119 }
5120
5121 function notOk () {
5122 return false;
5123 }
5124
5125 function undef () {
5126 return undefined;
5127 }
5128
5129 /**
5130 * @typedef {{
5131 * params: Param[],
5132 * fn: function
5133 * }} Signature
5134 *
5135 * @typedef {{
5136 * types: Type[],
5137 * restParam: boolean
5138 * }} Param
5139 *
5140 * @typedef {{
5141 * name: string,
5142 * typeIndex: number,
5143 * test: function,
5144 * conversion?: ConversionDef,
5145 * conversionIndex: number,
5146 * }} Type
5147 *
5148 * @typedef {{
5149 * from: string,
5150 * to: string,
5151 * convert: function (*) : *
5152 * }} ConversionDef
5153 *
5154 * @typedef {{
5155 * name: string,
5156 * test: function(*) : boolean
5157 * }} TypeDef
5158 */
5159
5160 // create a new instance of typed-function
5161 function create () {
5162 // data type tests
5163 var _types = [
5164 { name: 'number', test: function (x) { return typeof x === 'number' } },
5165 { name: 'string', test: function (x) { return typeof x === 'string' } },
5166 { name: 'boolean', test: function (x) { return typeof x === 'boolean' } },
5167 { name: 'Function', test: function (x) { return typeof x === 'function'} },
5168 { name: 'Array', test: Array.isArray },
5169 { name: 'Date', test: function (x) { return x instanceof Date } },
5170 { name: 'RegExp', test: function (x) { return x instanceof RegExp } },
5171 { name: 'Object', test: function (x) {
5172 return typeof x === 'object' && x !== null && x.constructor === Object
5173 }},
5174 { name: 'null', test: function (x) { return x === null } },
5175 { name: 'undefined', test: function (x) { return x === undefined } }
5176 ];
5177
5178 var anyType = {
5179 name: 'any',
5180 test: ok
5181 }
5182
5183 // types which need to be ignored
5184 var _ignore = [];
5185
5186 // type conversions
5187 var _conversions = [];
5188
5189 // This is a temporary object, will be replaced with a typed function at the end
5190 var typed = {
5191 types: _types,
5192 conversions: _conversions,
5193 ignore: _ignore
5194 };
5195
5196 /**
5197 * Find the test function for a type
5198 * @param {String} typeName
5199 * @return {TypeDef} Returns the type definition when found,
5200 * Throws a TypeError otherwise
5201 */
5202 function findTypeByName (typeName) {
5203 var entry = findInArray(typed.types, function (entry) {
5204 return entry.name === typeName;
5205 });
5206
5207 if (entry) {
5208 return entry;
5209 }
5210
5211 if (typeName === 'any') { // special baked-in case 'any'
5212 return anyType;
5213 }
5214
5215 var hint = findInArray(typed.types, function (entry) {
5216 return entry.name.toLowerCase() === typeName.toLowerCase();
5217 });
5218
5219 throw new TypeError('Unknown type "' + typeName + '"' +
5220 (hint ? ('. Did you mean "' + hint.name + '"?') : ''));
5221 }
5222
5223 /**
5224 * Find the index of a type definition. Handles special case 'any'
5225 * @param {TypeDef} type
5226 * @return {number}
5227 */
5228 function findTypeIndex(type) {
5229 if (type === anyType) {
5230 return 999;
5231 }
5232
5233 return typed.types.indexOf(type);
5234 }
5235
5236 /**
5237 * Find a type that matches a value.
5238 * @param {*} value
5239 * @return {string} Returns the name of the first type for which
5240 * the type test matches the value.
5241 */
5242 function findTypeName(value) {
5243 var entry = findInArray(typed.types, function (entry) {
5244 return entry.test(value);
5245 });
5246
5247 if (entry) {
5248 return entry.name;
5249 }
5250
5251 throw new TypeError('Value has unknown type. Value: ' + value);
5252 }
5253
5254 /**
5255 * Find a specific signature from a (composed) typed function, for example:
5256 *
5257 * typed.find(fn, ['number', 'string'])
5258 * typed.find(fn, 'number, string')
5259 *
5260 * Function find only only works for exact matches.
5261 *
5262 * @param {Function} fn A typed-function
5263 * @param {string | string[]} signature Signature to be found, can be
5264 * an array or a comma separated string.
5265 * @return {Function} Returns the matching signature, or
5266 * throws an error when no signature
5267 * is found.
5268 */
5269 function find (fn, signature) {
5270 if (!fn.signatures) {
5271 throw new TypeError('Function is no typed-function');
5272 }
5273
5274 // normalize input
5275 var arr;
5276 if (typeof signature === 'string') {
5277 arr = signature.split(',');
5278 for (var i = 0; i < arr.length; i++) {
5279 arr[i] = arr[i].trim();
5280 }
5281 }
5282 else if (Array.isArray(signature)) {
5283 arr = signature;
5284 }
5285 else {
5286 throw new TypeError('String array or a comma separated string expected');
5287 }
5288
5289 var str = arr.join(',');
5290
5291 // find an exact match
5292 var match = fn.signatures[str];
5293 if (match) {
5294 return match;
5295 }
5296
5297 // TODO: extend find to match non-exact signatures
5298
5299 throw new TypeError('Signature not found (signature: ' + (fn.name || 'unnamed') + '(' + arr.join(', ') + '))');
5300 }
5301
5302 /**
5303 * Convert a given value to another data type.
5304 * @param {*} value
5305 * @param {string} type
5306 */
5307 function convert (value, type) {
5308 var from = findTypeName(value);
5309
5310 // check conversion is needed
5311 if (type === from) {
5312 return value;
5313 }
5314
5315 for (var i = 0; i < typed.conversions.length; i++) {
5316 var conversion = typed.conversions[i];
5317 if (conversion.from === from && conversion.to === type) {
5318 return conversion.convert(value);
5319 }
5320 }
5321
5322 throw new Error('Cannot convert from ' + from + ' to ' + type);
5323 }
5324
5325 /**
5326 * Stringify parameters in a normalized way
5327 * @param {Param[]} params
5328 * @return {string}
5329 */
5330 function stringifyParams (params) {
5331 return params
5332 .map(function (param) {
5333 var typeNames = param.types.map(getTypeName);
5334
5335 return (param.restParam ? '...' : '') + typeNames.join('|');
5336 })
5337 .join(',');
5338 }
5339
5340 /**
5341 * Parse a parameter, like "...number | boolean"
5342 * @param {string} param
5343 * @param {ConversionDef[]} conversions
5344 * @return {Param} param
5345 */
5346 function parseParam (param, conversions) {
5347 var restParam = param.indexOf('...') === 0;
5348 var types = (!restParam)
5349 ? param
5350 : (param.length > 3)
5351 ? param.slice(3)
5352 : 'any';
5353
5354 var typeNames = types.split('|').map(trim)
5355 .filter(notEmpty)
5356 .filter(notIgnore);
5357
5358 var matchingConversions = filterConversions(conversions, typeNames);
5359
5360 var exactTypes = typeNames.map(function (typeName) {
5361 var type = findTypeByName(typeName);
5362
5363 return {
5364 name: typeName,
5365 typeIndex: findTypeIndex(type),
5366 test: type.test,
5367 conversion: null,
5368 conversionIndex: -1
5369 };
5370 });
5371
5372 var convertibleTypes = matchingConversions.map(function (conversion) {
5373 var type = findTypeByName(conversion.from);
5374
5375 return {
5376 name: conversion.from,
5377 typeIndex: findTypeIndex(type),
5378 test: type.test,
5379 conversion: conversion,
5380 conversionIndex: conversions.indexOf(conversion)
5381 };
5382 });
5383
5384 return {
5385 types: exactTypes.concat(convertibleTypes),
5386 restParam: restParam
5387 };
5388 }
5389
5390 /**
5391 * Parse a signature with comma separated parameters,
5392 * like "number | boolean, ...string"
5393 * @param {string} signature
5394 * @param {function} fn
5395 * @param {ConversionDef[]} conversions
5396 * @return {Signature | null} signature
5397 */
5398 function parseSignature (signature, fn, conversions) {
5399 var params = [];
5400
5401 if (signature.trim() !== '') {
5402 params = signature
5403 .split(',')
5404 .map(trim)
5405 .map(function (param, index, array) {
5406 var parsedParam = parseParam(param, conversions);
5407
5408 if (parsedParam.restParam && (index !== array.length - 1)) {
5409 throw new SyntaxError('Unexpected rest parameter "' + param + '": ' +
5410 'only allowed for the last parameter');
5411 }
5412
5413 return parsedParam;
5414 });
5415 }
5416
5417 if (params.some(isInvalidParam)) {
5418 // invalid signature: at least one parameter has no types
5419 // (they may have been filtered)
5420 return null;
5421 }
5422
5423 return {
5424 params: params,
5425 fn: fn
5426 };
5427 }
5428
5429 /**
5430 * Test whether a set of params contains a restParam
5431 * @param {Param[]} params
5432 * @return {boolean} Returns true when the last parameter is a restParam
5433 */
5434 function hasRestParam(params) {
5435 var param = last(params)
5436 return param ? param.restParam : false;
5437 }
5438
5439 /**
5440 * Test whether a parameter contains conversions
5441 * @param {Param} param
5442 * @return {boolean} Returns true when at least one of the parameters
5443 * contains a conversion.
5444 */
5445 function hasConversions(param) {
5446 return param.types.some(function (type) {
5447 return type.conversion != null;
5448 });
5449 }
5450
5451 /**
5452 * Create a type test for a single parameter, which can have one or multiple
5453 * types.
5454 * @param {Param} param
5455 * @return {function(x: *) : boolean} Returns a test function
5456 */
5457 function compileTest(param) {
5458 if (!param || param.types.length === 0) {
5459 // nothing to do
5460 return ok;
5461 }
5462 else if (param.types.length === 1) {
5463 return findTypeByName(param.types[0].name).test;
5464 }
5465 else if (param.types.length === 2) {
5466 var test0 = findTypeByName(param.types[0].name).test;
5467 var test1 = findTypeByName(param.types[1].name).test;
5468 return function or(x) {
5469 return test0(x) || test1(x);
5470 }
5471 }
5472 else { // param.types.length > 2
5473 var tests = param.types.map(function (type) {
5474 return findTypeByName(type.name).test;
5475 })
5476 return function or(x) {
5477 for (var i = 0; i < tests.length; i++) {
5478 if (tests[i](x)) {
5479 return true;
5480 }
5481 }
5482 return false;
5483 }
5484 }
5485 }
5486
5487 /**
5488 * Create a test for all parameters of a signature
5489 * @param {Param[]} params
5490 * @return {function(args: Array<*>) : boolean}
5491 */
5492 function compileTests(params) {
5493 var tests, test0, test1;
5494
5495 if (hasRestParam(params)) {
5496 // variable arguments like '...number'
5497 tests = initial(params).map(compileTest);
5498 var varIndex = tests.length;
5499 var lastTest = compileTest(last(params));
5500 var testRestParam = function (args) {
5501 for (var i = varIndex; i < args.length; i++) {
5502 if (!lastTest(args[i])) {
5503 return false;
5504 }
5505 }
5506 return true;
5507 }
5508
5509 return function testArgs(args) {
5510 for (var i = 0; i < tests.length; i++) {
5511 if (!tests[i](args[i])) {
5512 return false;
5513 }
5514 }
5515 return testRestParam(args) && (args.length >= varIndex + 1);
5516 };
5517 }
5518 else {
5519 // no variable arguments
5520 if (params.length === 0) {
5521 return function testArgs(args) {
5522 return args.length === 0;
5523 };
5524 }
5525 else if (params.length === 1) {
5526 test0 = compileTest(params[0]);
5527 return function testArgs(args) {
5528 return test0(args[0]) && args.length === 1;
5529 };
5530 }
5531 else if (params.length === 2) {
5532 test0 = compileTest(params[0]);
5533 test1 = compileTest(params[1]);
5534 return function testArgs(args) {
5535 return test0(args[0]) && test1(args[1]) && args.length === 2;
5536 };
5537 }
5538 else { // arguments.length > 2
5539 tests = params.map(compileTest);
5540 return function testArgs(args) {
5541 for (var i = 0; i < tests.length; i++) {
5542 if (!tests[i](args[i])) {
5543 return false;
5544 }
5545 }
5546 return args.length === tests.length;
5547 };
5548 }
5549 }
5550 }
5551
5552 /**
5553 * Find the parameter at a specific index of a signature.
5554 * Handles rest parameters.
5555 * @param {Signature} signature
5556 * @param {number} index
5557 * @return {Param | null} Returns the matching parameter when found,
5558 * null otherwise.
5559 */
5560 function getParamAtIndex(signature, index) {
5561 return index < signature.params.length
5562 ? signature.params[index]
5563 : hasRestParam(signature.params)
5564 ? last(signature.params)
5565 : null
5566 }
5567
5568 /**
5569 * Get all type names of a parameter
5570 * @param {Signature} signature
5571 * @param {number} index
5572 * @param {boolean} excludeConversions
5573 * @return {string[]} Returns an array with type names
5574 */
5575 function getExpectedTypeNames (signature, index, excludeConversions) {
5576 var param = getParamAtIndex(signature, index);
5577 var types = param
5578 ? excludeConversions
5579 ? param.types.filter(isExactType)
5580 : param.types
5581 : [];
5582
5583 return types.map(getTypeName);
5584 }
5585
5586 /**
5587 * Returns the name of a type
5588 * @param {Type} type
5589 * @return {string} Returns the type name
5590 */
5591 function getTypeName(type) {
5592 return type.name;
5593 }
5594
5595 /**
5596 * Test whether a type is an exact type or conversion
5597 * @param {Type} type
5598 * @return {boolean} Returns true when
5599 */
5600 function isExactType(type) {
5601 return type.conversion === null || type.conversion === undefined;
5602 }
5603
5604 /**
5605 * Helper function for creating error messages: create an array with
5606 * all available types on a specific argument index.
5607 * @param {Signature[]} signatures
5608 * @param {number} index
5609 * @return {string[]} Returns an array with available types
5610 */
5611 function mergeExpectedParams(signatures, index) {
5612 var typeNames = uniq(flatMap(signatures, function (signature) {
5613 return getExpectedTypeNames(signature, index, false);
5614 }));
5615
5616 return (typeNames.indexOf('any') !== -1) ? ['any'] : typeNames;
5617 }
5618
5619 /**
5620 * Create
5621 * @param {string} name The name of the function
5622 * @param {array.<*>} args The actual arguments passed to the function
5623 * @param {Signature[]} signatures A list with available signatures
5624 * @return {TypeError} Returns a type error with additional data
5625 * attached to it in the property `data`
5626 */
5627 function createError(name, args, signatures) {
5628 var err, expected;
5629 var _name = name || 'unnamed';
5630
5631 // test for wrong type at some index
5632 var matchingSignatures = signatures;
5633 var index;
5634 for (index = 0; index < args.length; index++) {
5635 var nextMatchingDefs = matchingSignatures.filter(function (signature) {
5636 var test = compileTest(getParamAtIndex(signature, index));
5637 return (index < signature.params.length || hasRestParam(signature.params)) &&
5638 test(args[index]);
5639 });
5640
5641 if (nextMatchingDefs.length === 0) {
5642 // no matching signatures anymore, throw error "wrong type"
5643 expected = mergeExpectedParams(matchingSignatures, index);
5644 if (expected.length > 0) {
5645 var actualType = findTypeName(args[index]);
5646
5647 err = new TypeError('Unexpected type of argument in function ' + _name +
5648 ' (expected: ' + expected.join(' or ') +
5649 ', actual: ' + actualType + ', index: ' + index + ')');
5650 err.data = {
5651 category: 'wrongType',
5652 fn: _name,
5653 index: index,
5654 actual: actualType,
5655 expected: expected
5656 }
5657 return err;
5658 }
5659 }
5660 else {
5661 matchingSignatures = nextMatchingDefs;
5662 }
5663 }
5664
5665 // test for too few arguments
5666 var lengths = matchingSignatures.map(function (signature) {
5667 return hasRestParam(signature.params) ? Infinity : signature.params.length;
5668 });
5669 if (args.length < Math.min.apply(null, lengths)) {
5670 expected = mergeExpectedParams(matchingSignatures, index);
5671 err = new TypeError('Too few arguments in function ' + _name +
5672 ' (expected: ' + expected.join(' or ') +
5673 ', index: ' + args.length + ')');
5674 err.data = {
5675 category: 'tooFewArgs',
5676 fn: _name,
5677 index: args.length,
5678 expected: expected
5679 }
5680 return err;
5681 }
5682
5683 // test for too many arguments
5684 var maxLength = Math.max.apply(null, lengths);
5685 if (args.length > maxLength) {
5686 err = new TypeError('Too many arguments in function ' + _name +
5687 ' (expected: ' + maxLength + ', actual: ' + args.length + ')');
5688 err.data = {
5689 category: 'tooManyArgs',
5690 fn: _name,
5691 index: args.length,
5692 expectedLength: maxLength
5693 }
5694 return err;
5695 }
5696
5697 err = new TypeError('Arguments of type "' + args.join(', ') +
5698 '" do not match any of the defined signatures of function ' + _name + '.');
5699 err.data = {
5700 category: 'mismatch',
5701 actual: args.map(findTypeName)
5702 }
5703 return err;
5704 }
5705
5706 /**
5707 * Find the lowest index of all exact types of a parameter (no conversions)
5708 * @param {Param} param
5709 * @return {number} Returns the index of the lowest type in typed.types
5710 */
5711 function getLowestTypeIndex (param) {
5712 var min = 999;
5713
5714 for (var i = 0; i < param.types.length; i++) {
5715 if (isExactType(param.types[i])) {
5716 min = Math.min(min, param.types[i].typeIndex);
5717 }
5718 }
5719
5720 return min;
5721 }
5722
5723 /**
5724 * Find the lowest index of the conversion of all types of the parameter
5725 * having a conversion
5726 * @param {Param} param
5727 * @return {number} Returns the lowest index of the conversions of this type
5728 */
5729 function getLowestConversionIndex (param) {
5730 var min = 999;
5731
5732 for (var i = 0; i < param.types.length; i++) {
5733 if (!isExactType(param.types[i])) {
5734 min = Math.min(min, param.types[i].conversionIndex);
5735 }
5736 }
5737
5738 return min;
5739 }
5740
5741 /**
5742 * Compare two params
5743 * @param {Param} param1
5744 * @param {Param} param2
5745 * @return {number} returns a negative number when param1 must get a lower
5746 * index than param2, a positive number when the opposite,
5747 * or zero when both are equal
5748 */
5749 function compareParams (param1, param2) {
5750 var c;
5751
5752 // compare having a rest parameter or not
5753 c = param1.restParam - param2.restParam;
5754 if (c !== 0) {
5755 return c;
5756 }
5757
5758 // compare having conversions or not
5759 c = hasConversions(param1) - hasConversions(param2);
5760 if (c !== 0) {
5761 return c;
5762 }
5763
5764 // compare the index of the types
5765 c = getLowestTypeIndex(param1) - getLowestTypeIndex(param2);
5766 if (c !== 0) {
5767 return c;
5768 }
5769
5770 // compare the index of any conversion
5771 return getLowestConversionIndex(param1) - getLowestConversionIndex(param2);
5772 }
5773
5774 /**
5775 * Compare two signatures
5776 * @param {Signature} signature1
5777 * @param {Signature} signature2
5778 * @return {number} returns a negative number when param1 must get a lower
5779 * index than param2, a positive number when the opposite,
5780 * or zero when both are equal
5781 */
5782 function compareSignatures (signature1, signature2) {
5783 var len = Math.min(signature1.params.length, signature2.params.length);
5784 var i;
5785 var c;
5786
5787 // compare whether the params have conversions at all or not
5788 c = signature1.params.some(hasConversions) - signature2.params.some(hasConversions)
5789 if (c !== 0) {
5790 return c;
5791 }
5792
5793 // next compare whether the params have conversions one by one
5794 for (i = 0; i < len; i++) {
5795 c = hasConversions(signature1.params[i]) - hasConversions(signature2.params[i]);
5796 if (c !== 0) {
5797 return c;
5798 }
5799 }
5800
5801 // compare the types of the params one by one
5802 for (i = 0; i < len; i++) {
5803 c = compareParams(signature1.params[i], signature2.params[i]);
5804 if (c !== 0) {
5805 return c;
5806 }
5807 }
5808
5809 // compare the number of params
5810 return signature1.params.length - signature2.params.length;
5811 }
5812
5813 /**
5814 * Get params containing all types that can be converted to the defined types.
5815 *
5816 * @param {ConversionDef[]} conversions
5817 * @param {string[]} typeNames
5818 * @return {ConversionDef[]} Returns the conversions that are available
5819 * for every type (if any)
5820 */
5821 function filterConversions(conversions, typeNames) {
5822 var matches = {};
5823
5824 conversions.forEach(function (conversion) {
5825 if (typeNames.indexOf(conversion.from) === -1 &&
5826 typeNames.indexOf(conversion.to) !== -1 &&
5827 !matches[conversion.from]) {
5828 matches[conversion.from] = conversion;
5829 }
5830 });
5831
5832 return Object.keys(matches).map(function (from) {
5833 return matches[from];
5834 });
5835 }
5836
5837 /**
5838 * Preprocess arguments before calling the original function:
5839 * - if needed convert the parameters
5840 * - in case of rest parameters, move the rest parameters into an Array
5841 * @param {Param[]} params
5842 * @param {function} fn
5843 * @return {function} Returns a wrapped function
5844 */
5845 function compileArgsPreprocessing(params, fn) {
5846 var fnConvert = fn;
5847
5848 // TODO: can we make this wrapper function smarter/simpler?
5849
5850 if (params.some(hasConversions)) {
5851 var restParam = hasRestParam(params);
5852 var compiledConversions = params.map(compileArgConversion)
5853
5854 fnConvert = function convertArgs() {
5855 var args = [];
5856 var last = restParam ? arguments.length - 1 : arguments.length;
5857 for (var i = 0; i < last; i++) {
5858 args[i] = compiledConversions[i](arguments[i]);
5859 }
5860 if (restParam) {
5861 args[last] = arguments[last].map(compiledConversions[last]);
5862 }
5863
5864 return fn.apply(null, args);
5865 }
5866 }
5867
5868 var fnPreprocess = fnConvert;
5869 if (hasRestParam(params)) {
5870 var offset = params.length - 1;
5871
5872 fnPreprocess = function preprocessRestParams () {
5873 return fnConvert.apply(null,
5874 slice(arguments, 0, offset).concat([slice(arguments, offset)]));
5875 }
5876 }
5877
5878 return fnPreprocess;
5879 }
5880
5881 /**
5882 * Compile conversion for a parameter to the right type
5883 * @param {Param} param
5884 * @return {function} Returns the wrapped function that will convert arguments
5885 *
5886 */
5887 function compileArgConversion(param) {
5888 var test0, test1, conversion0, conversion1;
5889 var tests = [];
5890 var conversions = [];
5891
5892 param.types.forEach(function (type) {
5893 if (type.conversion) {
5894 tests.push(findTypeByName(type.conversion.from).test);
5895 conversions.push(type.conversion.convert);
5896 }
5897 });
5898
5899 // create optimized conversion functions depending on the number of conversions
5900 switch (conversions.length) {
5901 case 0:
5902 return function convertArg(arg) {
5903 return arg;
5904 }
5905
5906 case 1:
5907 test0 = tests[0]
5908 conversion0 = conversions[0];
5909 return function convertArg(arg) {
5910 if (test0(arg)) {
5911 return conversion0(arg)
5912 }
5913 return arg;
5914 }
5915
5916 case 2:
5917 test0 = tests[0]
5918 test1 = tests[1]
5919 conversion0 = conversions[0];
5920 conversion1 = conversions[1];
5921 return function convertArg(arg) {
5922 if (test0(arg)) {
5923 return conversion0(arg)
5924 }
5925 if (test1(arg)) {
5926 return conversion1(arg)
5927 }
5928 return arg;
5929 }
5930
5931 default:
5932 return function convertArg(arg) {
5933 for (var i = 0; i < conversions.length; i++) {
5934 if (tests[i](arg)) {
5935 return conversions[i](arg);
5936 }
5937 }
5938 return arg;
5939 }
5940 }
5941 }
5942
5943 /**
5944 * Convert an array with signatures into a map with signatures,
5945 * where signatures with union types are split into separate signatures
5946 *
5947 * Throws an error when there are conflicting types
5948 *
5949 * @param {Signature[]} signatures
5950 * @return {Object.<string, function>} Returns a map with signatures
5951 * as key and the original function
5952 * of this signature as value.
5953 */
5954 function createSignaturesMap(signatures) {
5955 var signaturesMap = {};
5956 signatures.forEach(function (signature) {
5957 if (!signature.params.some(hasConversions)) {
5958 splitParams(signature.params, true).forEach(function (params) {
5959 signaturesMap[stringifyParams(params)] = signature.fn;
5960 });
5961 }
5962 });
5963
5964 return signaturesMap;
5965 }
5966
5967 /**
5968 * Split params with union types in to separate params.
5969 *
5970 * For example:
5971 *
5972 * splitParams([['Array', 'Object'], ['string', 'RegExp'])
5973 * // returns:
5974 * // [
5975 * // ['Array', 'string'],
5976 * // ['Array', 'RegExp'],
5977 * // ['Object', 'string'],
5978 * // ['Object', 'RegExp']
5979 * // ]
5980 *
5981 * @param {Param[]} params
5982 * @param {boolean} ignoreConversionTypes
5983 * @return {Param[]}
5984 */
5985 function splitParams(params, ignoreConversionTypes) {
5986 function _splitParams(params, index, types) {
5987 if (index < params.length) {
5988 var param = params[index]
5989 var filteredTypes = ignoreConversionTypes
5990 ? param.types.filter(isExactType)
5991 : param.types;
5992 var typeGroups
5993
5994 if (param.restParam) {
5995 // split the types of a rest parameter in two:
5996 // one with only exact types, and one with exact types and conversions
5997 var exactTypes = filteredTypes.filter(isExactType)
5998 typeGroups = exactTypes.length < filteredTypes.length
5999 ? [exactTypes, filteredTypes]
6000 : [filteredTypes]
6001
6002 }
6003 else {
6004 // split all the types of a regular parameter into one type per group
6005 typeGroups = filteredTypes.map(function (type) {
6006 return [type]
6007 })
6008 }
6009
6010 // recurse over the groups with types
6011 return flatMap(typeGroups, function (typeGroup) {
6012 return _splitParams(params, index + 1, types.concat([typeGroup]));
6013 });
6014
6015 }
6016 else {
6017 // we've reached the end of the parameters. Now build a new Param
6018 var splittedParams = types.map(function (type, typeIndex) {
6019 return {
6020 types: type,
6021 restParam: (typeIndex === params.length - 1) && hasRestParam(params)
6022 }
6023 });
6024
6025 return [splittedParams];
6026 }
6027 }
6028
6029 return _splitParams(params, 0, []);
6030 }
6031
6032 /**
6033 * Test whether two signatures have a conflicting signature
6034 * @param {Signature} signature1
6035 * @param {Signature} signature2
6036 * @return {boolean} Returns true when the signatures conflict, false otherwise.
6037 */
6038 function hasConflictingParams(signature1, signature2) {
6039 var ii = Math.max(signature1.params.length, signature2.params.length);
6040
6041 for (var i = 0; i < ii; i++) {
6042 var typesNames1 = getExpectedTypeNames(signature1, i, true);
6043 var typesNames2 = getExpectedTypeNames(signature2, i, true);
6044
6045 if (!hasOverlap(typesNames1, typesNames2)) {
6046 return false;
6047 }
6048 }
6049
6050 var len1 = signature1.params.length;
6051 var len2 = signature2.params.length;
6052 var restParam1 = hasRestParam(signature1.params);
6053 var restParam2 = hasRestParam(signature2.params);
6054
6055 return restParam1
6056 ? restParam2 ? (len1 === len2) : (len2 >= len1)
6057 : restParam2 ? (len1 >= len2) : (len1 === len2)
6058 }
6059
6060 /**
6061 * Create a typed function
6062 * @param {String} name The name for the typed function
6063 * @param {Object.<string, function>} signaturesMap
6064 * An object with one or
6065 * multiple signatures as key, and the
6066 * function corresponding to the
6067 * signature as value.
6068 * @return {function} Returns the created typed function.
6069 */
6070 function createTypedFunction(name, signaturesMap) {
6071 if (Object.keys(signaturesMap).length === 0) {
6072 throw new SyntaxError('No signatures provided');
6073 }
6074
6075 // parse the signatures, and check for conflicts
6076 var parsedSignatures = [];
6077 Object.keys(signaturesMap)
6078 .map(function (signature) {
6079 return parseSignature(signature, signaturesMap[signature], typed.conversions);
6080 })
6081 .filter(notNull)
6082 .forEach(function (parsedSignature) {
6083 // check whether this parameter conflicts with already parsed signatures
6084 var conflictingSignature = findInArray(parsedSignatures, function (s) {
6085 return hasConflictingParams(s, parsedSignature)
6086 });
6087 if (conflictingSignature) {
6088 throw new TypeError('Conflicting signatures "' +
6089 stringifyParams(conflictingSignature.params) + '" and "' +
6090 stringifyParams(parsedSignature.params) + '".');
6091 }
6092
6093 parsedSignatures.push(parsedSignature);
6094 });
6095
6096 // split and filter the types of the signatures, and then order them
6097 var signatures = flatMap(parsedSignatures, function (parsedSignature) {
6098 var params = parsedSignature ? splitParams(parsedSignature.params, false) : []
6099
6100 return params.map(function (params) {
6101 return {
6102 params: params,
6103 fn: parsedSignature.fn
6104 };
6105 });
6106 }).filter(notNull);
6107
6108 signatures.sort(compareSignatures);
6109
6110 // we create a highly optimized checks for the first couple of signatures with max 2 arguments
6111 var ok0 = signatures[0] && signatures[0].params.length <= 2 && !hasRestParam(signatures[0].params);
6112 var ok1 = signatures[1] && signatures[1].params.length <= 2 && !hasRestParam(signatures[1].params);
6113 var ok2 = signatures[2] && signatures[2].params.length <= 2 && !hasRestParam(signatures[2].params);
6114 var ok3 = signatures[3] && signatures[3].params.length <= 2 && !hasRestParam(signatures[3].params);
6115 var ok4 = signatures[4] && signatures[4].params.length <= 2 && !hasRestParam(signatures[4].params);
6116 var ok5 = signatures[5] && signatures[5].params.length <= 2 && !hasRestParam(signatures[5].params);
6117 var allOk = ok0 && ok1 && ok2 && ok3 && ok4 && ok5;
6118
6119 // compile the tests
6120 var tests = signatures.map(function (signature) {
6121 return compileTests(signature.params);
6122 });
6123
6124 var test00 = ok0 ? compileTest(signatures[0].params[0]) : notOk;
6125 var test10 = ok1 ? compileTest(signatures[1].params[0]) : notOk;
6126 var test20 = ok2 ? compileTest(signatures[2].params[0]) : notOk;
6127 var test30 = ok3 ? compileTest(signatures[3].params[0]) : notOk;
6128 var test40 = ok4 ? compileTest(signatures[4].params[0]) : notOk;
6129 var test50 = ok5 ? compileTest(signatures[5].params[0]) : notOk;
6130
6131 var test01 = ok0 ? compileTest(signatures[0].params[1]) : notOk;
6132 var test11 = ok1 ? compileTest(signatures[1].params[1]) : notOk;
6133 var test21 = ok2 ? compileTest(signatures[2].params[1]) : notOk;
6134 var test31 = ok3 ? compileTest(signatures[3].params[1]) : notOk;
6135 var test41 = ok4 ? compileTest(signatures[4].params[1]) : notOk;
6136 var test51 = ok5 ? compileTest(signatures[5].params[1]) : notOk;
6137
6138 // compile the functions
6139 var fns = signatures.map(function(signature) {
6140 return compileArgsPreprocessing(signature.params, signature.fn)
6141 });
6142
6143 var fn0 = ok0 ? fns[0] : undef;
6144 var fn1 = ok1 ? fns[1] : undef;
6145 var fn2 = ok2 ? fns[2] : undef;
6146 var fn3 = ok3 ? fns[3] : undef;
6147 var fn4 = ok4 ? fns[4] : undef;
6148 var fn5 = ok5 ? fns[5] : undef;
6149
6150 var len0 = ok0 ? signatures[0].params.length : -1;
6151 var len1 = ok1 ? signatures[1].params.length : -1;
6152 var len2 = ok2 ? signatures[2].params.length : -1;
6153 var len3 = ok3 ? signatures[3].params.length : -1;
6154 var len4 = ok4 ? signatures[4].params.length : -1;
6155 var len5 = ok5 ? signatures[5].params.length : -1;
6156
6157 // simple and generic, but also slow
6158 var iStart = allOk ? 6 : 0;
6159 var iEnd = signatures.length;
6160 var generic = function generic() {
6161 'use strict';
6162
6163 for (var i = iStart; i < iEnd; i++) {
6164 if (tests[i](arguments)) {
6165 return fns[i].apply(null, arguments);
6166 }
6167 }
6168
6169 throw createError(name, arguments, signatures);
6170 }
6171
6172 // create the typed function
6173 // fast, specialized version. Falls back to the slower, generic one if needed
6174 var fn = function fn(arg0, arg1) {
6175 'use strict';
6176
6177 if (arguments.length === len0 && test00(arg0) && test01(arg1)) { return fn0.apply(null, arguments); }
6178 if (arguments.length === len1 && test10(arg0) && test11(arg1)) { return fn1.apply(null, arguments); }
6179 if (arguments.length === len2 && test20(arg0) && test21(arg1)) { return fn2.apply(null, arguments); }
6180 if (arguments.length === len3 && test30(arg0) && test31(arg1)) { return fn3.apply(null, arguments); }
6181 if (arguments.length === len4 && test40(arg0) && test41(arg1)) { return fn4.apply(null, arguments); }
6182 if (arguments.length === len5 && test50(arg0) && test51(arg1)) { return fn5.apply(null, arguments); }
6183
6184 return generic.apply(null, arguments);
6185 }
6186
6187 // attach name the typed function
6188 try {
6189 Object.defineProperty(fn, 'name', {value: name});
6190 }
6191 catch (err) {
6192 // old browsers do not support Object.defineProperty and some don't support setting the name property
6193 // the function name is not essential for the functioning, it's mostly useful for debugging,
6194 // so it's fine to have unnamed functions.
6195 }
6196
6197 // attach signatures to the function
6198 fn.signatures = createSignaturesMap(signatures);
6199
6200 return fn;
6201 }
6202
6203 /**
6204 * Test whether a type should be NOT be ignored
6205 * @param {string} typeName
6206 * @return {boolean}
6207 */
6208 function notIgnore(typeName) {
6209 return typed.ignore.indexOf(typeName) === -1;
6210 }
6211
6212 /**
6213 * trim a string
6214 * @param {string} str
6215 * @return {string}
6216 */
6217 function trim(str) {
6218 return str.trim();
6219 }
6220
6221 /**
6222 * Test whether a string is not empty
6223 * @param {string} str
6224 * @return {boolean}
6225 */
6226 function notEmpty(str) {
6227 return !!str;
6228 }
6229
6230 /**
6231 * test whether a value is not strict equal to null
6232 * @param {*} value
6233 * @return {boolean}
6234 */
6235 function notNull(value) {
6236 return value !== null;
6237 }
6238
6239 /**
6240 * Test whether a parameter has no types defined
6241 * @param {Param} param
6242 * @return {boolean}
6243 */
6244 function isInvalidParam (param) {
6245 return param.types.length === 0;
6246 }
6247
6248 /**
6249 * Return all but the last items of an array
6250 * @param {Array} arr
6251 * @return {Array}
6252 */
6253 function initial(arr) {
6254 return arr.slice(0, arr.length - 1);
6255 }
6256
6257 /**
6258 * return the last item of an array
6259 * @param {Array} arr
6260 * @return {*}
6261 */
6262 function last(arr) {
6263 return arr[arr.length - 1];
6264 }
6265
6266 /**
6267 * Slice an array or function Arguments
6268 * @param {Array | Arguments | IArguments} arr
6269 * @param {number} start
6270 * @param {number} [end]
6271 * @return {Array}
6272 */
6273 function slice(arr, start, end) {
6274 return Array.prototype.slice.call(arr, start, end);
6275 }
6276
6277 /**
6278 * Test whether an array contains some item
6279 * @param {Array} array
6280 * @param {*} item
6281 * @return {boolean} Returns true if array contains item, false if not.
6282 */
6283 function contains(array, item) {
6284 return array.indexOf(item) !== -1;
6285 }
6286
6287 /**
6288 * Test whether two arrays have overlapping items
6289 * @param {Array} array1
6290 * @param {Array} array2
6291 * @return {boolean} Returns true when at least one item exists in both arrays
6292 */
6293 function hasOverlap(array1, array2) {
6294 for (var i = 0; i < array1.length; i++) {
6295 if (contains(array2, array1[i])) {
6296 return true;
6297 }
6298 }
6299
6300 return false;
6301 }
6302
6303 /**
6304 * Return the first item from an array for which test(arr[i]) returns true
6305 * @param {Array} arr
6306 * @param {function} test
6307 * @return {* | undefined} Returns the first matching item
6308 * or undefined when there is no match
6309 */
6310 function findInArray(arr, test) {
6311 for (var i = 0; i < arr.length; i++) {
6312 if (test(arr[i])) {
6313 return arr[i];
6314 }
6315 }
6316 return undefined;
6317 }
6318
6319 /**
6320 * Filter unique items of an array with strings
6321 * @param {string[]} arr
6322 * @return {string[]}
6323 */
6324 function uniq(arr) {
6325 var entries = {}
6326 for (var i = 0; i < arr.length; i++) {
6327 entries[arr[i]] = true;
6328 }
6329 return Object.keys(entries);
6330 }
6331
6332 /**
6333 * Flat map the result invoking a callback for every item in an array.
6334 * https://gist.github.com/samgiles/762ee337dff48623e729
6335 * @param {Array} arr
6336 * @param {function} callback
6337 * @return {Array}
6338 */
6339 function flatMap(arr, callback) {
6340 return Array.prototype.concat.apply([], arr.map(callback));
6341 }
6342
6343 /**
6344 * Retrieve the function name from a set of typed functions,
6345 * and check whether the name of all functions match (if given)
6346 * @param {function[]} fns
6347 */
6348 function getName (fns) {
6349 var name = '';
6350
6351 for (var i = 0; i < fns.length; i++) {
6352 var fn = fns[i];
6353
6354 // check whether the names are the same when defined
6355 if ((typeof fn.signatures === 'object' || typeof fn.signature === 'string') && fn.name !== '') {
6356 if (name === '') {
6357 name = fn.name;
6358 }
6359 else if (name !== fn.name) {
6360 var err = new Error('Function names do not match (expected: ' + name + ', actual: ' + fn.name + ')');
6361 err.data = {
6362 actual: fn.name,
6363 expected: name
6364 };
6365 throw err;
6366 }
6367 }
6368 }
6369
6370 return name;
6371 }
6372
6373 // extract and merge all signatures of a list with typed functions
6374 function extractSignatures(fns) {
6375 var err;
6376 var signaturesMap = {};
6377
6378 function validateUnique(_signature, _fn) {
6379 if (signaturesMap.hasOwnProperty(_signature) && _fn !== signaturesMap[_signature]) {
6380 err = new Error('Signature "' + _signature + '" is defined twice');
6381 err.data = {signature: _signature};
6382 throw err;
6383 // else: both signatures point to the same function, that's fine
6384 }
6385 }
6386
6387 for (var i = 0; i < fns.length; i++) {
6388 var fn = fns[i];
6389
6390 // test whether this is a typed-function
6391 if (typeof fn.signatures === 'object') {
6392 // merge the signatures
6393 for (var signature in fn.signatures) {
6394 if (fn.signatures.hasOwnProperty(signature)) {
6395 validateUnique(signature, fn.signatures[signature]);
6396 signaturesMap[signature] = fn.signatures[signature];
6397 }
6398 }
6399 }
6400 else if (typeof fn.signature === 'string') {
6401 validateUnique(fn.signature, fn);
6402 signaturesMap[fn.signature] = fn;
6403 }
6404 else {
6405 err = new TypeError('Function is no typed-function (index: ' + i + ')');
6406 err.data = {index: i};
6407 throw err;
6408 }
6409 }
6410
6411 return signaturesMap;
6412 }
6413
6414 typed = createTypedFunction('typed', {
6415 'string, Object': createTypedFunction,
6416 'Object': function (signaturesMap) {
6417 // find existing name
6418 var fns = [];
6419 for (var signature in signaturesMap) {
6420 if (signaturesMap.hasOwnProperty(signature)) {
6421 fns.push(signaturesMap[signature]);
6422 }
6423 }
6424 var name = getName(fns);
6425 return createTypedFunction(name, signaturesMap);
6426 },
6427 '...Function': function (fns) {
6428 return createTypedFunction(getName(fns), extractSignatures(fns));
6429 },
6430 'string, ...Function': function (name, fns) {
6431 return createTypedFunction(name, extractSignatures(fns));
6432 }
6433 });
6434
6435 typed.create = create;
6436 typed.types = _types;
6437 typed.conversions = _conversions;
6438 typed.ignore = _ignore;
6439 typed.convert = convert;
6440 typed.find = find;
6441
6442 /**
6443 * add a type
6444 * @param {{name: string, test: function}} type
6445 * @param {boolean} [beforeObjectTest=true]
6446 * If true, the new test will be inserted before
6447 * the test with name 'Object' (if any), since
6448 * tests for Object match Array and classes too.
6449 */
6450 typed.addType = function (type, beforeObjectTest) {
6451 if (!type || typeof type.name !== 'string' || typeof type.test !== 'function') {
6452 throw new TypeError('Object with properties {name: string, test: function} expected');
6453 }
6454
6455 if (beforeObjectTest !== false) {
6456 for (var i = 0; i < typed.types.length; i++) {
6457 if (typed.types[i].name === 'Object') {
6458 typed.types.splice(i, 0, type);
6459 return
6460 }
6461 }
6462 }
6463
6464 typed.types.push(type);
6465 };
6466
6467 // add a conversion
6468 typed.addConversion = function (conversion) {
6469 if (!conversion
6470 || typeof conversion.from !== 'string'
6471 || typeof conversion.to !== 'string'
6472 || typeof conversion.convert !== 'function') {
6473 throw new TypeError('Object with properties {from: string, to: string, convert: function} expected');
6474 }
6475
6476 typed.conversions.push(conversion);
6477 };
6478
6479 return typed;
6480 }
6481
6482 return create();
6483}));
6484
6485/***/ }),
6486/* 15 */
6487/***/ (function(module, exports, __webpack_require__) {
6488
6489"use strict";
6490/* WEBPACK VAR INJECTION */(function(global) {
6491
6492var width = 256;// each RC4 output is 0 <= x < 256
6493var chunks = 6;// at least six RC4 outputs for each double
6494var digits = 52;// there are 52 significant digits in a double
6495var pool = [];// pool: entropy pool starts empty
6496var GLOBAL = typeof global === 'undefined' ? window : global;
6497
6498//
6499// The following constants are related to IEEE 754 limits.
6500//
6501var startdenom = Math.pow(width, chunks),
6502 significance = Math.pow(2, digits),
6503 overflow = significance * 2,
6504 mask = width - 1;
6505
6506
6507var oldRandom = Math.random;
6508
6509//
6510// seedrandom()
6511// This is the seedrandom function described above.
6512//
6513module.exports = function(seed, options) {
6514 if (options && options.global === true) {
6515 options.global = false;
6516 Math.random = module.exports(seed, options);
6517 options.global = true;
6518 return Math.random;
6519 }
6520 var use_entropy = (options && options.entropy) || false;
6521 var key = [];
6522
6523 // Flatten the seed string or build one from local entropy if needed.
6524 var shortseed = mixkey(flatten(
6525 use_entropy ? [seed, tostring(pool)] :
6526 0 in arguments ? seed : autoseed(), 3), key);
6527
6528 // Use the seed to initialize an ARC4 generator.
6529 var arc4 = new ARC4(key);
6530
6531 // Mix the randomness into accumulated entropy.
6532 mixkey(tostring(arc4.S), pool);
6533
6534 // Override Math.random
6535
6536 // This function returns a random double in [0, 1) that contains
6537 // randomness in every bit of the mantissa of the IEEE 754 value.
6538
6539 return function() { // Closure to return a random double:
6540 var n = arc4.g(chunks), // Start with a numerator n < 2 ^ 48
6541 d = startdenom, // and denominator d = 2 ^ 48.
6542 x = 0; // and no 'extra last byte'.
6543 while (n < significance) { // Fill up all significant digits by
6544 n = (n + x) * width; // shifting numerator and
6545 d *= width; // denominator and generating a
6546 x = arc4.g(1); // new least-significant-byte.
6547 }
6548 while (n >= overflow) { // To avoid rounding up, before adding
6549 n /= 2; // last byte, shift everything
6550 d /= 2; // right using integer Math until
6551 x >>>= 1; // we have exactly the desired bits.
6552 }
6553 return (n + x) / d; // Form the number within [0, 1).
6554 };
6555};
6556
6557module.exports.resetGlobal = function () {
6558 Math.random = oldRandom;
6559};
6560
6561//
6562// ARC4
6563//
6564// An ARC4 implementation. The constructor takes a key in the form of
6565// an array of at most (width) integers that should be 0 <= x < (width).
6566//
6567// The g(count) method returns a pseudorandom integer that concatenates
6568// the next (count) outputs from ARC4. Its return value is a number x
6569// that is in the range 0 <= x < (width ^ count).
6570//
6571/** @constructor */
6572function ARC4(key) {
6573 var t, keylen = key.length,
6574 me = this, i = 0, j = me.i = me.j = 0, s = me.S = [];
6575
6576 // The empty key [] is treated as [0].
6577 if (!keylen) { key = [keylen++]; }
6578
6579 // Set up S using the standard key scheduling algorithm.
6580 while (i < width) {
6581 s[i] = i++;
6582 }
6583 for (i = 0; i < width; i++) {
6584 s[i] = s[j = mask & (j + key[i % keylen] + (t = s[i]))];
6585 s[j] = t;
6586 }
6587
6588 // The "g" method returns the next (count) outputs as one number.
6589 (me.g = function(count) {
6590 // Using instance members instead of closure state nearly doubles speed.
6591 var t, r = 0,
6592 i = me.i, j = me.j, s = me.S;
6593 while (count--) {
6594 t = s[i = mask & (i + 1)];
6595 r = r * width + s[mask & ((s[i] = s[j = mask & (j + t)]) + (s[j] = t))];
6596 }
6597 me.i = i; me.j = j;
6598 return r;
6599 // For robust unpredictability discard an initial batch of values.
6600 // See http://www.rsa.com/rsalabs/node.asp?id=2009
6601 })(width);
6602}
6603
6604//
6605// flatten()
6606// Converts an object tree to nested arrays of strings.
6607//
6608function flatten(obj, depth) {
6609 var result = [], typ = (typeof obj)[0], prop;
6610 if (depth && typ == 'o') {
6611 for (prop in obj) {
6612 try { result.push(flatten(obj[prop], depth - 1)); } catch (e) {}
6613 }
6614 }
6615 return (result.length ? result : typ == 's' ? obj : obj + '\0');
6616}
6617
6618//
6619// mixkey()
6620// Mixes a string seed into a key that is an array of integers, and
6621// returns a shortened string seed that is equivalent to the result key.
6622//
6623function mixkey(seed, key) {
6624 var stringseed = seed + '', smear, j = 0;
6625 while (j < stringseed.length) {
6626 key[mask & j] =
6627 mask & ((smear ^= key[mask & j] * 19) + stringseed.charCodeAt(j++));
6628 }
6629 return tostring(key);
6630}
6631
6632//
6633// autoseed()
6634// Returns an object for autoseeding, using window.crypto if available.
6635//
6636/** @param {Uint8Array=} seed */
6637function autoseed(seed) {
6638 try {
6639 GLOBAL.crypto.getRandomValues(seed = new Uint8Array(width));
6640 return tostring(seed);
6641 } catch (e) {
6642 return [+new Date, GLOBAL, GLOBAL.navigator && GLOBAL.navigator.plugins,
6643 GLOBAL.screen, tostring(pool)];
6644 }
6645}
6646
6647//
6648// tostring()
6649// Converts an array of charcodes to a string
6650//
6651function tostring(a) {
6652 return String.fromCharCode.apply(0, a);
6653}
6654
6655//
6656// When seedrandom.js is loaded, we immediately mix a few bits
6657// from the built-in RNG into the entropy pool. Because we do
6658// not want to intefere with determinstic PRNG state later,
6659// seedrandom will not call Math.random on its own again after
6660// initialization.
6661//
6662mixkey(Math.random(), pool);
6663
6664/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(20)))
6665
6666/***/ }),
6667/* 16 */
6668/***/ (function(module, exports, __webpack_require__) {
6669
6670var __WEBPACK_AMD_DEFINE_RESULT__;;(function (globalScope) {
6671 'use strict';
6672
6673
6674 /*
6675 * decimal.js v10.2.0
6676 * An arbitrary-precision Decimal type for JavaScript.
6677 * https://github.com/MikeMcl/decimal.js
6678 * Copyright (c) 2019 Michael Mclaughlin <M8ch88l@gmail.com>
6679 * MIT Licence
6680 */
6681
6682
6683 // ----------------------------------- EDITABLE DEFAULTS ------------------------------------ //
6684
6685
6686 // The maximum exponent magnitude.
6687 // The limit on the value of `toExpNeg`, `toExpPos`, `minE` and `maxE`.
6688 var EXP_LIMIT = 9e15, // 0 to 9e15
6689
6690 // The limit on the value of `precision`, and on the value of the first argument to
6691 // `toDecimalPlaces`, `toExponential`, `toFixed`, `toPrecision` and `toSignificantDigits`.
6692 MAX_DIGITS = 1e9, // 0 to 1e9
6693
6694 // Base conversion alphabet.
6695 NUMERALS = '0123456789abcdef',
6696
6697 // The natural logarithm of 10 (1025 digits).
6698 LN10 = '2.3025850929940456840179914546843642076011014886287729760333279009675726096773524802359972050895982983419677840422862486334095254650828067566662873690987816894829072083255546808437998948262331985283935053089653777326288461633662222876982198867465436674744042432743651550489343149393914796194044002221051017141748003688084012647080685567743216228355220114804663715659121373450747856947683463616792101806445070648000277502684916746550586856935673420670581136429224554405758925724208241314695689016758940256776311356919292033376587141660230105703089634572075440370847469940168269282808481184289314848524948644871927809676271275775397027668605952496716674183485704422507197965004714951050492214776567636938662976979522110718264549734772662425709429322582798502585509785265383207606726317164309505995087807523710333101197857547331541421808427543863591778117054309827482385045648019095610299291824318237525357709750539565187697510374970888692180205189339507238539205144634197265287286965110862571492198849978748873771345686209167058',
6699
6700 // Pi (1025 digits).
6701 PI = '3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823066470938446095505822317253594081284811174502841027019385211055596446229489549303819644288109756659334461284756482337867831652712019091456485669234603486104543266482133936072602491412737245870066063155881748815209209628292540917153643678925903600113305305488204665213841469519415116094330572703657595919530921861173819326117931051185480744623799627495673518857527248912279381830119491298336733624406566430860213949463952247371907021798609437027705392171762931767523846748184676694051320005681271452635608277857713427577896091736371787214684409012249534301465495853710507922796892589235420199561121290219608640344181598136297747713099605187072113499999983729780499510597317328160963185950244594553469083026425223082533446850352619311881710100031378387528865875332083814206171776691473035982534904287554687311595628638823537875937519577818577805321712268066130019278766111959092164201989380952572010654858632789',
6702
6703
6704 // The initial configuration properties of the Decimal constructor.
6705 DEFAULTS = {
6706
6707 // These values must be integers within the stated ranges (inclusive).
6708 // Most of these values can be changed at run-time using the `Decimal.config` method.
6709
6710 // The maximum number of significant digits of the result of a calculation or base conversion.
6711 // E.g. `Decimal.config({ precision: 20 });`
6712 precision: 20, // 1 to MAX_DIGITS
6713
6714 // The rounding mode used when rounding to `precision`.
6715 //
6716 // ROUND_UP 0 Away from zero.
6717 // ROUND_DOWN 1 Towards zero.
6718 // ROUND_CEIL 2 Towards +Infinity.
6719 // ROUND_FLOOR 3 Towards -Infinity.
6720 // ROUND_HALF_UP 4 Towards nearest neighbour. If equidistant, up.
6721 // ROUND_HALF_DOWN 5 Towards nearest neighbour. If equidistant, down.
6722 // ROUND_HALF_EVEN 6 Towards nearest neighbour. If equidistant, towards even neighbour.
6723 // ROUND_HALF_CEIL 7 Towards nearest neighbour. If equidistant, towards +Infinity.
6724 // ROUND_HALF_FLOOR 8 Towards nearest neighbour. If equidistant, towards -Infinity.
6725 //
6726 // E.g.
6727 // `Decimal.rounding = 4;`
6728 // `Decimal.rounding = Decimal.ROUND_HALF_UP;`
6729 rounding: 4, // 0 to 8
6730
6731 // The modulo mode used when calculating the modulus: a mod n.
6732 // The quotient (q = a / n) is calculated according to the corresponding rounding mode.
6733 // The remainder (r) is calculated as: r = a - n * q.
6734 //
6735 // UP 0 The remainder is positive if the dividend is negative, else is negative.
6736 // DOWN 1 The remainder has the same sign as the dividend (JavaScript %).
6737 // FLOOR 3 The remainder has the same sign as the divisor (Python %).
6738 // HALF_EVEN 6 The IEEE 754 remainder function.
6739 // EUCLID 9 Euclidian division. q = sign(n) * floor(a / abs(n)). Always positive.
6740 //
6741 // Truncated division (1), floored division (3), the IEEE 754 remainder (6), and Euclidian
6742 // division (9) are commonly used for the modulus operation. The other rounding modes can also
6743 // be used, but they may not give useful results.
6744 modulo: 1, // 0 to 9
6745
6746 // The exponent value at and beneath which `toString` returns exponential notation.
6747 // JavaScript numbers: -7
6748 toExpNeg: -7, // 0 to -EXP_LIMIT
6749
6750 // The exponent value at and above which `toString` returns exponential notation.
6751 // JavaScript numbers: 21
6752 toExpPos: 21, // 0 to EXP_LIMIT
6753
6754 // The minimum exponent value, beneath which underflow to zero occurs.
6755 // JavaScript numbers: -324 (5e-324)
6756 minE: -EXP_LIMIT, // -1 to -EXP_LIMIT
6757
6758 // The maximum exponent value, above which overflow to Infinity occurs.
6759 // JavaScript numbers: 308 (1.7976931348623157e+308)
6760 maxE: EXP_LIMIT, // 1 to EXP_LIMIT
6761
6762 // Whether to use cryptographically-secure random number generation, if available.
6763 crypto: false // true/false
6764 },
6765
6766
6767 // ----------------------------------- END OF EDITABLE DEFAULTS ------------------------------- //
6768
6769
6770 Decimal, inexact, noConflict, quadrant,
6771 external = true,
6772
6773 decimalError = '[DecimalError] ',
6774 invalidArgument = decimalError + 'Invalid argument: ',
6775 precisionLimitExceeded = decimalError + 'Precision limit exceeded',
6776 cryptoUnavailable = decimalError + 'crypto unavailable',
6777
6778 mathfloor = Math.floor,
6779 mathpow = Math.pow,
6780
6781 isBinary = /^0b([01]+(\.[01]*)?|\.[01]+)(p[+-]?\d+)?$/i,
6782 isHex = /^0x([0-9a-f]+(\.[0-9a-f]*)?|\.[0-9a-f]+)(p[+-]?\d+)?$/i,
6783 isOctal = /^0o([0-7]+(\.[0-7]*)?|\.[0-7]+)(p[+-]?\d+)?$/i,
6784 isDecimal = /^(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i,
6785
6786 BASE = 1e7,
6787 LOG_BASE = 7,
6788 MAX_SAFE_INTEGER = 9007199254740991,
6789
6790 LN10_PRECISION = LN10.length - 1,
6791 PI_PRECISION = PI.length - 1,
6792
6793 // Decimal.prototype object
6794 P = { name: '[object Decimal]' };
6795
6796
6797 // Decimal prototype methods
6798
6799
6800 /*
6801 * absoluteValue abs
6802 * ceil
6803 * comparedTo cmp
6804 * cosine cos
6805 * cubeRoot cbrt
6806 * decimalPlaces dp
6807 * dividedBy div
6808 * dividedToIntegerBy divToInt
6809 * equals eq
6810 * floor
6811 * greaterThan gt
6812 * greaterThanOrEqualTo gte
6813 * hyperbolicCosine cosh
6814 * hyperbolicSine sinh
6815 * hyperbolicTangent tanh
6816 * inverseCosine acos
6817 * inverseHyperbolicCosine acosh
6818 * inverseHyperbolicSine asinh
6819 * inverseHyperbolicTangent atanh
6820 * inverseSine asin
6821 * inverseTangent atan
6822 * isFinite
6823 * isInteger isInt
6824 * isNaN
6825 * isNegative isNeg
6826 * isPositive isPos
6827 * isZero
6828 * lessThan lt
6829 * lessThanOrEqualTo lte
6830 * logarithm log
6831 * [maximum] [max]
6832 * [minimum] [min]
6833 * minus sub
6834 * modulo mod
6835 * naturalExponential exp
6836 * naturalLogarithm ln
6837 * negated neg
6838 * plus add
6839 * precision sd
6840 * round
6841 * sine sin
6842 * squareRoot sqrt
6843 * tangent tan
6844 * times mul
6845 * toBinary
6846 * toDecimalPlaces toDP
6847 * toExponential
6848 * toFixed
6849 * toFraction
6850 * toHexadecimal toHex
6851 * toNearest
6852 * toNumber
6853 * toOctal
6854 * toPower pow
6855 * toPrecision
6856 * toSignificantDigits toSD
6857 * toString
6858 * truncated trunc
6859 * valueOf toJSON
6860 */
6861
6862
6863 /*
6864 * Return a new Decimal whose value is the absolute value of this Decimal.
6865 *
6866 */
6867 P.absoluteValue = P.abs = function () {
6868 var x = new this.constructor(this);
6869 if (x.s < 0) x.s = 1;
6870 return finalise(x);
6871 };
6872
6873
6874 /*
6875 * Return a new Decimal whose value is the value of this Decimal rounded to a whole number in the
6876 * direction of positive Infinity.
6877 *
6878 */
6879 P.ceil = function () {
6880 return finalise(new this.constructor(this), this.e + 1, 2);
6881 };
6882
6883
6884 /*
6885 * Return
6886 * 1 if the value of this Decimal is greater than the value of `y`,
6887 * -1 if the value of this Decimal is less than the value of `y`,
6888 * 0 if they have the same value,
6889 * NaN if the value of either Decimal is NaN.
6890 *
6891 */
6892 P.comparedTo = P.cmp = function (y) {
6893 var i, j, xdL, ydL,
6894 x = this,
6895 xd = x.d,
6896 yd = (y = new x.constructor(y)).d,
6897 xs = x.s,
6898 ys = y.s;
6899
6900 // Either NaN or ±Infinity?
6901 if (!xd || !yd) {
6902 return !xs || !ys ? NaN : xs !== ys ? xs : xd === yd ? 0 : !xd ^ xs < 0 ? 1 : -1;
6903 }
6904
6905 // Either zero?
6906 if (!xd[0] || !yd[0]) return xd[0] ? xs : yd[0] ? -ys : 0;
6907
6908 // Signs differ?
6909 if (xs !== ys) return xs;
6910
6911 // Compare exponents.
6912 if (x.e !== y.e) return x.e > y.e ^ xs < 0 ? 1 : -1;
6913
6914 xdL = xd.length;
6915 ydL = yd.length;
6916
6917 // Compare digit by digit.
6918 for (i = 0, j = xdL < ydL ? xdL : ydL; i < j; ++i) {
6919 if (xd[i] !== yd[i]) return xd[i] > yd[i] ^ xs < 0 ? 1 : -1;
6920 }
6921
6922 // Compare lengths.
6923 return xdL === ydL ? 0 : xdL > ydL ^ xs < 0 ? 1 : -1;
6924 };
6925
6926
6927 /*
6928 * Return a new Decimal whose value is the cosine of the value in radians of this Decimal.
6929 *
6930 * Domain: [-Infinity, Infinity]
6931 * Range: [-1, 1]
6932 *
6933 * cos(0) = 1
6934 * cos(-0) = 1
6935 * cos(Infinity) = NaN
6936 * cos(-Infinity) = NaN
6937 * cos(NaN) = NaN
6938 *
6939 */
6940 P.cosine = P.cos = function () {
6941 var pr, rm,
6942 x = this,
6943 Ctor = x.constructor;
6944
6945 if (!x.d) return new Ctor(NaN);
6946
6947 // cos(0) = cos(-0) = 1
6948 if (!x.d[0]) return new Ctor(1);
6949
6950 pr = Ctor.precision;
6951 rm = Ctor.rounding;
6952 Ctor.precision = pr + Math.max(x.e, x.sd()) + LOG_BASE;
6953 Ctor.rounding = 1;
6954
6955 x = cosine(Ctor, toLessThanHalfPi(Ctor, x));
6956
6957 Ctor.precision = pr;
6958 Ctor.rounding = rm;
6959
6960 return finalise(quadrant == 2 || quadrant == 3 ? x.neg() : x, pr, rm, true);
6961 };
6962
6963
6964 /*
6965 *
6966 * Return a new Decimal whose value is the cube root of the value of this Decimal, rounded to
6967 * `precision` significant digits using rounding mode `rounding`.
6968 *
6969 * cbrt(0) = 0
6970 * cbrt(-0) = -0
6971 * cbrt(1) = 1
6972 * cbrt(-1) = -1
6973 * cbrt(N) = N
6974 * cbrt(-I) = -I
6975 * cbrt(I) = I
6976 *
6977 * Math.cbrt(x) = (x < 0 ? -Math.pow(-x, 1/3) : Math.pow(x, 1/3))
6978 *
6979 */
6980 P.cubeRoot = P.cbrt = function () {
6981 var e, m, n, r, rep, s, sd, t, t3, t3plusx,
6982 x = this,
6983 Ctor = x.constructor;
6984
6985 if (!x.isFinite() || x.isZero()) return new Ctor(x);
6986 external = false;
6987
6988 // Initial estimate.
6989 s = x.s * mathpow(x.s * x, 1 / 3);
6990
6991 // Math.cbrt underflow/overflow?
6992 // Pass x to Math.pow as integer, then adjust the exponent of the result.
6993 if (!s || Math.abs(s) == 1 / 0) {
6994 n = digitsToString(x.d);
6995 e = x.e;
6996
6997 // Adjust n exponent so it is a multiple of 3 away from x exponent.
6998 if (s = (e - n.length + 1) % 3) n += (s == 1 || s == -2 ? '0' : '00');
6999 s = mathpow(n, 1 / 3);
7000
7001 // Rarely, e may be one less than the result exponent value.
7002 e = mathfloor((e + 1) / 3) - (e % 3 == (e < 0 ? -1 : 2));
7003
7004 if (s == 1 / 0) {
7005 n = '5e' + e;
7006 } else {
7007 n = s.toExponential();
7008 n = n.slice(0, n.indexOf('e') + 1) + e;
7009 }
7010
7011 r = new Ctor(n);
7012 r.s = x.s;
7013 } else {
7014 r = new Ctor(s.toString());
7015 }
7016
7017 sd = (e = Ctor.precision) + 3;
7018
7019 // Halley's method.
7020 // TODO? Compare Newton's method.
7021 for (;;) {
7022 t = r;
7023 t3 = t.times(t).times(t);
7024 t3plusx = t3.plus(x);
7025 r = divide(t3plusx.plus(x).times(t), t3plusx.plus(t3), sd + 2, 1);
7026
7027 // TODO? Replace with for-loop and checkRoundingDigits.
7028 if (digitsToString(t.d).slice(0, sd) === (n = digitsToString(r.d)).slice(0, sd)) {
7029 n = n.slice(sd - 3, sd + 1);
7030
7031 // The 4th rounding digit may be in error by -1 so if the 4 rounding digits are 9999 or 4999
7032 // , i.e. approaching a rounding boundary, continue the iteration.
7033 if (n == '9999' || !rep && n == '4999') {
7034
7035 // On the first iteration only, check to see if rounding up gives the exact result as the
7036 // nines may infinitely repeat.
7037 if (!rep) {
7038 finalise(t, e + 1, 0);
7039
7040 if (t.times(t).times(t).eq(x)) {
7041 r = t;
7042 break;
7043 }
7044 }
7045
7046 sd += 4;
7047 rep = 1;
7048 } else {
7049
7050 // If the rounding digits are null, 0{0,4} or 50{0,3}, check for an exact result.
7051 // If not, then there are further digits and m will be truthy.
7052 if (!+n || !+n.slice(1) && n.charAt(0) == '5') {
7053
7054 // Truncate to the first rounding digit.
7055 finalise(r, e + 1, 1);
7056 m = !r.times(r).times(r).eq(x);
7057 }
7058
7059 break;
7060 }
7061 }
7062 }
7063
7064 external = true;
7065
7066 return finalise(r, e, Ctor.rounding, m);
7067 };
7068
7069
7070 /*
7071 * Return the number of decimal places of the value of this Decimal.
7072 *
7073 */
7074 P.decimalPlaces = P.dp = function () {
7075 var w,
7076 d = this.d,
7077 n = NaN;
7078
7079 if (d) {
7080 w = d.length - 1;
7081 n = (w - mathfloor(this.e / LOG_BASE)) * LOG_BASE;
7082
7083 // Subtract the number of trailing zeros of the last word.
7084 w = d[w];
7085 if (w) for (; w % 10 == 0; w /= 10) n--;
7086 if (n < 0) n = 0;
7087 }
7088
7089 return n;
7090 };
7091
7092
7093 /*
7094 * n / 0 = I
7095 * n / N = N
7096 * n / I = 0
7097 * 0 / n = 0
7098 * 0 / 0 = N
7099 * 0 / N = N
7100 * 0 / I = 0
7101 * N / n = N
7102 * N / 0 = N
7103 * N / N = N
7104 * N / I = N
7105 * I / n = I
7106 * I / 0 = I
7107 * I / N = N
7108 * I / I = N
7109 *
7110 * Return a new Decimal whose value is the value of this Decimal divided by `y`, rounded to
7111 * `precision` significant digits using rounding mode `rounding`.
7112 *
7113 */
7114 P.dividedBy = P.div = function (y) {
7115 return divide(this, new this.constructor(y));
7116 };
7117
7118
7119 /*
7120 * Return a new Decimal whose value is the integer part of dividing the value of this Decimal
7121 * by the value of `y`, rounded to `precision` significant digits using rounding mode `rounding`.
7122 *
7123 */
7124 P.dividedToIntegerBy = P.divToInt = function (y) {
7125 var x = this,
7126 Ctor = x.constructor;
7127 return finalise(divide(x, new Ctor(y), 0, 1, 1), Ctor.precision, Ctor.rounding);
7128 };
7129
7130
7131 /*
7132 * Return true if the value of this Decimal is equal to the value of `y`, otherwise return false.
7133 *
7134 */
7135 P.equals = P.eq = function (y) {
7136 return this.cmp(y) === 0;
7137 };
7138
7139
7140 /*
7141 * Return a new Decimal whose value is the value of this Decimal rounded to a whole number in the
7142 * direction of negative Infinity.
7143 *
7144 */
7145 P.floor = function () {
7146 return finalise(new this.constructor(this), this.e + 1, 3);
7147 };
7148
7149
7150 /*
7151 * Return true if the value of this Decimal is greater than the value of `y`, otherwise return
7152 * false.
7153 *
7154 */
7155 P.greaterThan = P.gt = function (y) {
7156 return this.cmp(y) > 0;
7157 };
7158
7159
7160 /*
7161 * Return true if the value of this Decimal is greater than or equal to the value of `y`,
7162 * otherwise return false.
7163 *
7164 */
7165 P.greaterThanOrEqualTo = P.gte = function (y) {
7166 var k = this.cmp(y);
7167 return k == 1 || k === 0;
7168 };
7169
7170
7171 /*
7172 * Return a new Decimal whose value is the hyperbolic cosine of the value in radians of this
7173 * Decimal.
7174 *
7175 * Domain: [-Infinity, Infinity]
7176 * Range: [1, Infinity]
7177 *
7178 * cosh(x) = 1 + x^2/2! + x^4/4! + x^6/6! + ...
7179 *
7180 * cosh(0) = 1
7181 * cosh(-0) = 1
7182 * cosh(Infinity) = Infinity
7183 * cosh(-Infinity) = Infinity
7184 * cosh(NaN) = NaN
7185 *
7186 * x time taken (ms) result
7187 * 1000 9 9.8503555700852349694e+433
7188 * 10000 25 4.4034091128314607936e+4342
7189 * 100000 171 1.4033316802130615897e+43429
7190 * 1000000 3817 1.5166076984010437725e+434294
7191 * 10000000 abandoned after 2 minute wait
7192 *
7193 * TODO? Compare performance of cosh(x) = 0.5 * (exp(x) + exp(-x))
7194 *
7195 */
7196 P.hyperbolicCosine = P.cosh = function () {
7197 var k, n, pr, rm, len,
7198 x = this,
7199 Ctor = x.constructor,
7200 one = new Ctor(1);
7201
7202 if (!x.isFinite()) return new Ctor(x.s ? 1 / 0 : NaN);
7203 if (x.isZero()) return one;
7204
7205 pr = Ctor.precision;
7206 rm = Ctor.rounding;
7207 Ctor.precision = pr + Math.max(x.e, x.sd()) + 4;
7208 Ctor.rounding = 1;
7209 len = x.d.length;
7210
7211 // Argument reduction: cos(4x) = 1 - 8cos^2(x) + 8cos^4(x) + 1
7212 // i.e. cos(x) = 1 - cos^2(x/4)(8 - 8cos^2(x/4))
7213
7214 // Estimate the optimum number of times to use the argument reduction.
7215 // TODO? Estimation reused from cosine() and may not be optimal here.
7216 if (len < 32) {
7217 k = Math.ceil(len / 3);
7218 n = (1 / tinyPow(4, k)).toString();
7219 } else {
7220 k = 16;
7221 n = '2.3283064365386962890625e-10';
7222 }
7223
7224 x = taylorSeries(Ctor, 1, x.times(n), new Ctor(1), true);
7225
7226 // Reverse argument reduction
7227 var cosh2_x,
7228 i = k,
7229 d8 = new Ctor(8);
7230 for (; i--;) {
7231 cosh2_x = x.times(x);
7232 x = one.minus(cosh2_x.times(d8.minus(cosh2_x.times(d8))));
7233 }
7234
7235 return finalise(x, Ctor.precision = pr, Ctor.rounding = rm, true);
7236 };
7237
7238
7239 /*
7240 * Return a new Decimal whose value is the hyperbolic sine of the value in radians of this
7241 * Decimal.
7242 *
7243 * Domain: [-Infinity, Infinity]
7244 * Range: [-Infinity, Infinity]
7245 *
7246 * sinh(x) = x + x^3/3! + x^5/5! + x^7/7! + ...
7247 *
7248 * sinh(0) = 0
7249 * sinh(-0) = -0
7250 * sinh(Infinity) = Infinity
7251 * sinh(-Infinity) = -Infinity
7252 * sinh(NaN) = NaN
7253 *
7254 * x time taken (ms)
7255 * 10 2 ms
7256 * 100 5 ms
7257 * 1000 14 ms
7258 * 10000 82 ms
7259 * 100000 886 ms 1.4033316802130615897e+43429
7260 * 200000 2613 ms
7261 * 300000 5407 ms
7262 * 400000 8824 ms
7263 * 500000 13026 ms 8.7080643612718084129e+217146
7264 * 1000000 48543 ms
7265 *
7266 * TODO? Compare performance of sinh(x) = 0.5 * (exp(x) - exp(-x))
7267 *
7268 */
7269 P.hyperbolicSine = P.sinh = function () {
7270 var k, pr, rm, len,
7271 x = this,
7272 Ctor = x.constructor;
7273
7274 if (!x.isFinite() || x.isZero()) return new Ctor(x);
7275
7276 pr = Ctor.precision;
7277 rm = Ctor.rounding;
7278 Ctor.precision = pr + Math.max(x.e, x.sd()) + 4;
7279 Ctor.rounding = 1;
7280 len = x.d.length;
7281
7282 if (len < 3) {
7283 x = taylorSeries(Ctor, 2, x, x, true);
7284 } else {
7285
7286 // Alternative argument reduction: sinh(3x) = sinh(x)(3 + 4sinh^2(x))
7287 // i.e. sinh(x) = sinh(x/3)(3 + 4sinh^2(x/3))
7288 // 3 multiplications and 1 addition
7289
7290 // Argument reduction: sinh(5x) = sinh(x)(5 + sinh^2(x)(20 + 16sinh^2(x)))
7291 // i.e. sinh(x) = sinh(x/5)(5 + sinh^2(x/5)(20 + 16sinh^2(x/5)))
7292 // 4 multiplications and 2 additions
7293
7294 // Estimate the optimum number of times to use the argument reduction.
7295 k = 1.4 * Math.sqrt(len);
7296 k = k > 16 ? 16 : k | 0;
7297
7298 x = x.times(1 / tinyPow(5, k));
7299 x = taylorSeries(Ctor, 2, x, x, true);
7300
7301 // Reverse argument reduction
7302 var sinh2_x,
7303 d5 = new Ctor(5),
7304 d16 = new Ctor(16),
7305 d20 = new Ctor(20);
7306 for (; k--;) {
7307 sinh2_x = x.times(x);
7308 x = x.times(d5.plus(sinh2_x.times(d16.times(sinh2_x).plus(d20))));
7309 }
7310 }
7311
7312 Ctor.precision = pr;
7313 Ctor.rounding = rm;
7314
7315 return finalise(x, pr, rm, true);
7316 };
7317
7318
7319 /*
7320 * Return a new Decimal whose value is the hyperbolic tangent of the value in radians of this
7321 * Decimal.
7322 *
7323 * Domain: [-Infinity, Infinity]
7324 * Range: [-1, 1]
7325 *
7326 * tanh(x) = sinh(x) / cosh(x)
7327 *
7328 * tanh(0) = 0
7329 * tanh(-0) = -0
7330 * tanh(Infinity) = 1
7331 * tanh(-Infinity) = -1
7332 * tanh(NaN) = NaN
7333 *
7334 */
7335 P.hyperbolicTangent = P.tanh = function () {
7336 var pr, rm,
7337 x = this,
7338 Ctor = x.constructor;
7339
7340 if (!x.isFinite()) return new Ctor(x.s);
7341 if (x.isZero()) return new Ctor(x);
7342
7343 pr = Ctor.precision;
7344 rm = Ctor.rounding;
7345 Ctor.precision = pr + 7;
7346 Ctor.rounding = 1;
7347
7348 return divide(x.sinh(), x.cosh(), Ctor.precision = pr, Ctor.rounding = rm);
7349 };
7350
7351
7352 /*
7353 * Return a new Decimal whose value is the arccosine (inverse cosine) in radians of the value of
7354 * this Decimal.
7355 *
7356 * Domain: [-1, 1]
7357 * Range: [0, pi]
7358 *
7359 * acos(x) = pi/2 - asin(x)
7360 *
7361 * acos(0) = pi/2
7362 * acos(-0) = pi/2
7363 * acos(1) = 0
7364 * acos(-1) = pi
7365 * acos(1/2) = pi/3
7366 * acos(-1/2) = 2*pi/3
7367 * acos(|x| > 1) = NaN
7368 * acos(NaN) = NaN
7369 *
7370 */
7371 P.inverseCosine = P.acos = function () {
7372 var halfPi,
7373 x = this,
7374 Ctor = x.constructor,
7375 k = x.abs().cmp(1),
7376 pr = Ctor.precision,
7377 rm = Ctor.rounding;
7378
7379 if (k !== -1) {
7380 return k === 0
7381 // |x| is 1
7382 ? x.isNeg() ? getPi(Ctor, pr, rm) : new Ctor(0)
7383 // |x| > 1 or x is NaN
7384 : new Ctor(NaN);
7385 }
7386
7387 if (x.isZero()) return getPi(Ctor, pr + 4, rm).times(0.5);
7388
7389 // TODO? Special case acos(0.5) = pi/3 and acos(-0.5) = 2*pi/3
7390
7391 Ctor.precision = pr + 6;
7392 Ctor.rounding = 1;
7393
7394 x = x.asin();
7395 halfPi = getPi(Ctor, pr + 4, rm).times(0.5);
7396
7397 Ctor.precision = pr;
7398 Ctor.rounding = rm;
7399
7400 return halfPi.minus(x);
7401 };
7402
7403
7404 /*
7405 * Return a new Decimal whose value is the inverse of the hyperbolic cosine in radians of the
7406 * value of this Decimal.
7407 *
7408 * Domain: [1, Infinity]
7409 * Range: [0, Infinity]
7410 *
7411 * acosh(x) = ln(x + sqrt(x^2 - 1))
7412 *
7413 * acosh(x < 1) = NaN
7414 * acosh(NaN) = NaN
7415 * acosh(Infinity) = Infinity
7416 * acosh(-Infinity) = NaN
7417 * acosh(0) = NaN
7418 * acosh(-0) = NaN
7419 * acosh(1) = 0
7420 * acosh(-1) = NaN
7421 *
7422 */
7423 P.inverseHyperbolicCosine = P.acosh = function () {
7424 var pr, rm,
7425 x = this,
7426 Ctor = x.constructor;
7427
7428 if (x.lte(1)) return new Ctor(x.eq(1) ? 0 : NaN);
7429 if (!x.isFinite()) return new Ctor(x);
7430
7431 pr = Ctor.precision;
7432 rm = Ctor.rounding;
7433 Ctor.precision = pr + Math.max(Math.abs(x.e), x.sd()) + 4;
7434 Ctor.rounding = 1;
7435 external = false;
7436
7437 x = x.times(x).minus(1).sqrt().plus(x);
7438
7439 external = true;
7440 Ctor.precision = pr;
7441 Ctor.rounding = rm;
7442
7443 return x.ln();
7444 };
7445
7446
7447 /*
7448 * Return a new Decimal whose value is the inverse of the hyperbolic sine in radians of the value
7449 * of this Decimal.
7450 *
7451 * Domain: [-Infinity, Infinity]
7452 * Range: [-Infinity, Infinity]
7453 *
7454 * asinh(x) = ln(x + sqrt(x^2 + 1))
7455 *
7456 * asinh(NaN) = NaN
7457 * asinh(Infinity) = Infinity
7458 * asinh(-Infinity) = -Infinity
7459 * asinh(0) = 0
7460 * asinh(-0) = -0
7461 *
7462 */
7463 P.inverseHyperbolicSine = P.asinh = function () {
7464 var pr, rm,
7465 x = this,
7466 Ctor = x.constructor;
7467
7468 if (!x.isFinite() || x.isZero()) return new Ctor(x);
7469
7470 pr = Ctor.precision;
7471 rm = Ctor.rounding;
7472 Ctor.precision = pr + 2 * Math.max(Math.abs(x.e), x.sd()) + 6;
7473 Ctor.rounding = 1;
7474 external = false;
7475
7476 x = x.times(x).plus(1).sqrt().plus(x);
7477
7478 external = true;
7479 Ctor.precision = pr;
7480 Ctor.rounding = rm;
7481
7482 return x.ln();
7483 };
7484
7485
7486 /*
7487 * Return a new Decimal whose value is the inverse of the hyperbolic tangent in radians of the
7488 * value of this Decimal.
7489 *
7490 * Domain: [-1, 1]
7491 * Range: [-Infinity, Infinity]
7492 *
7493 * atanh(x) = 0.5 * ln((1 + x) / (1 - x))
7494 *
7495 * atanh(|x| > 1) = NaN
7496 * atanh(NaN) = NaN
7497 * atanh(Infinity) = NaN
7498 * atanh(-Infinity) = NaN
7499 * atanh(0) = 0
7500 * atanh(-0) = -0
7501 * atanh(1) = Infinity
7502 * atanh(-1) = -Infinity
7503 *
7504 */
7505 P.inverseHyperbolicTangent = P.atanh = function () {
7506 var pr, rm, wpr, xsd,
7507 x = this,
7508 Ctor = x.constructor;
7509
7510 if (!x.isFinite()) return new Ctor(NaN);
7511 if (x.e >= 0) return new Ctor(x.abs().eq(1) ? x.s / 0 : x.isZero() ? x : NaN);
7512
7513 pr = Ctor.precision;
7514 rm = Ctor.rounding;
7515 xsd = x.sd();
7516
7517 if (Math.max(xsd, pr) < 2 * -x.e - 1) return finalise(new Ctor(x), pr, rm, true);
7518
7519 Ctor.precision = wpr = xsd - x.e;
7520
7521 x = divide(x.plus(1), new Ctor(1).minus(x), wpr + pr, 1);
7522
7523 Ctor.precision = pr + 4;
7524 Ctor.rounding = 1;
7525
7526 x = x.ln();
7527
7528 Ctor.precision = pr;
7529 Ctor.rounding = rm;
7530
7531 return x.times(0.5);
7532 };
7533
7534
7535 /*
7536 * Return a new Decimal whose value is the arcsine (inverse sine) in radians of the value of this
7537 * Decimal.
7538 *
7539 * Domain: [-Infinity, Infinity]
7540 * Range: [-pi/2, pi/2]
7541 *
7542 * asin(x) = 2*atan(x/(1 + sqrt(1 - x^2)))
7543 *
7544 * asin(0) = 0
7545 * asin(-0) = -0
7546 * asin(1/2) = pi/6
7547 * asin(-1/2) = -pi/6
7548 * asin(1) = pi/2
7549 * asin(-1) = -pi/2
7550 * asin(|x| > 1) = NaN
7551 * asin(NaN) = NaN
7552 *
7553 * TODO? Compare performance of Taylor series.
7554 *
7555 */
7556 P.inverseSine = P.asin = function () {
7557 var halfPi, k,
7558 pr, rm,
7559 x = this,
7560 Ctor = x.constructor;
7561
7562 if (x.isZero()) return new Ctor(x);
7563
7564 k = x.abs().cmp(1);
7565 pr = Ctor.precision;
7566 rm = Ctor.rounding;
7567
7568 if (k !== -1) {
7569
7570 // |x| is 1
7571 if (k === 0) {
7572 halfPi = getPi(Ctor, pr + 4, rm).times(0.5);
7573 halfPi.s = x.s;
7574 return halfPi;
7575 }
7576
7577 // |x| > 1 or x is NaN
7578 return new Ctor(NaN);
7579 }
7580
7581 // TODO? Special case asin(1/2) = pi/6 and asin(-1/2) = -pi/6
7582
7583 Ctor.precision = pr + 6;
7584 Ctor.rounding = 1;
7585
7586 x = x.div(new Ctor(1).minus(x.times(x)).sqrt().plus(1)).atan();
7587
7588 Ctor.precision = pr;
7589 Ctor.rounding = rm;
7590
7591 return x.times(2);
7592 };
7593
7594
7595 /*
7596 * Return a new Decimal whose value is the arctangent (inverse tangent) in radians of the value
7597 * of this Decimal.
7598 *
7599 * Domain: [-Infinity, Infinity]
7600 * Range: [-pi/2, pi/2]
7601 *
7602 * atan(x) = x - x^3/3 + x^5/5 - x^7/7 + ...
7603 *
7604 * atan(0) = 0
7605 * atan(-0) = -0
7606 * atan(1) = pi/4
7607 * atan(-1) = -pi/4
7608 * atan(Infinity) = pi/2
7609 * atan(-Infinity) = -pi/2
7610 * atan(NaN) = NaN
7611 *
7612 */
7613 P.inverseTangent = P.atan = function () {
7614 var i, j, k, n, px, t, r, wpr, x2,
7615 x = this,
7616 Ctor = x.constructor,
7617 pr = Ctor.precision,
7618 rm = Ctor.rounding;
7619
7620 if (!x.isFinite()) {
7621 if (!x.s) return new Ctor(NaN);
7622 if (pr + 4 <= PI_PRECISION) {
7623 r = getPi(Ctor, pr + 4, rm).times(0.5);
7624 r.s = x.s;
7625 return r;
7626 }
7627 } else if (x.isZero()) {
7628 return new Ctor(x);
7629 } else if (x.abs().eq(1) && pr + 4 <= PI_PRECISION) {
7630 r = getPi(Ctor, pr + 4, rm).times(0.25);
7631 r.s = x.s;
7632 return r;
7633 }
7634
7635 Ctor.precision = wpr = pr + 10;
7636 Ctor.rounding = 1;
7637
7638 // TODO? if (x >= 1 && pr <= PI_PRECISION) atan(x) = halfPi * x.s - atan(1 / x);
7639
7640 // Argument reduction
7641 // Ensure |x| < 0.42
7642 // atan(x) = 2 * atan(x / (1 + sqrt(1 + x^2)))
7643
7644 k = Math.min(28, wpr / LOG_BASE + 2 | 0);
7645
7646 for (i = k; i; --i) x = x.div(x.times(x).plus(1).sqrt().plus(1));
7647
7648 external = false;
7649
7650 j = Math.ceil(wpr / LOG_BASE);
7651 n = 1;
7652 x2 = x.times(x);
7653 r = new Ctor(x);
7654 px = x;
7655
7656 // atan(x) = x - x^3/3 + x^5/5 - x^7/7 + ...
7657 for (; i !== -1;) {
7658 px = px.times(x2);
7659 t = r.minus(px.div(n += 2));
7660
7661 px = px.times(x2);
7662 r = t.plus(px.div(n += 2));
7663
7664 if (r.d[j] !== void 0) for (i = j; r.d[i] === t.d[i] && i--;);
7665 }
7666
7667 if (k) r = r.times(2 << (k - 1));
7668
7669 external = true;
7670
7671 return finalise(r, Ctor.precision = pr, Ctor.rounding = rm, true);
7672 };
7673
7674
7675 /*
7676 * Return true if the value of this Decimal is a finite number, otherwise return false.
7677 *
7678 */
7679 P.isFinite = function () {
7680 return !!this.d;
7681 };
7682
7683
7684 /*
7685 * Return true if the value of this Decimal is an integer, otherwise return false.
7686 *
7687 */
7688 P.isInteger = P.isInt = function () {
7689 return !!this.d && mathfloor(this.e / LOG_BASE) > this.d.length - 2;
7690 };
7691
7692
7693 /*
7694 * Return true if the value of this Decimal is NaN, otherwise return false.
7695 *
7696 */
7697 P.isNaN = function () {
7698 return !this.s;
7699 };
7700
7701
7702 /*
7703 * Return true if the value of this Decimal is negative, otherwise return false.
7704 *
7705 */
7706 P.isNegative = P.isNeg = function () {
7707 return this.s < 0;
7708 };
7709
7710
7711 /*
7712 * Return true if the value of this Decimal is positive, otherwise return false.
7713 *
7714 */
7715 P.isPositive = P.isPos = function () {
7716 return this.s > 0;
7717 };
7718
7719
7720 /*
7721 * Return true if the value of this Decimal is 0 or -0, otherwise return false.
7722 *
7723 */
7724 P.isZero = function () {
7725 return !!this.d && this.d[0] === 0;
7726 };
7727
7728
7729 /*
7730 * Return true if the value of this Decimal is less than `y`, otherwise return false.
7731 *
7732 */
7733 P.lessThan = P.lt = function (y) {
7734 return this.cmp(y) < 0;
7735 };
7736
7737
7738 /*
7739 * Return true if the value of this Decimal is less than or equal to `y`, otherwise return false.
7740 *
7741 */
7742 P.lessThanOrEqualTo = P.lte = function (y) {
7743 return this.cmp(y) < 1;
7744 };
7745
7746
7747 /*
7748 * Return the logarithm of the value of this Decimal to the specified base, rounded to `precision`
7749 * significant digits using rounding mode `rounding`.
7750 *
7751 * If no base is specified, return log[10](arg).
7752 *
7753 * log[base](arg) = ln(arg) / ln(base)
7754 *
7755 * The result will always be correctly rounded if the base of the log is 10, and 'almost always'
7756 * otherwise:
7757 *
7758 * Depending on the rounding mode, the result may be incorrectly rounded if the first fifteen
7759 * rounding digits are [49]99999999999999 or [50]00000000000000. In that case, the maximum error
7760 * between the result and the correctly rounded result will be one ulp (unit in the last place).
7761 *
7762 * log[-b](a) = NaN
7763 * log[0](a) = NaN
7764 * log[1](a) = NaN
7765 * log[NaN](a) = NaN
7766 * log[Infinity](a) = NaN
7767 * log[b](0) = -Infinity
7768 * log[b](-0) = -Infinity
7769 * log[b](-a) = NaN
7770 * log[b](1) = 0
7771 * log[b](Infinity) = Infinity
7772 * log[b](NaN) = NaN
7773 *
7774 * [base] {number|string|Decimal} The base of the logarithm.
7775 *
7776 */
7777 P.logarithm = P.log = function (base) {
7778 var isBase10, d, denominator, k, inf, num, sd, r,
7779 arg = this,
7780 Ctor = arg.constructor,
7781 pr = Ctor.precision,
7782 rm = Ctor.rounding,
7783 guard = 5;
7784
7785 // Default base is 10.
7786 if (base == null) {
7787 base = new Ctor(10);
7788 isBase10 = true;
7789 } else {
7790 base = new Ctor(base);
7791 d = base.d;
7792
7793 // Return NaN if base is negative, or non-finite, or is 0 or 1.
7794 if (base.s < 0 || !d || !d[0] || base.eq(1)) return new Ctor(NaN);
7795
7796 isBase10 = base.eq(10);
7797 }
7798
7799 d = arg.d;
7800
7801 // Is arg negative, non-finite, 0 or 1?
7802 if (arg.s < 0 || !d || !d[0] || arg.eq(1)) {
7803 return new Ctor(d && !d[0] ? -1 / 0 : arg.s != 1 ? NaN : d ? 0 : 1 / 0);
7804 }
7805
7806 // The result will have a non-terminating decimal expansion if base is 10 and arg is not an
7807 // integer power of 10.
7808 if (isBase10) {
7809 if (d.length > 1) {
7810 inf = true;
7811 } else {
7812 for (k = d[0]; k % 10 === 0;) k /= 10;
7813 inf = k !== 1;
7814 }
7815 }
7816
7817 external = false;
7818 sd = pr + guard;
7819 num = naturalLogarithm(arg, sd);
7820 denominator = isBase10 ? getLn10(Ctor, sd + 10) : naturalLogarithm(base, sd);
7821
7822 // The result will have 5 rounding digits.
7823 r = divide(num, denominator, sd, 1);
7824
7825 // If at a rounding boundary, i.e. the result's rounding digits are [49]9999 or [50]0000,
7826 // calculate 10 further digits.
7827 //
7828 // If the result is known to have an infinite decimal expansion, repeat this until it is clear
7829 // that the result is above or below the boundary. Otherwise, if after calculating the 10
7830 // further digits, the last 14 are nines, round up and assume the result is exact.
7831 // Also assume the result is exact if the last 14 are zero.
7832 //
7833 // Example of a result that will be incorrectly rounded:
7834 // log[1048576](4503599627370502) = 2.60000000000000009610279511444746...
7835 // The above result correctly rounded using ROUND_CEIL to 1 decimal place should be 2.7, but it
7836 // will be given as 2.6 as there are 15 zeros immediately after the requested decimal place, so
7837 // the exact result would be assumed to be 2.6, which rounded using ROUND_CEIL to 1 decimal
7838 // place is still 2.6.
7839 if (checkRoundingDigits(r.d, k = pr, rm)) {
7840
7841 do {
7842 sd += 10;
7843 num = naturalLogarithm(arg, sd);
7844 denominator = isBase10 ? getLn10(Ctor, sd + 10) : naturalLogarithm(base, sd);
7845 r = divide(num, denominator, sd, 1);
7846
7847 if (!inf) {
7848
7849 // Check for 14 nines from the 2nd rounding digit, as the first may be 4.
7850 if (+digitsToString(r.d).slice(k + 1, k + 15) + 1 == 1e14) {
7851 r = finalise(r, pr + 1, 0);
7852 }
7853
7854 break;
7855 }
7856 } while (checkRoundingDigits(r.d, k += 10, rm));
7857 }
7858
7859 external = true;
7860
7861 return finalise(r, pr, rm);
7862 };
7863
7864
7865 /*
7866 * Return a new Decimal whose value is the maximum of the arguments and the value of this Decimal.
7867 *
7868 * arguments {number|string|Decimal}
7869 *
7870 P.max = function () {
7871 Array.prototype.push.call(arguments, this);
7872 return maxOrMin(this.constructor, arguments, 'lt');
7873 };
7874 */
7875
7876
7877 /*
7878 * Return a new Decimal whose value is the minimum of the arguments and the value of this Decimal.
7879 *
7880 * arguments {number|string|Decimal}
7881 *
7882 P.min = function () {
7883 Array.prototype.push.call(arguments, this);
7884 return maxOrMin(this.constructor, arguments, 'gt');
7885 };
7886 */
7887
7888
7889 /*
7890 * n - 0 = n
7891 * n - N = N
7892 * n - I = -I
7893 * 0 - n = -n
7894 * 0 - 0 = 0
7895 * 0 - N = N
7896 * 0 - I = -I
7897 * N - n = N
7898 * N - 0 = N
7899 * N - N = N
7900 * N - I = N
7901 * I - n = I
7902 * I - 0 = I
7903 * I - N = N
7904 * I - I = N
7905 *
7906 * Return a new Decimal whose value is the value of this Decimal minus `y`, rounded to `precision`
7907 * significant digits using rounding mode `rounding`.
7908 *
7909 */
7910 P.minus = P.sub = function (y) {
7911 var d, e, i, j, k, len, pr, rm, xd, xe, xLTy, yd,
7912 x = this,
7913 Ctor = x.constructor;
7914
7915 y = new Ctor(y);
7916
7917 // If either is not finite...
7918 if (!x.d || !y.d) {
7919
7920 // Return NaN if either is NaN.
7921 if (!x.s || !y.s) y = new Ctor(NaN);
7922
7923 // Return y negated if x is finite and y is ±Infinity.
7924 else if (x.d) y.s = -y.s;
7925
7926 // Return x if y is finite and x is ±Infinity.
7927 // Return x if both are ±Infinity with different signs.
7928 // Return NaN if both are ±Infinity with the same sign.
7929 else y = new Ctor(y.d || x.s !== y.s ? x : NaN);
7930
7931 return y;
7932 }
7933
7934 // If signs differ...
7935 if (x.s != y.s) {
7936 y.s = -y.s;
7937 return x.plus(y);
7938 }
7939
7940 xd = x.d;
7941 yd = y.d;
7942 pr = Ctor.precision;
7943 rm = Ctor.rounding;
7944
7945 // If either is zero...
7946 if (!xd[0] || !yd[0]) {
7947
7948 // Return y negated if x is zero and y is non-zero.
7949 if (yd[0]) y.s = -y.s;
7950
7951 // Return x if y is zero and x is non-zero.
7952 else if (xd[0]) y = new Ctor(x);
7953
7954 // Return zero if both are zero.
7955 // From IEEE 754 (2008) 6.3: 0 - 0 = -0 - -0 = -0 when rounding to -Infinity.
7956 else return new Ctor(rm === 3 ? -0 : 0);
7957
7958 return external ? finalise(y, pr, rm) : y;
7959 }
7960
7961 // x and y are finite, non-zero numbers with the same sign.
7962
7963 // Calculate base 1e7 exponents.
7964 e = mathfloor(y.e / LOG_BASE);
7965 xe = mathfloor(x.e / LOG_BASE);
7966
7967 xd = xd.slice();
7968 k = xe - e;
7969
7970 // If base 1e7 exponents differ...
7971 if (k) {
7972 xLTy = k < 0;
7973
7974 if (xLTy) {
7975 d = xd;
7976 k = -k;
7977 len = yd.length;
7978 } else {
7979 d = yd;
7980 e = xe;
7981 len = xd.length;
7982 }
7983
7984 // Numbers with massively different exponents would result in a very high number of
7985 // zeros needing to be prepended, but this can be avoided while still ensuring correct
7986 // rounding by limiting the number of zeros to `Math.ceil(pr / LOG_BASE) + 2`.
7987 i = Math.max(Math.ceil(pr / LOG_BASE), len) + 2;
7988
7989 if (k > i) {
7990 k = i;
7991 d.length = 1;
7992 }
7993
7994 // Prepend zeros to equalise exponents.
7995 d.reverse();
7996 for (i = k; i--;) d.push(0);
7997 d.reverse();
7998
7999 // Base 1e7 exponents equal.
8000 } else {
8001
8002 // Check digits to determine which is the bigger number.
8003
8004 i = xd.length;
8005 len = yd.length;
8006 xLTy = i < len;
8007 if (xLTy) len = i;
8008
8009 for (i = 0; i < len; i++) {
8010 if (xd[i] != yd[i]) {
8011 xLTy = xd[i] < yd[i];
8012 break;
8013 }
8014 }
8015
8016 k = 0;
8017 }
8018
8019 if (xLTy) {
8020 d = xd;
8021 xd = yd;
8022 yd = d;
8023 y.s = -y.s;
8024 }
8025
8026 len = xd.length;
8027
8028 // Append zeros to `xd` if shorter.
8029 // Don't add zeros to `yd` if shorter as subtraction only needs to start at `yd` length.
8030 for (i = yd.length - len; i > 0; --i) xd[len++] = 0;
8031
8032 // Subtract yd from xd.
8033 for (i = yd.length; i > k;) {
8034
8035 if (xd[--i] < yd[i]) {
8036 for (j = i; j && xd[--j] === 0;) xd[j] = BASE - 1;
8037 --xd[j];
8038 xd[i] += BASE;
8039 }
8040
8041 xd[i] -= yd[i];
8042 }
8043
8044 // Remove trailing zeros.
8045 for (; xd[--len] === 0;) xd.pop();
8046
8047 // Remove leading zeros and adjust exponent accordingly.
8048 for (; xd[0] === 0; xd.shift()) --e;
8049
8050 // Zero?
8051 if (!xd[0]) return new Ctor(rm === 3 ? -0 : 0);
8052
8053 y.d = xd;
8054 y.e = getBase10Exponent(xd, e);
8055
8056 return external ? finalise(y, pr, rm) : y;
8057 };
8058
8059
8060 /*
8061 * n % 0 = N
8062 * n % N = N
8063 * n % I = n
8064 * 0 % n = 0
8065 * -0 % n = -0
8066 * 0 % 0 = N
8067 * 0 % N = N
8068 * 0 % I = 0
8069 * N % n = N
8070 * N % 0 = N
8071 * N % N = N
8072 * N % I = N
8073 * I % n = N
8074 * I % 0 = N
8075 * I % N = N
8076 * I % I = N
8077 *
8078 * Return a new Decimal whose value is the value of this Decimal modulo `y`, rounded to
8079 * `precision` significant digits using rounding mode `rounding`.
8080 *
8081 * The result depends on the modulo mode.
8082 *
8083 */
8084 P.modulo = P.mod = function (y) {
8085 var q,
8086 x = this,
8087 Ctor = x.constructor;
8088
8089 y = new Ctor(y);
8090
8091 // Return NaN if x is ±Infinity or NaN, or y is NaN or ±0.
8092 if (!x.d || !y.s || y.d && !y.d[0]) return new Ctor(NaN);
8093
8094 // Return x if y is ±Infinity or x is ±0.
8095 if (!y.d || x.d && !x.d[0]) {
8096 return finalise(new Ctor(x), Ctor.precision, Ctor.rounding);
8097 }
8098
8099 // Prevent rounding of intermediate calculations.
8100 external = false;
8101
8102 if (Ctor.modulo == 9) {
8103
8104 // Euclidian division: q = sign(y) * floor(x / abs(y))
8105 // result = x - q * y where 0 <= result < abs(y)
8106 q = divide(x, y.abs(), 0, 3, 1);
8107 q.s *= y.s;
8108 } else {
8109 q = divide(x, y, 0, Ctor.modulo, 1);
8110 }
8111
8112 q = q.times(y);
8113
8114 external = true;
8115
8116 return x.minus(q);
8117 };
8118
8119
8120 /*
8121 * Return a new Decimal whose value is the natural exponential of the value of this Decimal,
8122 * i.e. the base e raised to the power the value of this Decimal, rounded to `precision`
8123 * significant digits using rounding mode `rounding`.
8124 *
8125 */
8126 P.naturalExponential = P.exp = function () {
8127 return naturalExponential(this);
8128 };
8129
8130
8131 /*
8132 * Return a new Decimal whose value is the natural logarithm of the value of this Decimal,
8133 * rounded to `precision` significant digits using rounding mode `rounding`.
8134 *
8135 */
8136 P.naturalLogarithm = P.ln = function () {
8137 return naturalLogarithm(this);
8138 };
8139
8140
8141 /*
8142 * Return a new Decimal whose value is the value of this Decimal negated, i.e. as if multiplied by
8143 * -1.
8144 *
8145 */
8146 P.negated = P.neg = function () {
8147 var x = new this.constructor(this);
8148 x.s = -x.s;
8149 return finalise(x);
8150 };
8151
8152
8153 /*
8154 * n + 0 = n
8155 * n + N = N
8156 * n + I = I
8157 * 0 + n = n
8158 * 0 + 0 = 0
8159 * 0 + N = N
8160 * 0 + I = I
8161 * N + n = N
8162 * N + 0 = N
8163 * N + N = N
8164 * N + I = N
8165 * I + n = I
8166 * I + 0 = I
8167 * I + N = N
8168 * I + I = I
8169 *
8170 * Return a new Decimal whose value is the value of this Decimal plus `y`, rounded to `precision`
8171 * significant digits using rounding mode `rounding`.
8172 *
8173 */
8174 P.plus = P.add = function (y) {
8175 var carry, d, e, i, k, len, pr, rm, xd, yd,
8176 x = this,
8177 Ctor = x.constructor;
8178
8179 y = new Ctor(y);
8180
8181 // If either is not finite...
8182 if (!x.d || !y.d) {
8183
8184 // Return NaN if either is NaN.
8185 if (!x.s || !y.s) y = new Ctor(NaN);
8186
8187 // Return x if y is finite and x is ±Infinity.
8188 // Return x if both are ±Infinity with the same sign.
8189 // Return NaN if both are ±Infinity with different signs.
8190 // Return y if x is finite and y is ±Infinity.
8191 else if (!x.d) y = new Ctor(y.d || x.s === y.s ? x : NaN);
8192
8193 return y;
8194 }
8195
8196 // If signs differ...
8197 if (x.s != y.s) {
8198 y.s = -y.s;
8199 return x.minus(y);
8200 }
8201
8202 xd = x.d;
8203 yd = y.d;
8204 pr = Ctor.precision;
8205 rm = Ctor.rounding;
8206
8207 // If either is zero...
8208 if (!xd[0] || !yd[0]) {
8209
8210 // Return x if y is zero.
8211 // Return y if y is non-zero.
8212 if (!yd[0]) y = new Ctor(x);
8213
8214 return external ? finalise(y, pr, rm) : y;
8215 }
8216
8217 // x and y are finite, non-zero numbers with the same sign.
8218
8219 // Calculate base 1e7 exponents.
8220 k = mathfloor(x.e / LOG_BASE);
8221 e = mathfloor(y.e / LOG_BASE);
8222
8223 xd = xd.slice();
8224 i = k - e;
8225
8226 // If base 1e7 exponents differ...
8227 if (i) {
8228
8229 if (i < 0) {
8230 d = xd;
8231 i = -i;
8232 len = yd.length;
8233 } else {
8234 d = yd;
8235 e = k;
8236 len = xd.length;
8237 }
8238
8239 // Limit number of zeros prepended to max(ceil(pr / LOG_BASE), len) + 1.
8240 k = Math.ceil(pr / LOG_BASE);
8241 len = k > len ? k + 1 : len + 1;
8242
8243 if (i > len) {
8244 i = len;
8245 d.length = 1;
8246 }
8247
8248 // Prepend zeros to equalise exponents. Note: Faster to use reverse then do unshifts.
8249 d.reverse();
8250 for (; i--;) d.push(0);
8251 d.reverse();
8252 }
8253
8254 len = xd.length;
8255 i = yd.length;
8256
8257 // If yd is longer than xd, swap xd and yd so xd points to the longer array.
8258 if (len - i < 0) {
8259 i = len;
8260 d = yd;
8261 yd = xd;
8262 xd = d;
8263 }
8264
8265 // Only start adding at yd.length - 1 as the further digits of xd can be left as they are.
8266 for (carry = 0; i;) {
8267 carry = (xd[--i] = xd[i] + yd[i] + carry) / BASE | 0;
8268 xd[i] %= BASE;
8269 }
8270
8271 if (carry) {
8272 xd.unshift(carry);
8273 ++e;
8274 }
8275
8276 // Remove trailing zeros.
8277 // No need to check for zero, as +x + +y != 0 && -x + -y != 0
8278 for (len = xd.length; xd[--len] == 0;) xd.pop();
8279
8280 y.d = xd;
8281 y.e = getBase10Exponent(xd, e);
8282
8283 return external ? finalise(y, pr, rm) : y;
8284 };
8285
8286
8287 /*
8288 * Return the number of significant digits of the value of this Decimal.
8289 *
8290 * [z] {boolean|number} Whether to count integer-part trailing zeros: true, false, 1 or 0.
8291 *
8292 */
8293 P.precision = P.sd = function (z) {
8294 var k,
8295 x = this;
8296
8297 if (z !== void 0 && z !== !!z && z !== 1 && z !== 0) throw Error(invalidArgument + z);
8298
8299 if (x.d) {
8300 k = getPrecision(x.d);
8301 if (z && x.e + 1 > k) k = x.e + 1;
8302 } else {
8303 k = NaN;
8304 }
8305
8306 return k;
8307 };
8308
8309
8310 /*
8311 * Return a new Decimal whose value is the value of this Decimal rounded to a whole number using
8312 * rounding mode `rounding`.
8313 *
8314 */
8315 P.round = function () {
8316 var x = this,
8317 Ctor = x.constructor;
8318
8319 return finalise(new Ctor(x), x.e + 1, Ctor.rounding);
8320 };
8321
8322
8323 /*
8324 * Return a new Decimal whose value is the sine of the value in radians of this Decimal.
8325 *
8326 * Domain: [-Infinity, Infinity]
8327 * Range: [-1, 1]
8328 *
8329 * sin(x) = x - x^3/3! + x^5/5! - ...
8330 *
8331 * sin(0) = 0
8332 * sin(-0) = -0
8333 * sin(Infinity) = NaN
8334 * sin(-Infinity) = NaN
8335 * sin(NaN) = NaN
8336 *
8337 */
8338 P.sine = P.sin = function () {
8339 var pr, rm,
8340 x = this,
8341 Ctor = x.constructor;
8342
8343 if (!x.isFinite()) return new Ctor(NaN);
8344 if (x.isZero()) return new Ctor(x);
8345
8346 pr = Ctor.precision;
8347 rm = Ctor.rounding;
8348 Ctor.precision = pr + Math.max(x.e, x.sd()) + LOG_BASE;
8349 Ctor.rounding = 1;
8350
8351 x = sine(Ctor, toLessThanHalfPi(Ctor, x));
8352
8353 Ctor.precision = pr;
8354 Ctor.rounding = rm;
8355
8356 return finalise(quadrant > 2 ? x.neg() : x, pr, rm, true);
8357 };
8358
8359
8360 /*
8361 * Return a new Decimal whose value is the square root of this Decimal, rounded to `precision`
8362 * significant digits using rounding mode `rounding`.
8363 *
8364 * sqrt(-n) = N
8365 * sqrt(N) = N
8366 * sqrt(-I) = N
8367 * sqrt(I) = I
8368 * sqrt(0) = 0
8369 * sqrt(-0) = -0
8370 *
8371 */
8372 P.squareRoot = P.sqrt = function () {
8373 var m, n, sd, r, rep, t,
8374 x = this,
8375 d = x.d,
8376 e = x.e,
8377 s = x.s,
8378 Ctor = x.constructor;
8379
8380 // Negative/NaN/Infinity/zero?
8381 if (s !== 1 || !d || !d[0]) {
8382 return new Ctor(!s || s < 0 && (!d || d[0]) ? NaN : d ? x : 1 / 0);
8383 }
8384
8385 external = false;
8386
8387 // Initial estimate.
8388 s = Math.sqrt(+x);
8389
8390 // Math.sqrt underflow/overflow?
8391 // Pass x to Math.sqrt as integer, then adjust the exponent of the result.
8392 if (s == 0 || s == 1 / 0) {
8393 n = digitsToString(d);
8394
8395 if ((n.length + e) % 2 == 0) n += '0';
8396 s = Math.sqrt(n);
8397 e = mathfloor((e + 1) / 2) - (e < 0 || e % 2);
8398
8399 if (s == 1 / 0) {
8400 n = '1e' + e;
8401 } else {
8402 n = s.toExponential();
8403 n = n.slice(0, n.indexOf('e') + 1) + e;
8404 }
8405
8406 r = new Ctor(n);
8407 } else {
8408 r = new Ctor(s.toString());
8409 }
8410
8411 sd = (e = Ctor.precision) + 3;
8412
8413 // Newton-Raphson iteration.
8414 for (;;) {
8415 t = r;
8416 r = t.plus(divide(x, t, sd + 2, 1)).times(0.5);
8417
8418 // TODO? Replace with for-loop and checkRoundingDigits.
8419 if (digitsToString(t.d).slice(0, sd) === (n = digitsToString(r.d)).slice(0, sd)) {
8420 n = n.slice(sd - 3, sd + 1);
8421
8422 // The 4th rounding digit may be in error by -1 so if the 4 rounding digits are 9999 or
8423 // 4999, i.e. approaching a rounding boundary, continue the iteration.
8424 if (n == '9999' || !rep && n == '4999') {
8425
8426 // On the first iteration only, check to see if rounding up gives the exact result as the
8427 // nines may infinitely repeat.
8428 if (!rep) {
8429 finalise(t, e + 1, 0);
8430
8431 if (t.times(t).eq(x)) {
8432 r = t;
8433 break;
8434 }
8435 }
8436
8437 sd += 4;
8438 rep = 1;
8439 } else {
8440
8441 // If the rounding digits are null, 0{0,4} or 50{0,3}, check for an exact result.
8442 // If not, then there are further digits and m will be truthy.
8443 if (!+n || !+n.slice(1) && n.charAt(0) == '5') {
8444
8445 // Truncate to the first rounding digit.
8446 finalise(r, e + 1, 1);
8447 m = !r.times(r).eq(x);
8448 }
8449
8450 break;
8451 }
8452 }
8453 }
8454
8455 external = true;
8456
8457 return finalise(r, e, Ctor.rounding, m);
8458 };
8459
8460
8461 /*
8462 * Return a new Decimal whose value is the tangent of the value in radians of this Decimal.
8463 *
8464 * Domain: [-Infinity, Infinity]
8465 * Range: [-Infinity, Infinity]
8466 *
8467 * tan(0) = 0
8468 * tan(-0) = -0
8469 * tan(Infinity) = NaN
8470 * tan(-Infinity) = NaN
8471 * tan(NaN) = NaN
8472 *
8473 */
8474 P.tangent = P.tan = function () {
8475 var pr, rm,
8476 x = this,
8477 Ctor = x.constructor;
8478
8479 if (!x.isFinite()) return new Ctor(NaN);
8480 if (x.isZero()) return new Ctor(x);
8481
8482 pr = Ctor.precision;
8483 rm = Ctor.rounding;
8484 Ctor.precision = pr + 10;
8485 Ctor.rounding = 1;
8486
8487 x = x.sin();
8488 x.s = 1;
8489 x = divide(x, new Ctor(1).minus(x.times(x)).sqrt(), pr + 10, 0);
8490
8491 Ctor.precision = pr;
8492 Ctor.rounding = rm;
8493
8494 return finalise(quadrant == 2 || quadrant == 4 ? x.neg() : x, pr, rm, true);
8495 };
8496
8497
8498 /*
8499 * n * 0 = 0
8500 * n * N = N
8501 * n * I = I
8502 * 0 * n = 0
8503 * 0 * 0 = 0
8504 * 0 * N = N
8505 * 0 * I = N
8506 * N * n = N
8507 * N * 0 = N
8508 * N * N = N
8509 * N * I = N
8510 * I * n = I
8511 * I * 0 = N
8512 * I * N = N
8513 * I * I = I
8514 *
8515 * Return a new Decimal whose value is this Decimal times `y`, rounded to `precision` significant
8516 * digits using rounding mode `rounding`.
8517 *
8518 */
8519 P.times = P.mul = function (y) {
8520 var carry, e, i, k, r, rL, t, xdL, ydL,
8521 x = this,
8522 Ctor = x.constructor,
8523 xd = x.d,
8524 yd = (y = new Ctor(y)).d;
8525
8526 y.s *= x.s;
8527
8528 // If either is NaN, ±Infinity or ±0...
8529 if (!xd || !xd[0] || !yd || !yd[0]) {
8530
8531 return new Ctor(!y.s || xd && !xd[0] && !yd || yd && !yd[0] && !xd
8532
8533 // Return NaN if either is NaN.
8534 // Return NaN if x is ±0 and y is ±Infinity, or y is ±0 and x is ±Infinity.
8535 ? NaN
8536
8537 // Return ±Infinity if either is ±Infinity.
8538 // Return ±0 if either is ±0.
8539 : !xd || !yd ? y.s / 0 : y.s * 0);
8540 }
8541
8542 e = mathfloor(x.e / LOG_BASE) + mathfloor(y.e / LOG_BASE);
8543 xdL = xd.length;
8544 ydL = yd.length;
8545
8546 // Ensure xd points to the longer array.
8547 if (xdL < ydL) {
8548 r = xd;
8549 xd = yd;
8550 yd = r;
8551 rL = xdL;
8552 xdL = ydL;
8553 ydL = rL;
8554 }
8555
8556 // Initialise the result array with zeros.
8557 r = [];
8558 rL = xdL + ydL;
8559 for (i = rL; i--;) r.push(0);
8560
8561 // Multiply!
8562 for (i = ydL; --i >= 0;) {
8563 carry = 0;
8564 for (k = xdL + i; k > i;) {
8565 t = r[k] + yd[i] * xd[k - i - 1] + carry;
8566 r[k--] = t % BASE | 0;
8567 carry = t / BASE | 0;
8568 }
8569
8570 r[k] = (r[k] + carry) % BASE | 0;
8571 }
8572
8573 // Remove trailing zeros.
8574 for (; !r[--rL];) r.pop();
8575
8576 if (carry) ++e;
8577 else r.shift();
8578
8579 y.d = r;
8580 y.e = getBase10Exponent(r, e);
8581
8582 return external ? finalise(y, Ctor.precision, Ctor.rounding) : y;
8583 };
8584
8585
8586 /*
8587 * Return a string representing the value of this Decimal in base 2, round to `sd` significant
8588 * digits using rounding mode `rm`.
8589 *
8590 * If the optional `sd` argument is present then return binary exponential notation.
8591 *
8592 * [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive.
8593 * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
8594 *
8595 */
8596 P.toBinary = function (sd, rm) {
8597 return toStringBinary(this, 2, sd, rm);
8598 };
8599
8600
8601 /*
8602 * Return a new Decimal whose value is the value of this Decimal rounded to a maximum of `dp`
8603 * decimal places using rounding mode `rm` or `rounding` if `rm` is omitted.
8604 *
8605 * If `dp` is omitted, return a new Decimal whose value is the value of this Decimal.
8606 *
8607 * [dp] {number} Decimal places. Integer, 0 to MAX_DIGITS inclusive.
8608 * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
8609 *
8610 */
8611 P.toDecimalPlaces = P.toDP = function (dp, rm) {
8612 var x = this,
8613 Ctor = x.constructor;
8614
8615 x = new Ctor(x);
8616 if (dp === void 0) return x;
8617
8618 checkInt32(dp, 0, MAX_DIGITS);
8619
8620 if (rm === void 0) rm = Ctor.rounding;
8621 else checkInt32(rm, 0, 8);
8622
8623 return finalise(x, dp + x.e + 1, rm);
8624 };
8625
8626
8627 /*
8628 * Return a string representing the value of this Decimal in exponential notation rounded to
8629 * `dp` fixed decimal places using rounding mode `rounding`.
8630 *
8631 * [dp] {number} Decimal places. Integer, 0 to MAX_DIGITS inclusive.
8632 * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
8633 *
8634 */
8635 P.toExponential = function (dp, rm) {
8636 var str,
8637 x = this,
8638 Ctor = x.constructor;
8639
8640 if (dp === void 0) {
8641 str = finiteToString(x, true);
8642 } else {
8643 checkInt32(dp, 0, MAX_DIGITS);
8644
8645 if (rm === void 0) rm = Ctor.rounding;
8646 else checkInt32(rm, 0, 8);
8647
8648 x = finalise(new Ctor(x), dp + 1, rm);
8649 str = finiteToString(x, true, dp + 1);
8650 }
8651
8652 return x.isNeg() && !x.isZero() ? '-' + str : str;
8653 };
8654
8655
8656 /*
8657 * Return a string representing the value of this Decimal in normal (fixed-point) notation to
8658 * `dp` fixed decimal places and rounded using rounding mode `rm` or `rounding` if `rm` is
8659 * omitted.
8660 *
8661 * As with JavaScript numbers, (-0).toFixed(0) is '0', but e.g. (-0.00001).toFixed(0) is '-0'.
8662 *
8663 * [dp] {number} Decimal places. Integer, 0 to MAX_DIGITS inclusive.
8664 * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
8665 *
8666 * (-0).toFixed(0) is '0', but (-0.1).toFixed(0) is '-0'.
8667 * (-0).toFixed(1) is '0.0', but (-0.01).toFixed(1) is '-0.0'.
8668 * (-0).toFixed(3) is '0.000'.
8669 * (-0.5).toFixed(0) is '-0'.
8670 *
8671 */
8672 P.toFixed = function (dp, rm) {
8673 var str, y,
8674 x = this,
8675 Ctor = x.constructor;
8676
8677 if (dp === void 0) {
8678 str = finiteToString(x);
8679 } else {
8680 checkInt32(dp, 0, MAX_DIGITS);
8681
8682 if (rm === void 0) rm = Ctor.rounding;
8683 else checkInt32(rm, 0, 8);
8684
8685 y = finalise(new Ctor(x), dp + x.e + 1, rm);
8686 str = finiteToString(y, false, dp + y.e + 1);
8687 }
8688
8689 // To determine whether to add the minus sign look at the value before it was rounded,
8690 // i.e. look at `x` rather than `y`.
8691 return x.isNeg() && !x.isZero() ? '-' + str : str;
8692 };
8693
8694
8695 /*
8696 * Return an array representing the value of this Decimal as a simple fraction with an integer
8697 * numerator and an integer denominator.
8698 *
8699 * The denominator will be a positive non-zero value less than or equal to the specified maximum
8700 * denominator. If a maximum denominator is not specified, the denominator will be the lowest
8701 * value necessary to represent the number exactly.
8702 *
8703 * [maxD] {number|string|Decimal} Maximum denominator. Integer >= 1 and < Infinity.
8704 *
8705 */
8706 P.toFraction = function (maxD) {
8707 var d, d0, d1, d2, e, k, n, n0, n1, pr, q, r,
8708 x = this,
8709 xd = x.d,
8710 Ctor = x.constructor;
8711
8712 if (!xd) return new Ctor(x);
8713
8714 n1 = d0 = new Ctor(1);
8715 d1 = n0 = new Ctor(0);
8716
8717 d = new Ctor(d1);
8718 e = d.e = getPrecision(xd) - x.e - 1;
8719 k = e % LOG_BASE;
8720 d.d[0] = mathpow(10, k < 0 ? LOG_BASE + k : k);
8721
8722 if (maxD == null) {
8723
8724 // d is 10**e, the minimum max-denominator needed.
8725 maxD = e > 0 ? d : n1;
8726 } else {
8727 n = new Ctor(maxD);
8728 if (!n.isInt() || n.lt(n1)) throw Error(invalidArgument + n);
8729 maxD = n.gt(d) ? (e > 0 ? d : n1) : n;
8730 }
8731
8732 external = false;
8733 n = new Ctor(digitsToString(xd));
8734 pr = Ctor.precision;
8735 Ctor.precision = e = xd.length * LOG_BASE * 2;
8736
8737 for (;;) {
8738 q = divide(n, d, 0, 1, 1);
8739 d2 = d0.plus(q.times(d1));
8740 if (d2.cmp(maxD) == 1) break;
8741 d0 = d1;
8742 d1 = d2;
8743 d2 = n1;
8744 n1 = n0.plus(q.times(d2));
8745 n0 = d2;
8746 d2 = d;
8747 d = n.minus(q.times(d2));
8748 n = d2;
8749 }
8750
8751 d2 = divide(maxD.minus(d0), d1, 0, 1, 1);
8752 n0 = n0.plus(d2.times(n1));
8753 d0 = d0.plus(d2.times(d1));
8754 n0.s = n1.s = x.s;
8755
8756 // Determine which fraction is closer to x, n0/d0 or n1/d1?
8757 r = divide(n1, d1, e, 1).minus(x).abs().cmp(divide(n0, d0, e, 1).minus(x).abs()) < 1
8758 ? [n1, d1] : [n0, d0];
8759
8760 Ctor.precision = pr;
8761 external = true;
8762
8763 return r;
8764 };
8765
8766
8767 /*
8768 * Return a string representing the value of this Decimal in base 16, round to `sd` significant
8769 * digits using rounding mode `rm`.
8770 *
8771 * If the optional `sd` argument is present then return binary exponential notation.
8772 *
8773 * [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive.
8774 * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
8775 *
8776 */
8777 P.toHexadecimal = P.toHex = function (sd, rm) {
8778 return toStringBinary(this, 16, sd, rm);
8779 };
8780
8781
8782 /*
8783 * Returns a new Decimal whose value is the nearest multiple of `y` in the direction of rounding
8784 * mode `rm`, or `Decimal.rounding` if `rm` is omitted, to the value of this Decimal.
8785 *
8786 * The return value will always have the same sign as this Decimal, unless either this Decimal
8787 * or `y` is NaN, in which case the return value will be also be NaN.
8788 *
8789 * The return value is not affected by the value of `precision`.
8790 *
8791 * y {number|string|Decimal} The magnitude to round to a multiple of.
8792 * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
8793 *
8794 * 'toNearest() rounding mode not an integer: {rm}'
8795 * 'toNearest() rounding mode out of range: {rm}'
8796 *
8797 */
8798 P.toNearest = function (y, rm) {
8799 var x = this,
8800 Ctor = x.constructor;
8801
8802 x = new Ctor(x);
8803
8804 if (y == null) {
8805
8806 // If x is not finite, return x.
8807 if (!x.d) return x;
8808
8809 y = new Ctor(1);
8810 rm = Ctor.rounding;
8811 } else {
8812 y = new Ctor(y);
8813 if (rm === void 0) {
8814 rm = Ctor.rounding;
8815 } else {
8816 checkInt32(rm, 0, 8);
8817 }
8818
8819 // If x is not finite, return x if y is not NaN, else NaN.
8820 if (!x.d) return y.s ? x : y;
8821
8822 // If y is not finite, return Infinity with the sign of x if y is Infinity, else NaN.
8823 if (!y.d) {
8824 if (y.s) y.s = x.s;
8825 return y;
8826 }
8827 }
8828
8829 // If y is not zero, calculate the nearest multiple of y to x.
8830 if (y.d[0]) {
8831 external = false;
8832 x = divide(x, y, 0, rm, 1).times(y);
8833 external = true;
8834 finalise(x);
8835
8836 // If y is zero, return zero with the sign of x.
8837 } else {
8838 y.s = x.s;
8839 x = y;
8840 }
8841
8842 return x;
8843 };
8844
8845
8846 /*
8847 * Return the value of this Decimal converted to a number primitive.
8848 * Zero keeps its sign.
8849 *
8850 */
8851 P.toNumber = function () {
8852 return +this;
8853 };
8854
8855
8856 /*
8857 * Return a string representing the value of this Decimal in base 8, round to `sd` significant
8858 * digits using rounding mode `rm`.
8859 *
8860 * If the optional `sd` argument is present then return binary exponential notation.
8861 *
8862 * [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive.
8863 * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
8864 *
8865 */
8866 P.toOctal = function (sd, rm) {
8867 return toStringBinary(this, 8, sd, rm);
8868 };
8869
8870
8871 /*
8872 * Return a new Decimal whose value is the value of this Decimal raised to the power `y`, rounded
8873 * to `precision` significant digits using rounding mode `rounding`.
8874 *
8875 * ECMAScript compliant.
8876 *
8877 * pow(x, NaN) = NaN
8878 * pow(x, ±0) = 1
8879
8880 * pow(NaN, non-zero) = NaN
8881 * pow(abs(x) > 1, +Infinity) = +Infinity
8882 * pow(abs(x) > 1, -Infinity) = +0
8883 * pow(abs(x) == 1, ±Infinity) = NaN
8884 * pow(abs(x) < 1, +Infinity) = +0
8885 * pow(abs(x) < 1, -Infinity) = +Infinity
8886 * pow(+Infinity, y > 0) = +Infinity
8887 * pow(+Infinity, y < 0) = +0
8888 * pow(-Infinity, odd integer > 0) = -Infinity
8889 * pow(-Infinity, even integer > 0) = +Infinity
8890 * pow(-Infinity, odd integer < 0) = -0
8891 * pow(-Infinity, even integer < 0) = +0
8892 * pow(+0, y > 0) = +0
8893 * pow(+0, y < 0) = +Infinity
8894 * pow(-0, odd integer > 0) = -0
8895 * pow(-0, even integer > 0) = +0
8896 * pow(-0, odd integer < 0) = -Infinity
8897 * pow(-0, even integer < 0) = +Infinity
8898 * pow(finite x < 0, finite non-integer) = NaN
8899 *
8900 * For non-integer or very large exponents pow(x, y) is calculated using
8901 *
8902 * x^y = exp(y*ln(x))
8903 *
8904 * Assuming the first 15 rounding digits are each equally likely to be any digit 0-9, the
8905 * probability of an incorrectly rounded result
8906 * P([49]9{14} | [50]0{14}) = 2 * 0.2 * 10^-14 = 4e-15 = 1/2.5e+14
8907 * i.e. 1 in 250,000,000,000,000
8908 *
8909 * If a result is incorrectly rounded the maximum error will be 1 ulp (unit in last place).
8910 *
8911 * y {number|string|Decimal} The power to which to raise this Decimal.
8912 *
8913 */
8914 P.toPower = P.pow = function (y) {
8915 var e, k, pr, r, rm, s,
8916 x = this,
8917 Ctor = x.constructor,
8918 yn = +(y = new Ctor(y));
8919
8920 // Either ±Infinity, NaN or ±0?
8921 if (!x.d || !y.d || !x.d[0] || !y.d[0]) return new Ctor(mathpow(+x, yn));
8922
8923 x = new Ctor(x);
8924
8925 if (x.eq(1)) return x;
8926
8927 pr = Ctor.precision;
8928 rm = Ctor.rounding;
8929
8930 if (y.eq(1)) return finalise(x, pr, rm);
8931
8932 // y exponent
8933 e = mathfloor(y.e / LOG_BASE);
8934
8935 // If y is a small integer use the 'exponentiation by squaring' algorithm.
8936 if (e >= y.d.length - 1 && (k = yn < 0 ? -yn : yn) <= MAX_SAFE_INTEGER) {
8937 r = intPow(Ctor, x, k, pr);
8938 return y.s < 0 ? new Ctor(1).div(r) : finalise(r, pr, rm);
8939 }
8940
8941 s = x.s;
8942
8943 // if x is negative
8944 if (s < 0) {
8945
8946 // if y is not an integer
8947 if (e < y.d.length - 1) return new Ctor(NaN);
8948
8949 // Result is positive if x is negative and the last digit of integer y is even.
8950 if ((y.d[e] & 1) == 0) s = 1;
8951
8952 // if x.eq(-1)
8953 if (x.e == 0 && x.d[0] == 1 && x.d.length == 1) {
8954 x.s = s;
8955 return x;
8956 }
8957 }
8958
8959 // Estimate result exponent.
8960 // x^y = 10^e, where e = y * log10(x)
8961 // log10(x) = log10(x_significand) + x_exponent
8962 // log10(x_significand) = ln(x_significand) / ln(10)
8963 k = mathpow(+x, yn);
8964 e = k == 0 || !isFinite(k)
8965 ? mathfloor(yn * (Math.log('0.' + digitsToString(x.d)) / Math.LN10 + x.e + 1))
8966 : new Ctor(k + '').e;
8967
8968 // Exponent estimate may be incorrect e.g. x: 0.999999999999999999, y: 2.29, e: 0, r.e: -1.
8969
8970 // Overflow/underflow?
8971 if (e > Ctor.maxE + 1 || e < Ctor.minE - 1) return new Ctor(e > 0 ? s / 0 : 0);
8972
8973 external = false;
8974 Ctor.rounding = x.s = 1;
8975
8976 // Estimate the extra guard digits needed to ensure five correct rounding digits from
8977 // naturalLogarithm(x). Example of failure without these extra digits (precision: 10):
8978 // new Decimal(2.32456).pow('2087987436534566.46411')
8979 // should be 1.162377823e+764914905173815, but is 1.162355823e+764914905173815
8980 k = Math.min(12, (e + '').length);
8981
8982 // r = x^y = exp(y*ln(x))
8983 r = naturalExponential(y.times(naturalLogarithm(x, pr + k)), pr);
8984
8985 // r may be Infinity, e.g. (0.9999999999999999).pow(-1e+40)
8986 if (r.d) {
8987
8988 // Truncate to the required precision plus five rounding digits.
8989 r = finalise(r, pr + 5, 1);
8990
8991 // If the rounding digits are [49]9999 or [50]0000 increase the precision by 10 and recalculate
8992 // the result.
8993 if (checkRoundingDigits(r.d, pr, rm)) {
8994 e = pr + 10;
8995
8996 // Truncate to the increased precision plus five rounding digits.
8997 r = finalise(naturalExponential(y.times(naturalLogarithm(x, e + k)), e), e + 5, 1);
8998
8999 // Check for 14 nines from the 2nd rounding digit (the first rounding digit may be 4 or 9).
9000 if (+digitsToString(r.d).slice(pr + 1, pr + 15) + 1 == 1e14) {
9001 r = finalise(r, pr + 1, 0);
9002 }
9003 }
9004 }
9005
9006 r.s = s;
9007 external = true;
9008 Ctor.rounding = rm;
9009
9010 return finalise(r, pr, rm);
9011 };
9012
9013
9014 /*
9015 * Return a string representing the value of this Decimal rounded to `sd` significant digits
9016 * using rounding mode `rounding`.
9017 *
9018 * Return exponential notation if `sd` is less than the number of digits necessary to represent
9019 * the integer part of the value in normal notation.
9020 *
9021 * [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive.
9022 * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
9023 *
9024 */
9025 P.toPrecision = function (sd, rm) {
9026 var str,
9027 x = this,
9028 Ctor = x.constructor;
9029
9030 if (sd === void 0) {
9031 str = finiteToString(x, x.e <= Ctor.toExpNeg || x.e >= Ctor.toExpPos);
9032 } else {
9033 checkInt32(sd, 1, MAX_DIGITS);
9034
9035 if (rm === void 0) rm = Ctor.rounding;
9036 else checkInt32(rm, 0, 8);
9037
9038 x = finalise(new Ctor(x), sd, rm);
9039 str = finiteToString(x, sd <= x.e || x.e <= Ctor.toExpNeg, sd);
9040 }
9041
9042 return x.isNeg() && !x.isZero() ? '-' + str : str;
9043 };
9044
9045
9046 /*
9047 * Return a new Decimal whose value is the value of this Decimal rounded to a maximum of `sd`
9048 * significant digits using rounding mode `rm`, or to `precision` and `rounding` respectively if
9049 * omitted.
9050 *
9051 * [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive.
9052 * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
9053 *
9054 * 'toSD() digits out of range: {sd}'
9055 * 'toSD() digits not an integer: {sd}'
9056 * 'toSD() rounding mode not an integer: {rm}'
9057 * 'toSD() rounding mode out of range: {rm}'
9058 *
9059 */
9060 P.toSignificantDigits = P.toSD = function (sd, rm) {
9061 var x = this,
9062 Ctor = x.constructor;
9063
9064 if (sd === void 0) {
9065 sd = Ctor.precision;
9066 rm = Ctor.rounding;
9067 } else {
9068 checkInt32(sd, 1, MAX_DIGITS);
9069
9070 if (rm === void 0) rm = Ctor.rounding;
9071 else checkInt32(rm, 0, 8);
9072 }
9073
9074 return finalise(new Ctor(x), sd, rm);
9075 };
9076
9077
9078 /*
9079 * Return a string representing the value of this Decimal.
9080 *
9081 * Return exponential notation if this Decimal has a positive exponent equal to or greater than
9082 * `toExpPos`, or a negative exponent equal to or less than `toExpNeg`.
9083 *
9084 */
9085 P.toString = function () {
9086 var x = this,
9087 Ctor = x.constructor,
9088 str = finiteToString(x, x.e <= Ctor.toExpNeg || x.e >= Ctor.toExpPos);
9089
9090 return x.isNeg() && !x.isZero() ? '-' + str : str;
9091 };
9092
9093
9094 /*
9095 * Return a new Decimal whose value is the value of this Decimal truncated to a whole number.
9096 *
9097 */
9098 P.truncated = P.trunc = function () {
9099 return finalise(new this.constructor(this), this.e + 1, 1);
9100 };
9101
9102
9103 /*
9104 * Return a string representing the value of this Decimal.
9105 * Unlike `toString`, negative zero will include the minus sign.
9106 *
9107 */
9108 P.valueOf = P.toJSON = function () {
9109 var x = this,
9110 Ctor = x.constructor,
9111 str = finiteToString(x, x.e <= Ctor.toExpNeg || x.e >= Ctor.toExpPos);
9112
9113 return x.isNeg() ? '-' + str : str;
9114 };
9115
9116
9117 /*
9118 // Add aliases to match BigDecimal method names.
9119 // P.add = P.plus;
9120 P.subtract = P.minus;
9121 P.multiply = P.times;
9122 P.divide = P.div;
9123 P.remainder = P.mod;
9124 P.compareTo = P.cmp;
9125 P.negate = P.neg;
9126 */
9127
9128
9129 // Helper functions for Decimal.prototype (P) and/or Decimal methods, and their callers.
9130
9131
9132 /*
9133 * digitsToString P.cubeRoot, P.logarithm, P.squareRoot, P.toFraction, P.toPower,
9134 * finiteToString, naturalExponential, naturalLogarithm
9135 * checkInt32 P.toDecimalPlaces, P.toExponential, P.toFixed, P.toNearest,
9136 * P.toPrecision, P.toSignificantDigits, toStringBinary, random
9137 * checkRoundingDigits P.logarithm, P.toPower, naturalExponential, naturalLogarithm
9138 * convertBase toStringBinary, parseOther
9139 * cos P.cos
9140 * divide P.atanh, P.cubeRoot, P.dividedBy, P.dividedToIntegerBy,
9141 * P.logarithm, P.modulo, P.squareRoot, P.tan, P.tanh, P.toFraction,
9142 * P.toNearest, toStringBinary, naturalExponential, naturalLogarithm,
9143 * taylorSeries, atan2, parseOther
9144 * finalise P.absoluteValue, P.atan, P.atanh, P.ceil, P.cos, P.cosh,
9145 * P.cubeRoot, P.dividedToIntegerBy, P.floor, P.logarithm, P.minus,
9146 * P.modulo, P.negated, P.plus, P.round, P.sin, P.sinh, P.squareRoot,
9147 * P.tan, P.times, P.toDecimalPlaces, P.toExponential, P.toFixed,
9148 * P.toNearest, P.toPower, P.toPrecision, P.toSignificantDigits,
9149 * P.truncated, divide, getLn10, getPi, naturalExponential,
9150 * naturalLogarithm, ceil, floor, round, trunc
9151 * finiteToString P.toExponential, P.toFixed, P.toPrecision, P.toString, P.valueOf,
9152 * toStringBinary
9153 * getBase10Exponent P.minus, P.plus, P.times, parseOther
9154 * getLn10 P.logarithm, naturalLogarithm
9155 * getPi P.acos, P.asin, P.atan, toLessThanHalfPi, atan2
9156 * getPrecision P.precision, P.toFraction
9157 * getZeroString digitsToString, finiteToString
9158 * intPow P.toPower, parseOther
9159 * isOdd toLessThanHalfPi
9160 * maxOrMin max, min
9161 * naturalExponential P.naturalExponential, P.toPower
9162 * naturalLogarithm P.acosh, P.asinh, P.atanh, P.logarithm, P.naturalLogarithm,
9163 * P.toPower, naturalExponential
9164 * nonFiniteToString finiteToString, toStringBinary
9165 * parseDecimal Decimal
9166 * parseOther Decimal
9167 * sin P.sin
9168 * taylorSeries P.cosh, P.sinh, cos, sin
9169 * toLessThanHalfPi P.cos, P.sin
9170 * toStringBinary P.toBinary, P.toHexadecimal, P.toOctal
9171 * truncate intPow
9172 *
9173 * Throws: P.logarithm, P.precision, P.toFraction, checkInt32, getLn10, getPi,
9174 * naturalLogarithm, config, parseOther, random, Decimal
9175 */
9176
9177
9178 function digitsToString(d) {
9179 var i, k, ws,
9180 indexOfLastWord = d.length - 1,
9181 str = '',
9182 w = d[0];
9183
9184 if (indexOfLastWord > 0) {
9185 str += w;
9186 for (i = 1; i < indexOfLastWord; i++) {
9187 ws = d[i] + '';
9188 k = LOG_BASE - ws.length;
9189 if (k) str += getZeroString(k);
9190 str += ws;
9191 }
9192
9193 w = d[i];
9194 ws = w + '';
9195 k = LOG_BASE - ws.length;
9196 if (k) str += getZeroString(k);
9197 } else if (w === 0) {
9198 return '0';
9199 }
9200
9201 // Remove trailing zeros of last w.
9202 for (; w % 10 === 0;) w /= 10;
9203
9204 return str + w;
9205 }
9206
9207
9208 function checkInt32(i, min, max) {
9209 if (i !== ~~i || i < min || i > max) {
9210 throw Error(invalidArgument + i);
9211 }
9212 }
9213
9214
9215 /*
9216 * Check 5 rounding digits if `repeating` is null, 4 otherwise.
9217 * `repeating == null` if caller is `log` or `pow`,
9218 * `repeating != null` if caller is `naturalLogarithm` or `naturalExponential`.
9219 */
9220 function checkRoundingDigits(d, i, rm, repeating) {
9221 var di, k, r, rd;
9222
9223 // Get the length of the first word of the array d.
9224 for (k = d[0]; k >= 10; k /= 10) --i;
9225
9226 // Is the rounding digit in the first word of d?
9227 if (--i < 0) {
9228 i += LOG_BASE;
9229 di = 0;
9230 } else {
9231 di = Math.ceil((i + 1) / LOG_BASE);
9232 i %= LOG_BASE;
9233 }
9234
9235 // i is the index (0 - 6) of the rounding digit.
9236 // E.g. if within the word 3487563 the first rounding digit is 5,
9237 // then i = 4, k = 1000, rd = 3487563 % 1000 = 563
9238 k = mathpow(10, LOG_BASE - i);
9239 rd = d[di] % k | 0;
9240
9241 if (repeating == null) {
9242 if (i < 3) {
9243 if (i == 0) rd = rd / 100 | 0;
9244 else if (i == 1) rd = rd / 10 | 0;
9245 r = rm < 4 && rd == 99999 || rm > 3 && rd == 49999 || rd == 50000 || rd == 0;
9246 } else {
9247 r = (rm < 4 && rd + 1 == k || rm > 3 && rd + 1 == k / 2) &&
9248 (d[di + 1] / k / 100 | 0) == mathpow(10, i - 2) - 1 ||
9249 (rd == k / 2 || rd == 0) && (d[di + 1] / k / 100 | 0) == 0;
9250 }
9251 } else {
9252 if (i < 4) {
9253 if (i == 0) rd = rd / 1000 | 0;
9254 else if (i == 1) rd = rd / 100 | 0;
9255 else if (i == 2) rd = rd / 10 | 0;
9256 r = (repeating || rm < 4) && rd == 9999 || !repeating && rm > 3 && rd == 4999;
9257 } else {
9258 r = ((repeating || rm < 4) && rd + 1 == k ||
9259 (!repeating && rm > 3) && rd + 1 == k / 2) &&
9260 (d[di + 1] / k / 1000 | 0) == mathpow(10, i - 3) - 1;
9261 }
9262 }
9263
9264 return r;
9265 }
9266
9267
9268 // Convert string of `baseIn` to an array of numbers of `baseOut`.
9269 // Eg. convertBase('255', 10, 16) returns [15, 15].
9270 // Eg. convertBase('ff', 16, 10) returns [2, 5, 5].
9271 function convertBase(str, baseIn, baseOut) {
9272 var j,
9273 arr = [0],
9274 arrL,
9275 i = 0,
9276 strL = str.length;
9277
9278 for (; i < strL;) {
9279 for (arrL = arr.length; arrL--;) arr[arrL] *= baseIn;
9280 arr[0] += NUMERALS.indexOf(str.charAt(i++));
9281 for (j = 0; j < arr.length; j++) {
9282 if (arr[j] > baseOut - 1) {
9283 if (arr[j + 1] === void 0) arr[j + 1] = 0;
9284 arr[j + 1] += arr[j] / baseOut | 0;
9285 arr[j] %= baseOut;
9286 }
9287 }
9288 }
9289
9290 return arr.reverse();
9291 }
9292
9293
9294 /*
9295 * cos(x) = 1 - x^2/2! + x^4/4! - ...
9296 * |x| < pi/2
9297 *
9298 */
9299 function cosine(Ctor, x) {
9300 var k, y,
9301 len = x.d.length;
9302
9303 // Argument reduction: cos(4x) = 8*(cos^4(x) - cos^2(x)) + 1
9304 // i.e. cos(x) = 8*(cos^4(x/4) - cos^2(x/4)) + 1
9305
9306 // Estimate the optimum number of times to use the argument reduction.
9307 if (len < 32) {
9308 k = Math.ceil(len / 3);
9309 y = (1 / tinyPow(4, k)).toString();
9310 } else {
9311 k = 16;
9312 y = '2.3283064365386962890625e-10';
9313 }
9314
9315 Ctor.precision += k;
9316
9317 x = taylorSeries(Ctor, 1, x.times(y), new Ctor(1));
9318
9319 // Reverse argument reduction
9320 for (var i = k; i--;) {
9321 var cos2x = x.times(x);
9322 x = cos2x.times(cos2x).minus(cos2x).times(8).plus(1);
9323 }
9324
9325 Ctor.precision -= k;
9326
9327 return x;
9328 }
9329
9330
9331 /*
9332 * Perform division in the specified base.
9333 */
9334 var divide = (function () {
9335
9336 // Assumes non-zero x and k, and hence non-zero result.
9337 function multiplyInteger(x, k, base) {
9338 var temp,
9339 carry = 0,
9340 i = x.length;
9341
9342 for (x = x.slice(); i--;) {
9343 temp = x[i] * k + carry;
9344 x[i] = temp % base | 0;
9345 carry = temp / base | 0;
9346 }
9347
9348 if (carry) x.unshift(carry);
9349
9350 return x;
9351 }
9352
9353 function compare(a, b, aL, bL) {
9354 var i, r;
9355
9356 if (aL != bL) {
9357 r = aL > bL ? 1 : -1;
9358 } else {
9359 for (i = r = 0; i < aL; i++) {
9360 if (a[i] != b[i]) {
9361 r = a[i] > b[i] ? 1 : -1;
9362 break;
9363 }
9364 }
9365 }
9366
9367 return r;
9368 }
9369
9370 function subtract(a, b, aL, base) {
9371 var i = 0;
9372
9373 // Subtract b from a.
9374 for (; aL--;) {
9375 a[aL] -= i;
9376 i = a[aL] < b[aL] ? 1 : 0;
9377 a[aL] = i * base + a[aL] - b[aL];
9378 }
9379
9380 // Remove leading zeros.
9381 for (; !a[0] && a.length > 1;) a.shift();
9382 }
9383
9384 return function (x, y, pr, rm, dp, base) {
9385 var cmp, e, i, k, logBase, more, prod, prodL, q, qd, rem, remL, rem0, sd, t, xi, xL, yd0,
9386 yL, yz,
9387 Ctor = x.constructor,
9388 sign = x.s == y.s ? 1 : -1,
9389 xd = x.d,
9390 yd = y.d;
9391
9392 // Either NaN, Infinity or 0?
9393 if (!xd || !xd[0] || !yd || !yd[0]) {
9394
9395 return new Ctor(// Return NaN if either NaN, or both Infinity or 0.
9396 !x.s || !y.s || (xd ? yd && xd[0] == yd[0] : !yd) ? NaN :
9397
9398 // Return ±0 if x is 0 or y is ±Infinity, or return ±Infinity as y is 0.
9399 xd && xd[0] == 0 || !yd ? sign * 0 : sign / 0);
9400 }
9401
9402 if (base) {
9403 logBase = 1;
9404 e = x.e - y.e;
9405 } else {
9406 base = BASE;
9407 logBase = LOG_BASE;
9408 e = mathfloor(x.e / logBase) - mathfloor(y.e / logBase);
9409 }
9410
9411 yL = yd.length;
9412 xL = xd.length;
9413 q = new Ctor(sign);
9414 qd = q.d = [];
9415
9416 // Result exponent may be one less than e.
9417 // The digit array of a Decimal from toStringBinary may have trailing zeros.
9418 for (i = 0; yd[i] == (xd[i] || 0); i++);
9419
9420 if (yd[i] > (xd[i] || 0)) e--;
9421
9422 if (pr == null) {
9423 sd = pr = Ctor.precision;
9424 rm = Ctor.rounding;
9425 } else if (dp) {
9426 sd = pr + (x.e - y.e) + 1;
9427 } else {
9428 sd = pr;
9429 }
9430
9431 if (sd < 0) {
9432 qd.push(1);
9433 more = true;
9434 } else {
9435
9436 // Convert precision in number of base 10 digits to base 1e7 digits.
9437 sd = sd / logBase + 2 | 0;
9438 i = 0;
9439
9440 // divisor < 1e7
9441 if (yL == 1) {
9442 k = 0;
9443 yd = yd[0];
9444 sd++;
9445
9446 // k is the carry.
9447 for (; (i < xL || k) && sd--; i++) {
9448 t = k * base + (xd[i] || 0);
9449 qd[i] = t / yd | 0;
9450 k = t % yd | 0;
9451 }
9452
9453 more = k || i < xL;
9454
9455 // divisor >= 1e7
9456 } else {
9457
9458 // Normalise xd and yd so highest order digit of yd is >= base/2
9459 k = base / (yd[0] + 1) | 0;
9460
9461 if (k > 1) {
9462 yd = multiplyInteger(yd, k, base);
9463 xd = multiplyInteger(xd, k, base);
9464 yL = yd.length;
9465 xL = xd.length;
9466 }
9467
9468 xi = yL;
9469 rem = xd.slice(0, yL);
9470 remL = rem.length;
9471
9472 // Add zeros to make remainder as long as divisor.
9473 for (; remL < yL;) rem[remL++] = 0;
9474
9475 yz = yd.slice();
9476 yz.unshift(0);
9477 yd0 = yd[0];
9478
9479 if (yd[1] >= base / 2) ++yd0;
9480
9481 do {
9482 k = 0;
9483
9484 // Compare divisor and remainder.
9485 cmp = compare(yd, rem, yL, remL);
9486
9487 // If divisor < remainder.
9488 if (cmp < 0) {
9489
9490 // Calculate trial digit, k.
9491 rem0 = rem[0];
9492 if (yL != remL) rem0 = rem0 * base + (rem[1] || 0);
9493
9494 // k will be how many times the divisor goes into the current remainder.
9495 k = rem0 / yd0 | 0;
9496
9497 // Algorithm:
9498 // 1. product = divisor * trial digit (k)
9499 // 2. if product > remainder: product -= divisor, k--
9500 // 3. remainder -= product
9501 // 4. if product was < remainder at 2:
9502 // 5. compare new remainder and divisor
9503 // 6. If remainder > divisor: remainder -= divisor, k++
9504
9505 if (k > 1) {
9506 if (k >= base) k = base - 1;
9507
9508 // product = divisor * trial digit.
9509 prod = multiplyInteger(yd, k, base);
9510 prodL = prod.length;
9511 remL = rem.length;
9512
9513 // Compare product and remainder.
9514 cmp = compare(prod, rem, prodL, remL);
9515
9516 // product > remainder.
9517 if (cmp == 1) {
9518 k--;
9519
9520 // Subtract divisor from product.
9521 subtract(prod, yL < prodL ? yz : yd, prodL, base);
9522 }
9523 } else {
9524
9525 // cmp is -1.
9526 // If k is 0, there is no need to compare yd and rem again below, so change cmp to 1
9527 // to avoid it. If k is 1 there is a need to compare yd and rem again below.
9528 if (k == 0) cmp = k = 1;
9529 prod = yd.slice();
9530 }
9531
9532 prodL = prod.length;
9533 if (prodL < remL) prod.unshift(0);
9534
9535 // Subtract product from remainder.
9536 subtract(rem, prod, remL, base);
9537
9538 // If product was < previous remainder.
9539 if (cmp == -1) {
9540 remL = rem.length;
9541
9542 // Compare divisor and new remainder.
9543 cmp = compare(yd, rem, yL, remL);
9544
9545 // If divisor < new remainder, subtract divisor from remainder.
9546 if (cmp < 1) {
9547 k++;
9548
9549 // Subtract divisor from remainder.
9550 subtract(rem, yL < remL ? yz : yd, remL, base);
9551 }
9552 }
9553
9554 remL = rem.length;
9555 } else if (cmp === 0) {
9556 k++;
9557 rem = [0];
9558 } // if cmp === 1, k will be 0
9559
9560 // Add the next digit, k, to the result array.
9561 qd[i++] = k;
9562
9563 // Update the remainder.
9564 if (cmp && rem[0]) {
9565 rem[remL++] = xd[xi] || 0;
9566 } else {
9567 rem = [xd[xi]];
9568 remL = 1;
9569 }
9570
9571 } while ((xi++ < xL || rem[0] !== void 0) && sd--);
9572
9573 more = rem[0] !== void 0;
9574 }
9575
9576 // Leading zero?
9577 if (!qd[0]) qd.shift();
9578 }
9579
9580 // logBase is 1 when divide is being used for base conversion.
9581 if (logBase == 1) {
9582 q.e = e;
9583 inexact = more;
9584 } else {
9585
9586 // To calculate q.e, first get the number of digits of qd[0].
9587 for (i = 1, k = qd[0]; k >= 10; k /= 10) i++;
9588 q.e = i + e * logBase - 1;
9589
9590 finalise(q, dp ? pr + q.e + 1 : pr, rm, more);
9591 }
9592
9593 return q;
9594 };
9595 })();
9596
9597
9598 /*
9599 * Round `x` to `sd` significant digits using rounding mode `rm`.
9600 * Check for over/under-flow.
9601 */
9602 function finalise(x, sd, rm, isTruncated) {
9603 var digits, i, j, k, rd, roundUp, w, xd, xdi,
9604 Ctor = x.constructor;
9605
9606 // Don't round if sd is null or undefined.
9607 out: if (sd != null) {
9608 xd = x.d;
9609
9610 // Infinity/NaN.
9611 if (!xd) return x;
9612
9613 // rd: the rounding digit, i.e. the digit after the digit that may be rounded up.
9614 // w: the word of xd containing rd, a base 1e7 number.
9615 // xdi: the index of w within xd.
9616 // digits: the number of digits of w.
9617 // i: what would be the index of rd within w if all the numbers were 7 digits long (i.e. if
9618 // they had leading zeros)
9619 // j: if > 0, the actual index of rd within w (if < 0, rd is a leading zero).
9620
9621 // Get the length of the first word of the digits array xd.
9622 for (digits = 1, k = xd[0]; k >= 10; k /= 10) digits++;
9623 i = sd - digits;
9624
9625 // Is the rounding digit in the first word of xd?
9626 if (i < 0) {
9627 i += LOG_BASE;
9628 j = sd;
9629 w = xd[xdi = 0];
9630
9631 // Get the rounding digit at index j of w.
9632 rd = w / mathpow(10, digits - j - 1) % 10 | 0;
9633 } else {
9634 xdi = Math.ceil((i + 1) / LOG_BASE);
9635 k = xd.length;
9636 if (xdi >= k) {
9637 if (isTruncated) {
9638
9639 // Needed by `naturalExponential`, `naturalLogarithm` and `squareRoot`.
9640 for (; k++ <= xdi;) xd.push(0);
9641 w = rd = 0;
9642 digits = 1;
9643 i %= LOG_BASE;
9644 j = i - LOG_BASE + 1;
9645 } else {
9646 break out;
9647 }
9648 } else {
9649 w = k = xd[xdi];
9650
9651 // Get the number of digits of w.
9652 for (digits = 1; k >= 10; k /= 10) digits++;
9653
9654 // Get the index of rd within w.
9655 i %= LOG_BASE;
9656
9657 // Get the index of rd within w, adjusted for leading zeros.
9658 // The number of leading zeros of w is given by LOG_BASE - digits.
9659 j = i - LOG_BASE + digits;
9660
9661 // Get the rounding digit at index j of w.
9662 rd = j < 0 ? 0 : w / mathpow(10, digits - j - 1) % 10 | 0;
9663 }
9664 }
9665
9666 // Are there any non-zero digits after the rounding digit?
9667 isTruncated = isTruncated || sd < 0 ||
9668 xd[xdi + 1] !== void 0 || (j < 0 ? w : w % mathpow(10, digits - j - 1));
9669
9670 // The expression `w % mathpow(10, digits - j - 1)` returns all the digits of w to the right
9671 // of the digit at (left-to-right) index j, e.g. if w is 908714 and j is 2, the expression
9672 // will give 714.
9673
9674 roundUp = rm < 4
9675 ? (rd || isTruncated) && (rm == 0 || rm == (x.s < 0 ? 3 : 2))
9676 : rd > 5 || rd == 5 && (rm == 4 || isTruncated || rm == 6 &&
9677
9678 // Check whether the digit to the left of the rounding digit is odd.
9679 ((i > 0 ? j > 0 ? w / mathpow(10, digits - j) : 0 : xd[xdi - 1]) % 10) & 1 ||
9680 rm == (x.s < 0 ? 8 : 7));
9681
9682 if (sd < 1 || !xd[0]) {
9683 xd.length = 0;
9684 if (roundUp) {
9685
9686 // Convert sd to decimal places.
9687 sd -= x.e + 1;
9688
9689 // 1, 0.1, 0.01, 0.001, 0.0001 etc.
9690 xd[0] = mathpow(10, (LOG_BASE - sd % LOG_BASE) % LOG_BASE);
9691 x.e = -sd || 0;
9692 } else {
9693
9694 // Zero.
9695 xd[0] = x.e = 0;
9696 }
9697
9698 return x;
9699 }
9700
9701 // Remove excess digits.
9702 if (i == 0) {
9703 xd.length = xdi;
9704 k = 1;
9705 xdi--;
9706 } else {
9707 xd.length = xdi + 1;
9708 k = mathpow(10, LOG_BASE - i);
9709
9710 // E.g. 56700 becomes 56000 if 7 is the rounding digit.
9711 // j > 0 means i > number of leading zeros of w.
9712 xd[xdi] = j > 0 ? (w / mathpow(10, digits - j) % mathpow(10, j) | 0) * k : 0;
9713 }
9714
9715 if (roundUp) {
9716 for (;;) {
9717
9718 // Is the digit to be rounded up in the first word of xd?
9719 if (xdi == 0) {
9720
9721 // i will be the length of xd[0] before k is added.
9722 for (i = 1, j = xd[0]; j >= 10; j /= 10) i++;
9723 j = xd[0] += k;
9724 for (k = 1; j >= 10; j /= 10) k++;
9725
9726 // if i != k the length has increased.
9727 if (i != k) {
9728 x.e++;
9729 if (xd[0] == BASE) xd[0] = 1;
9730 }
9731
9732 break;
9733 } else {
9734 xd[xdi] += k;
9735 if (xd[xdi] != BASE) break;
9736 xd[xdi--] = 0;
9737 k = 1;
9738 }
9739 }
9740 }
9741
9742 // Remove trailing zeros.
9743 for (i = xd.length; xd[--i] === 0;) xd.pop();
9744 }
9745
9746 if (external) {
9747
9748 // Overflow?
9749 if (x.e > Ctor.maxE) {
9750
9751 // Infinity.
9752 x.d = null;
9753 x.e = NaN;
9754
9755 // Underflow?
9756 } else if (x.e < Ctor.minE) {
9757
9758 // Zero.
9759 x.e = 0;
9760 x.d = [0];
9761 // Ctor.underflow = true;
9762 } // else Ctor.underflow = false;
9763 }
9764
9765 return x;
9766 }
9767
9768
9769 function finiteToString(x, isExp, sd) {
9770 if (!x.isFinite()) return nonFiniteToString(x);
9771 var k,
9772 e = x.e,
9773 str = digitsToString(x.d),
9774 len = str.length;
9775
9776 if (isExp) {
9777 if (sd && (k = sd - len) > 0) {
9778 str = str.charAt(0) + '.' + str.slice(1) + getZeroString(k);
9779 } else if (len > 1) {
9780 str = str.charAt(0) + '.' + str.slice(1);
9781 }
9782
9783 str = str + (x.e < 0 ? 'e' : 'e+') + x.e;
9784 } else if (e < 0) {
9785 str = '0.' + getZeroString(-e - 1) + str;
9786 if (sd && (k = sd - len) > 0) str += getZeroString(k);
9787 } else if (e >= len) {
9788 str += getZeroString(e + 1 - len);
9789 if (sd && (k = sd - e - 1) > 0) str = str + '.' + getZeroString(k);
9790 } else {
9791 if ((k = e + 1) < len) str = str.slice(0, k) + '.' + str.slice(k);
9792 if (sd && (k = sd - len) > 0) {
9793 if (e + 1 === len) str += '.';
9794 str += getZeroString(k);
9795 }
9796 }
9797
9798 return str;
9799 }
9800
9801
9802 // Calculate the base 10 exponent from the base 1e7 exponent.
9803 function getBase10Exponent(digits, e) {
9804 var w = digits[0];
9805
9806 // Add the number of digits of the first word of the digits array.
9807 for ( e *= LOG_BASE; w >= 10; w /= 10) e++;
9808 return e;
9809 }
9810
9811
9812 function getLn10(Ctor, sd, pr) {
9813 if (sd > LN10_PRECISION) {
9814
9815 // Reset global state in case the exception is caught.
9816 external = true;
9817 if (pr) Ctor.precision = pr;
9818 throw Error(precisionLimitExceeded);
9819 }
9820 return finalise(new Ctor(LN10), sd, 1, true);
9821 }
9822
9823
9824 function getPi(Ctor, sd, rm) {
9825 if (sd > PI_PRECISION) throw Error(precisionLimitExceeded);
9826 return finalise(new Ctor(PI), sd, rm, true);
9827 }
9828
9829
9830 function getPrecision(digits) {
9831 var w = digits.length - 1,
9832 len = w * LOG_BASE + 1;
9833
9834 w = digits[w];
9835
9836 // If non-zero...
9837 if (w) {
9838
9839 // Subtract the number of trailing zeros of the last word.
9840 for (; w % 10 == 0; w /= 10) len--;
9841
9842 // Add the number of digits of the first word.
9843 for (w = digits[0]; w >= 10; w /= 10) len++;
9844 }
9845
9846 return len;
9847 }
9848
9849
9850 function getZeroString(k) {
9851 var zs = '';
9852 for (; k--;) zs += '0';
9853 return zs;
9854 }
9855
9856
9857 /*
9858 * Return a new Decimal whose value is the value of Decimal `x` to the power `n`, where `n` is an
9859 * integer of type number.
9860 *
9861 * Implements 'exponentiation by squaring'. Called by `pow` and `parseOther`.
9862 *
9863 */
9864 function intPow(Ctor, x, n, pr) {
9865 var isTruncated,
9866 r = new Ctor(1),
9867
9868 // Max n of 9007199254740991 takes 53 loop iterations.
9869 // Maximum digits array length; leaves [28, 34] guard digits.
9870 k = Math.ceil(pr / LOG_BASE + 4);
9871
9872 external = false;
9873
9874 for (;;) {
9875 if (n % 2) {
9876 r = r.times(x);
9877 if (truncate(r.d, k)) isTruncated = true;
9878 }
9879
9880 n = mathfloor(n / 2);
9881 if (n === 0) {
9882
9883 // To ensure correct rounding when r.d is truncated, increment the last word if it is zero.
9884 n = r.d.length - 1;
9885 if (isTruncated && r.d[n] === 0) ++r.d[n];
9886 break;
9887 }
9888
9889 x = x.times(x);
9890 truncate(x.d, k);
9891 }
9892
9893 external = true;
9894
9895 return r;
9896 }
9897
9898
9899 function isOdd(n) {
9900 return n.d[n.d.length - 1] & 1;
9901 }
9902
9903
9904 /*
9905 * Handle `max` and `min`. `ltgt` is 'lt' or 'gt'.
9906 */
9907 function maxOrMin(Ctor, args, ltgt) {
9908 var y,
9909 x = new Ctor(args[0]),
9910 i = 0;
9911
9912 for (; ++i < args.length;) {
9913 y = new Ctor(args[i]);
9914 if (!y.s) {
9915 x = y;
9916 break;
9917 } else if (x[ltgt](y)) {
9918 x = y;
9919 }
9920 }
9921
9922 return x;
9923 }
9924
9925
9926 /*
9927 * Return a new Decimal whose value is the natural exponential of `x` rounded to `sd` significant
9928 * digits.
9929 *
9930 * Taylor/Maclaurin series.
9931 *
9932 * exp(x) = x^0/0! + x^1/1! + x^2/2! + x^3/3! + ...
9933 *
9934 * Argument reduction:
9935 * Repeat x = x / 32, k += 5, until |x| < 0.1
9936 * exp(x) = exp(x / 2^k)^(2^k)
9937 *
9938 * Previously, the argument was initially reduced by
9939 * exp(x) = exp(r) * 10^k where r = x - k * ln10, k = floor(x / ln10)
9940 * to first put r in the range [0, ln10], before dividing by 32 until |x| < 0.1, but this was
9941 * found to be slower than just dividing repeatedly by 32 as above.
9942 *
9943 * Max integer argument: exp('20723265836946413') = 6.3e+9000000000000000
9944 * Min integer argument: exp('-20723265836946411') = 1.2e-9000000000000000
9945 * (Math object integer min/max: Math.exp(709) = 8.2e+307, Math.exp(-745) = 5e-324)
9946 *
9947 * exp(Infinity) = Infinity
9948 * exp(-Infinity) = 0
9949 * exp(NaN) = NaN
9950 * exp(±0) = 1
9951 *
9952 * exp(x) is non-terminating for any finite, non-zero x.
9953 *
9954 * The result will always be correctly rounded.
9955 *
9956 */
9957 function naturalExponential(x, sd) {
9958 var denominator, guard, j, pow, sum, t, wpr,
9959 rep = 0,
9960 i = 0,
9961 k = 0,
9962 Ctor = x.constructor,
9963 rm = Ctor.rounding,
9964 pr = Ctor.precision;
9965
9966 // 0/NaN/Infinity?
9967 if (!x.d || !x.d[0] || x.e > 17) {
9968
9969 return new Ctor(x.d
9970 ? !x.d[0] ? 1 : x.s < 0 ? 0 : 1 / 0
9971 : x.s ? x.s < 0 ? 0 : x : 0 / 0);
9972 }
9973
9974 if (sd == null) {
9975 external = false;
9976 wpr = pr;
9977 } else {
9978 wpr = sd;
9979 }
9980
9981 t = new Ctor(0.03125);
9982
9983 // while abs(x) >= 0.1
9984 while (x.e > -2) {
9985
9986 // x = x / 2^5
9987 x = x.times(t);
9988 k += 5;
9989 }
9990
9991 // Use 2 * log10(2^k) + 5 (empirically derived) to estimate the increase in precision
9992 // necessary to ensure the first 4 rounding digits are correct.
9993 guard = Math.log(mathpow(2, k)) / Math.LN10 * 2 + 5 | 0;
9994 wpr += guard;
9995 denominator = pow = sum = new Ctor(1);
9996 Ctor.precision = wpr;
9997
9998 for (;;) {
9999 pow = finalise(pow.times(x), wpr, 1);
10000 denominator = denominator.times(++i);
10001 t = sum.plus(divide(pow, denominator, wpr, 1));
10002
10003 if (digitsToString(t.d).slice(0, wpr) === digitsToString(sum.d).slice(0, wpr)) {
10004 j = k;
10005 while (j--) sum = finalise(sum.times(sum), wpr, 1);
10006
10007 // Check to see if the first 4 rounding digits are [49]999.
10008 // If so, repeat the summation with a higher precision, otherwise
10009 // e.g. with precision: 18, rounding: 1
10010 // exp(18.404272462595034083567793919843761) = 98372560.1229999999 (should be 98372560.123)
10011 // `wpr - guard` is the index of first rounding digit.
10012 if (sd == null) {
10013
10014 if (rep < 3 && checkRoundingDigits(sum.d, wpr - guard, rm, rep)) {
10015 Ctor.precision = wpr += 10;
10016 denominator = pow = t = new Ctor(1);
10017 i = 0;
10018 rep++;
10019 } else {
10020 return finalise(sum, Ctor.precision = pr, rm, external = true);
10021 }
10022 } else {
10023 Ctor.precision = pr;
10024 return sum;
10025 }
10026 }
10027
10028 sum = t;
10029 }
10030 }
10031
10032
10033 /*
10034 * Return a new Decimal whose value is the natural logarithm of `x` rounded to `sd` significant
10035 * digits.
10036 *
10037 * ln(-n) = NaN
10038 * ln(0) = -Infinity
10039 * ln(-0) = -Infinity
10040 * ln(1) = 0
10041 * ln(Infinity) = Infinity
10042 * ln(-Infinity) = NaN
10043 * ln(NaN) = NaN
10044 *
10045 * ln(n) (n != 1) is non-terminating.
10046 *
10047 */
10048 function naturalLogarithm(y, sd) {
10049 var c, c0, denominator, e, numerator, rep, sum, t, wpr, x1, x2,
10050 n = 1,
10051 guard = 10,
10052 x = y,
10053 xd = x.d,
10054 Ctor = x.constructor,
10055 rm = Ctor.rounding,
10056 pr = Ctor.precision;
10057
10058 // Is x negative or Infinity, NaN, 0 or 1?
10059 if (x.s < 0 || !xd || !xd[0] || !x.e && xd[0] == 1 && xd.length == 1) {
10060 return new Ctor(xd && !xd[0] ? -1 / 0 : x.s != 1 ? NaN : xd ? 0 : x);
10061 }
10062
10063 if (sd == null) {
10064 external = false;
10065 wpr = pr;
10066 } else {
10067 wpr = sd;
10068 }
10069
10070 Ctor.precision = wpr += guard;
10071 c = digitsToString(xd);
10072 c0 = c.charAt(0);
10073
10074 if (Math.abs(e = x.e) < 1.5e15) {
10075
10076 // Argument reduction.
10077 // The series converges faster the closer the argument is to 1, so using
10078 // ln(a^b) = b * ln(a), ln(a) = ln(a^b) / b
10079 // multiply the argument by itself until the leading digits of the significand are 7, 8, 9,
10080 // 10, 11, 12 or 13, recording the number of multiplications so the sum of the series can
10081 // later be divided by this number, then separate out the power of 10 using
10082 // ln(a*10^b) = ln(a) + b*ln(10).
10083
10084 // max n is 21 (gives 0.9, 1.0 or 1.1) (9e15 / 21 = 4.2e14).
10085 //while (c0 < 9 && c0 != 1 || c0 == 1 && c.charAt(1) > 1) {
10086 // max n is 6 (gives 0.7 - 1.3)
10087 while (c0 < 7 && c0 != 1 || c0 == 1 && c.charAt(1) > 3) {
10088 x = x.times(y);
10089 c = digitsToString(x.d);
10090 c0 = c.charAt(0);
10091 n++;
10092 }
10093
10094 e = x.e;
10095
10096 if (c0 > 1) {
10097 x = new Ctor('0.' + c);
10098 e++;
10099 } else {
10100 x = new Ctor(c0 + '.' + c.slice(1));
10101 }
10102 } else {
10103
10104 // The argument reduction method above may result in overflow if the argument y is a massive
10105 // number with exponent >= 1500000000000000 (9e15 / 6 = 1.5e15), so instead recall this
10106 // function using ln(x*10^e) = ln(x) + e*ln(10).
10107 t = getLn10(Ctor, wpr + 2, pr).times(e + '');
10108 x = naturalLogarithm(new Ctor(c0 + '.' + c.slice(1)), wpr - guard).plus(t);
10109 Ctor.precision = pr;
10110
10111 return sd == null ? finalise(x, pr, rm, external = true) : x;
10112 }
10113
10114 // x1 is x reduced to a value near 1.
10115 x1 = x;
10116
10117 // Taylor series.
10118 // ln(y) = ln((1 + x)/(1 - x)) = 2(x + x^3/3 + x^5/5 + x^7/7 + ...)
10119 // where x = (y - 1)/(y + 1) (|x| < 1)
10120 sum = numerator = x = divide(x.minus(1), x.plus(1), wpr, 1);
10121 x2 = finalise(x.times(x), wpr, 1);
10122 denominator = 3;
10123
10124 for (;;) {
10125 numerator = finalise(numerator.times(x2), wpr, 1);
10126 t = sum.plus(divide(numerator, new Ctor(denominator), wpr, 1));
10127
10128 if (digitsToString(t.d).slice(0, wpr) === digitsToString(sum.d).slice(0, wpr)) {
10129 sum = sum.times(2);
10130
10131 // Reverse the argument reduction. Check that e is not 0 because, besides preventing an
10132 // unnecessary calculation, -0 + 0 = +0 and to ensure correct rounding -0 needs to stay -0.
10133 if (e !== 0) sum = sum.plus(getLn10(Ctor, wpr + 2, pr).times(e + ''));
10134 sum = divide(sum, new Ctor(n), wpr, 1);
10135
10136 // Is rm > 3 and the first 4 rounding digits 4999, or rm < 4 (or the summation has
10137 // been repeated previously) and the first 4 rounding digits 9999?
10138 // If so, restart the summation with a higher precision, otherwise
10139 // e.g. with precision: 12, rounding: 1
10140 // ln(135520028.6126091714265381533) = 18.7246299999 when it should be 18.72463.
10141 // `wpr - guard` is the index of first rounding digit.
10142 if (sd == null) {
10143 if (checkRoundingDigits(sum.d, wpr - guard, rm, rep)) {
10144 Ctor.precision = wpr += guard;
10145 t = numerator = x = divide(x1.minus(1), x1.plus(1), wpr, 1);
10146 x2 = finalise(x.times(x), wpr, 1);
10147 denominator = rep = 1;
10148 } else {
10149 return finalise(sum, Ctor.precision = pr, rm, external = true);
10150 }
10151 } else {
10152 Ctor.precision = pr;
10153 return sum;
10154 }
10155 }
10156
10157 sum = t;
10158 denominator += 2;
10159 }
10160 }
10161
10162
10163 // ±Infinity, NaN.
10164 function nonFiniteToString(x) {
10165 // Unsigned.
10166 return String(x.s * x.s / 0);
10167 }
10168
10169
10170 /*
10171 * Parse the value of a new Decimal `x` from string `str`.
10172 */
10173 function parseDecimal(x, str) {
10174 var e, i, len;
10175
10176 // Decimal point?
10177 if ((e = str.indexOf('.')) > -1) str = str.replace('.', '');
10178
10179 // Exponential form?
10180 if ((i = str.search(/e/i)) > 0) {
10181
10182 // Determine exponent.
10183 if (e < 0) e = i;
10184 e += +str.slice(i + 1);
10185 str = str.substring(0, i);
10186 } else if (e < 0) {
10187
10188 // Integer.
10189 e = str.length;
10190 }
10191
10192 // Determine leading zeros.
10193 for (i = 0; str.charCodeAt(i) === 48; i++);
10194
10195 // Determine trailing zeros.
10196 for (len = str.length; str.charCodeAt(len - 1) === 48; --len);
10197 str = str.slice(i, len);
10198
10199 if (str) {
10200 len -= i;
10201 x.e = e = e - i - 1;
10202 x.d = [];
10203
10204 // Transform base
10205
10206 // e is the base 10 exponent.
10207 // i is where to slice str to get the first word of the digits array.
10208 i = (e + 1) % LOG_BASE;
10209 if (e < 0) i += LOG_BASE;
10210
10211 if (i < len) {
10212 if (i) x.d.push(+str.slice(0, i));
10213 for (len -= LOG_BASE; i < len;) x.d.push(+str.slice(i, i += LOG_BASE));
10214 str = str.slice(i);
10215 i = LOG_BASE - str.length;
10216 } else {
10217 i -= len;
10218 }
10219
10220 for (; i--;) str += '0';
10221 x.d.push(+str);
10222
10223 if (external) {
10224
10225 // Overflow?
10226 if (x.e > x.constructor.maxE) {
10227
10228 // Infinity.
10229 x.d = null;
10230 x.e = NaN;
10231
10232 // Underflow?
10233 } else if (x.e < x.constructor.minE) {
10234
10235 // Zero.
10236 x.e = 0;
10237 x.d = [0];
10238 // x.constructor.underflow = true;
10239 } // else x.constructor.underflow = false;
10240 }
10241 } else {
10242
10243 // Zero.
10244 x.e = 0;
10245 x.d = [0];
10246 }
10247
10248 return x;
10249 }
10250
10251
10252 /*
10253 * Parse the value of a new Decimal `x` from a string `str`, which is not a decimal value.
10254 */
10255 function parseOther(x, str) {
10256 var base, Ctor, divisor, i, isFloat, len, p, xd, xe;
10257
10258 if (str === 'Infinity' || str === 'NaN') {
10259 if (!+str) x.s = NaN;
10260 x.e = NaN;
10261 x.d = null;
10262 return x;
10263 }
10264
10265 if (isHex.test(str)) {
10266 base = 16;
10267 str = str.toLowerCase();
10268 } else if (isBinary.test(str)) {
10269 base = 2;
10270 } else if (isOctal.test(str)) {
10271 base = 8;
10272 } else {
10273 throw Error(invalidArgument + str);
10274 }
10275
10276 // Is there a binary exponent part?
10277 i = str.search(/p/i);
10278
10279 if (i > 0) {
10280 p = +str.slice(i + 1);
10281 str = str.substring(2, i);
10282 } else {
10283 str = str.slice(2);
10284 }
10285
10286 // Convert `str` as an integer then divide the result by `base` raised to a power such that the
10287 // fraction part will be restored.
10288 i = str.indexOf('.');
10289 isFloat = i >= 0;
10290 Ctor = x.constructor;
10291
10292 if (isFloat) {
10293 str = str.replace('.', '');
10294 len = str.length;
10295 i = len - i;
10296
10297 // log[10](16) = 1.2041... , log[10](88) = 1.9444....
10298 divisor = intPow(Ctor, new Ctor(base), i, i * 2);
10299 }
10300
10301 xd = convertBase(str, base, BASE);
10302 xe = xd.length - 1;
10303
10304 // Remove trailing zeros.
10305 for (i = xe; xd[i] === 0; --i) xd.pop();
10306 if (i < 0) return new Ctor(x.s * 0);
10307 x.e = getBase10Exponent(xd, xe);
10308 x.d = xd;
10309 external = false;
10310
10311 // At what precision to perform the division to ensure exact conversion?
10312 // maxDecimalIntegerPartDigitCount = ceil(log[10](b) * otherBaseIntegerPartDigitCount)
10313 // log[10](2) = 0.30103, log[10](8) = 0.90309, log[10](16) = 1.20412
10314 // E.g. ceil(1.2 * 3) = 4, so up to 4 decimal digits are needed to represent 3 hex int digits.
10315 // maxDecimalFractionPartDigitCount = {Hex:4|Oct:3|Bin:1} * otherBaseFractionPartDigitCount
10316 // Therefore using 4 * the number of digits of str will always be enough.
10317 if (isFloat) x = divide(x, divisor, len * 4);
10318
10319 // Multiply by the binary exponent part if present.
10320 if (p) x = x.times(Math.abs(p) < 54 ? mathpow(2, p) : Decimal.pow(2, p));
10321 external = true;
10322
10323 return x;
10324 }
10325
10326
10327 /*
10328 * sin(x) = x - x^3/3! + x^5/5! - ...
10329 * |x| < pi/2
10330 *
10331 */
10332 function sine(Ctor, x) {
10333 var k,
10334 len = x.d.length;
10335
10336 if (len < 3) return taylorSeries(Ctor, 2, x, x);
10337
10338 // Argument reduction: sin(5x) = 16*sin^5(x) - 20*sin^3(x) + 5*sin(x)
10339 // i.e. sin(x) = 16*sin^5(x/5) - 20*sin^3(x/5) + 5*sin(x/5)
10340 // and sin(x) = sin(x/5)(5 + sin^2(x/5)(16sin^2(x/5) - 20))
10341
10342 // Estimate the optimum number of times to use the argument reduction.
10343 k = 1.4 * Math.sqrt(len);
10344 k = k > 16 ? 16 : k | 0;
10345
10346 x = x.times(1 / tinyPow(5, k));
10347 x = taylorSeries(Ctor, 2, x, x);
10348
10349 // Reverse argument reduction
10350 var sin2_x,
10351 d5 = new Ctor(5),
10352 d16 = new Ctor(16),
10353 d20 = new Ctor(20);
10354 for (; k--;) {
10355 sin2_x = x.times(x);
10356 x = x.times(d5.plus(sin2_x.times(d16.times(sin2_x).minus(d20))));
10357 }
10358
10359 return x;
10360 }
10361
10362
10363 // Calculate Taylor series for `cos`, `cosh`, `sin` and `sinh`.
10364 function taylorSeries(Ctor, n, x, y, isHyperbolic) {
10365 var j, t, u, x2,
10366 i = 1,
10367 pr = Ctor.precision,
10368 k = Math.ceil(pr / LOG_BASE);
10369
10370 external = false;
10371 x2 = x.times(x);
10372 u = new Ctor(y);
10373
10374 for (;;) {
10375 t = divide(u.times(x2), new Ctor(n++ * n++), pr, 1);
10376 u = isHyperbolic ? y.plus(t) : y.minus(t);
10377 y = divide(t.times(x2), new Ctor(n++ * n++), pr, 1);
10378 t = u.plus(y);
10379
10380 if (t.d[k] !== void 0) {
10381 for (j = k; t.d[j] === u.d[j] && j--;);
10382 if (j == -1) break;
10383 }
10384
10385 j = u;
10386 u = y;
10387 y = t;
10388 t = j;
10389 i++;
10390 }
10391
10392 external = true;
10393 t.d.length = k + 1;
10394
10395 return t;
10396 }
10397
10398
10399 // Exponent e must be positive and non-zero.
10400 function tinyPow(b, e) {
10401 var n = b;
10402 while (--e) n *= b;
10403 return n;
10404 }
10405
10406
10407 // Return the absolute value of `x` reduced to less than or equal to half pi.
10408 function toLessThanHalfPi(Ctor, x) {
10409 var t,
10410 isNeg = x.s < 0,
10411 pi = getPi(Ctor, Ctor.precision, 1),
10412 halfPi = pi.times(0.5);
10413
10414 x = x.abs();
10415
10416 if (x.lte(halfPi)) {
10417 quadrant = isNeg ? 4 : 1;
10418 return x;
10419 }
10420
10421 t = x.divToInt(pi);
10422
10423 if (t.isZero()) {
10424 quadrant = isNeg ? 3 : 2;
10425 } else {
10426 x = x.minus(t.times(pi));
10427
10428 // 0 <= x < pi
10429 if (x.lte(halfPi)) {
10430 quadrant = isOdd(t) ? (isNeg ? 2 : 3) : (isNeg ? 4 : 1);
10431 return x;
10432 }
10433
10434 quadrant = isOdd(t) ? (isNeg ? 1 : 4) : (isNeg ? 3 : 2);
10435 }
10436
10437 return x.minus(pi).abs();
10438 }
10439
10440
10441 /*
10442 * Return the value of Decimal `x` as a string in base `baseOut`.
10443 *
10444 * If the optional `sd` argument is present include a binary exponent suffix.
10445 */
10446 function toStringBinary(x, baseOut, sd, rm) {
10447 var base, e, i, k, len, roundUp, str, xd, y,
10448 Ctor = x.constructor,
10449 isExp = sd !== void 0;
10450
10451 if (isExp) {
10452 checkInt32(sd, 1, MAX_DIGITS);
10453 if (rm === void 0) rm = Ctor.rounding;
10454 else checkInt32(rm, 0, 8);
10455 } else {
10456 sd = Ctor.precision;
10457 rm = Ctor.rounding;
10458 }
10459
10460 if (!x.isFinite()) {
10461 str = nonFiniteToString(x);
10462 } else {
10463 str = finiteToString(x);
10464 i = str.indexOf('.');
10465
10466 // Use exponential notation according to `toExpPos` and `toExpNeg`? No, but if required:
10467 // maxBinaryExponent = floor((decimalExponent + 1) * log[2](10))
10468 // minBinaryExponent = floor(decimalExponent * log[2](10))
10469 // log[2](10) = 3.321928094887362347870319429489390175864
10470
10471 if (isExp) {
10472 base = 2;
10473 if (baseOut == 16) {
10474 sd = sd * 4 - 3;
10475 } else if (baseOut == 8) {
10476 sd = sd * 3 - 2;
10477 }
10478 } else {
10479 base = baseOut;
10480 }
10481
10482 // Convert the number as an integer then divide the result by its base raised to a power such
10483 // that the fraction part will be restored.
10484
10485 // Non-integer.
10486 if (i >= 0) {
10487 str = str.replace('.', '');
10488 y = new Ctor(1);
10489 y.e = str.length - i;
10490 y.d = convertBase(finiteToString(y), 10, base);
10491 y.e = y.d.length;
10492 }
10493
10494 xd = convertBase(str, 10, base);
10495 e = len = xd.length;
10496
10497 // Remove trailing zeros.
10498 for (; xd[--len] == 0;) xd.pop();
10499
10500 if (!xd[0]) {
10501 str = isExp ? '0p+0' : '0';
10502 } else {
10503 if (i < 0) {
10504 e--;
10505 } else {
10506 x = new Ctor(x);
10507 x.d = xd;
10508 x.e = e;
10509 x = divide(x, y, sd, rm, 0, base);
10510 xd = x.d;
10511 e = x.e;
10512 roundUp = inexact;
10513 }
10514
10515 // The rounding digit, i.e. the digit after the digit that may be rounded up.
10516 i = xd[sd];
10517 k = base / 2;
10518 roundUp = roundUp || xd[sd + 1] !== void 0;
10519
10520 roundUp = rm < 4
10521 ? (i !== void 0 || roundUp) && (rm === 0 || rm === (x.s < 0 ? 3 : 2))
10522 : i > k || i === k && (rm === 4 || roundUp || rm === 6 && xd[sd - 1] & 1 ||
10523 rm === (x.s < 0 ? 8 : 7));
10524
10525 xd.length = sd;
10526
10527 if (roundUp) {
10528
10529 // Rounding up may mean the previous digit has to be rounded up and so on.
10530 for (; ++xd[--sd] > base - 1;) {
10531 xd[sd] = 0;
10532 if (!sd) {
10533 ++e;
10534 xd.unshift(1);
10535 }
10536 }
10537 }
10538
10539 // Determine trailing zeros.
10540 for (len = xd.length; !xd[len - 1]; --len);
10541
10542 // E.g. [4, 11, 15] becomes 4bf.
10543 for (i = 0, str = ''; i < len; i++) str += NUMERALS.charAt(xd[i]);
10544
10545 // Add binary exponent suffix?
10546 if (isExp) {
10547 if (len > 1) {
10548 if (baseOut == 16 || baseOut == 8) {
10549 i = baseOut == 16 ? 4 : 3;
10550 for (--len; len % i; len++) str += '0';
10551 xd = convertBase(str, base, baseOut);
10552 for (len = xd.length; !xd[len - 1]; --len);
10553
10554 // xd[0] will always be be 1
10555 for (i = 1, str = '1.'; i < len; i++) str += NUMERALS.charAt(xd[i]);
10556 } else {
10557 str = str.charAt(0) + '.' + str.slice(1);
10558 }
10559 }
10560
10561 str = str + (e < 0 ? 'p' : 'p+') + e;
10562 } else if (e < 0) {
10563 for (; ++e;) str = '0' + str;
10564 str = '0.' + str;
10565 } else {
10566 if (++e > len) for (e -= len; e-- ;) str += '0';
10567 else if (e < len) str = str.slice(0, e) + '.' + str.slice(e);
10568 }
10569 }
10570
10571 str = (baseOut == 16 ? '0x' : baseOut == 2 ? '0b' : baseOut == 8 ? '0o' : '') + str;
10572 }
10573
10574 return x.s < 0 ? '-' + str : str;
10575 }
10576
10577
10578 // Does not strip trailing zeros.
10579 function truncate(arr, len) {
10580 if (arr.length > len) {
10581 arr.length = len;
10582 return true;
10583 }
10584 }
10585
10586
10587 // Decimal methods
10588
10589
10590 /*
10591 * abs
10592 * acos
10593 * acosh
10594 * add
10595 * asin
10596 * asinh
10597 * atan
10598 * atanh
10599 * atan2
10600 * cbrt
10601 * ceil
10602 * clone
10603 * config
10604 * cos
10605 * cosh
10606 * div
10607 * exp
10608 * floor
10609 * hypot
10610 * ln
10611 * log
10612 * log2
10613 * log10
10614 * max
10615 * min
10616 * mod
10617 * mul
10618 * pow
10619 * random
10620 * round
10621 * set
10622 * sign
10623 * sin
10624 * sinh
10625 * sqrt
10626 * sub
10627 * tan
10628 * tanh
10629 * trunc
10630 */
10631
10632
10633 /*
10634 * Return a new Decimal whose value is the absolute value of `x`.
10635 *
10636 * x {number|string|Decimal}
10637 *
10638 */
10639 function abs(x) {
10640 return new this(x).abs();
10641 }
10642
10643
10644 /*
10645 * Return a new Decimal whose value is the arccosine in radians of `x`.
10646 *
10647 * x {number|string|Decimal}
10648 *
10649 */
10650 function acos(x) {
10651 return new this(x).acos();
10652 }
10653
10654
10655 /*
10656 * Return a new Decimal whose value is the inverse of the hyperbolic cosine of `x`, rounded to
10657 * `precision` significant digits using rounding mode `rounding`.
10658 *
10659 * x {number|string|Decimal} A value in radians.
10660 *
10661 */
10662 function acosh(x) {
10663 return new this(x).acosh();
10664 }
10665
10666
10667 /*
10668 * Return a new Decimal whose value is the sum of `x` and `y`, rounded to `precision` significant
10669 * digits using rounding mode `rounding`.
10670 *
10671 * x {number|string|Decimal}
10672 * y {number|string|Decimal}
10673 *
10674 */
10675 function add(x, y) {
10676 return new this(x).plus(y);
10677 }
10678
10679
10680 /*
10681 * Return a new Decimal whose value is the arcsine in radians of `x`, rounded to `precision`
10682 * significant digits using rounding mode `rounding`.
10683 *
10684 * x {number|string|Decimal}
10685 *
10686 */
10687 function asin(x) {
10688 return new this(x).asin();
10689 }
10690
10691
10692 /*
10693 * Return a new Decimal whose value is the inverse of the hyperbolic sine of `x`, rounded to
10694 * `precision` significant digits using rounding mode `rounding`.
10695 *
10696 * x {number|string|Decimal} A value in radians.
10697 *
10698 */
10699 function asinh(x) {
10700 return new this(x).asinh();
10701 }
10702
10703
10704 /*
10705 * Return a new Decimal whose value is the arctangent in radians of `x`, rounded to `precision`
10706 * significant digits using rounding mode `rounding`.
10707 *
10708 * x {number|string|Decimal}
10709 *
10710 */
10711 function atan(x) {
10712 return new this(x).atan();
10713 }
10714
10715
10716 /*
10717 * Return a new Decimal whose value is the inverse of the hyperbolic tangent of `x`, rounded to
10718 * `precision` significant digits using rounding mode `rounding`.
10719 *
10720 * x {number|string|Decimal} A value in radians.
10721 *
10722 */
10723 function atanh(x) {
10724 return new this(x).atanh();
10725 }
10726
10727
10728 /*
10729 * Return a new Decimal whose value is the arctangent in radians of `y/x` in the range -pi to pi
10730 * (inclusive), rounded to `precision` significant digits using rounding mode `rounding`.
10731 *
10732 * Domain: [-Infinity, Infinity]
10733 * Range: [-pi, pi]
10734 *
10735 * y {number|string|Decimal} The y-coordinate.
10736 * x {number|string|Decimal} The x-coordinate.
10737 *
10738 * atan2(±0, -0) = ±pi
10739 * atan2(±0, +0) = ±0
10740 * atan2(±0, -x) = ±pi for x > 0
10741 * atan2(±0, x) = ±0 for x > 0
10742 * atan2(-y, ±0) = -pi/2 for y > 0
10743 * atan2(y, ±0) = pi/2 for y > 0
10744 * atan2(±y, -Infinity) = ±pi for finite y > 0
10745 * atan2(±y, +Infinity) = ±0 for finite y > 0
10746 * atan2(±Infinity, x) = ±pi/2 for finite x
10747 * atan2(±Infinity, -Infinity) = ±3*pi/4
10748 * atan2(±Infinity, +Infinity) = ±pi/4
10749 * atan2(NaN, x) = NaN
10750 * atan2(y, NaN) = NaN
10751 *
10752 */
10753 function atan2(y, x) {
10754 y = new this(y);
10755 x = new this(x);
10756 var r,
10757 pr = this.precision,
10758 rm = this.rounding,
10759 wpr = pr + 4;
10760
10761 // Either NaN
10762 if (!y.s || !x.s) {
10763 r = new this(NaN);
10764
10765 // Both ±Infinity
10766 } else if (!y.d && !x.d) {
10767 r = getPi(this, wpr, 1).times(x.s > 0 ? 0.25 : 0.75);
10768 r.s = y.s;
10769
10770 // x is ±Infinity or y is ±0
10771 } else if (!x.d || y.isZero()) {
10772 r = x.s < 0 ? getPi(this, pr, rm) : new this(0);
10773 r.s = y.s;
10774
10775 // y is ±Infinity or x is ±0
10776 } else if (!y.d || x.isZero()) {
10777 r = getPi(this, wpr, 1).times(0.5);
10778 r.s = y.s;
10779
10780 // Both non-zero and finite
10781 } else if (x.s < 0) {
10782 this.precision = wpr;
10783 this.rounding = 1;
10784 r = this.atan(divide(y, x, wpr, 1));
10785 x = getPi(this, wpr, 1);
10786 this.precision = pr;
10787 this.rounding = rm;
10788 r = y.s < 0 ? r.minus(x) : r.plus(x);
10789 } else {
10790 r = this.atan(divide(y, x, wpr, 1));
10791 }
10792
10793 return r;
10794 }
10795
10796
10797 /*
10798 * Return a new Decimal whose value is the cube root of `x`, rounded to `precision` significant
10799 * digits using rounding mode `rounding`.
10800 *
10801 * x {number|string|Decimal}
10802 *
10803 */
10804 function cbrt(x) {
10805 return new this(x).cbrt();
10806 }
10807
10808
10809 /*
10810 * Return a new Decimal whose value is `x` rounded to an integer using `ROUND_CEIL`.
10811 *
10812 * x {number|string|Decimal}
10813 *
10814 */
10815 function ceil(x) {
10816 return finalise(x = new this(x), x.e + 1, 2);
10817 }
10818
10819
10820 /*
10821 * Configure global settings for a Decimal constructor.
10822 *
10823 * `obj` is an object with one or more of the following properties,
10824 *
10825 * precision {number}
10826 * rounding {number}
10827 * toExpNeg {number}
10828 * toExpPos {number}
10829 * maxE {number}
10830 * minE {number}
10831 * modulo {number}
10832 * crypto {boolean|number}
10833 * defaults {true}
10834 *
10835 * E.g. Decimal.config({ precision: 20, rounding: 4 })
10836 *
10837 */
10838 function config(obj) {
10839 if (!obj || typeof obj !== 'object') throw Error(decimalError + 'Object expected');
10840 var i, p, v,
10841 useDefaults = obj.defaults === true,
10842 ps = [
10843 'precision', 1, MAX_DIGITS,
10844 'rounding', 0, 8,
10845 'toExpNeg', -EXP_LIMIT, 0,
10846 'toExpPos', 0, EXP_LIMIT,
10847 'maxE', 0, EXP_LIMIT,
10848 'minE', -EXP_LIMIT, 0,
10849 'modulo', 0, 9
10850 ];
10851
10852 for (i = 0; i < ps.length; i += 3) {
10853 if (p = ps[i], useDefaults) this[p] = DEFAULTS[p];
10854 if ((v = obj[p]) !== void 0) {
10855 if (mathfloor(v) === v && v >= ps[i + 1] && v <= ps[i + 2]) this[p] = v;
10856 else throw Error(invalidArgument + p + ': ' + v);
10857 }
10858 }
10859
10860 if (p = 'crypto', useDefaults) this[p] = DEFAULTS[p];
10861 if ((v = obj[p]) !== void 0) {
10862 if (v === true || v === false || v === 0 || v === 1) {
10863 if (v) {
10864 if (typeof crypto != 'undefined' && crypto &&
10865 (crypto.getRandomValues || crypto.randomBytes)) {
10866 this[p] = true;
10867 } else {
10868 throw Error(cryptoUnavailable);
10869 }
10870 } else {
10871 this[p] = false;
10872 }
10873 } else {
10874 throw Error(invalidArgument + p + ': ' + v);
10875 }
10876 }
10877
10878 return this;
10879 }
10880
10881
10882 /*
10883 * Return a new Decimal whose value is the cosine of `x`, rounded to `precision` significant
10884 * digits using rounding mode `rounding`.
10885 *
10886 * x {number|string|Decimal} A value in radians.
10887 *
10888 */
10889 function cos(x) {
10890 return new this(x).cos();
10891 }
10892
10893
10894 /*
10895 * Return a new Decimal whose value is the hyperbolic cosine of `x`, rounded to precision
10896 * significant digits using rounding mode `rounding`.
10897 *
10898 * x {number|string|Decimal} A value in radians.
10899 *
10900 */
10901 function cosh(x) {
10902 return new this(x).cosh();
10903 }
10904
10905
10906 /*
10907 * Create and return a Decimal constructor with the same configuration properties as this Decimal
10908 * constructor.
10909 *
10910 */
10911 function clone(obj) {
10912 var i, p, ps;
10913
10914 /*
10915 * The Decimal constructor and exported function.
10916 * Return a new Decimal instance.
10917 *
10918 * v {number|string|Decimal} A numeric value.
10919 *
10920 */
10921 function Decimal(v) {
10922 var e, i, t,
10923 x = this;
10924
10925 // Decimal called without new.
10926 if (!(x instanceof Decimal)) return new Decimal(v);
10927
10928 // Retain a reference to this Decimal constructor, and shadow Decimal.prototype.constructor
10929 // which points to Object.
10930 x.constructor = Decimal;
10931
10932 // Duplicate.
10933 if (v instanceof Decimal) {
10934 x.s = v.s;
10935
10936 if (external) {
10937 if (!v.d || v.e > Decimal.maxE) {
10938
10939 // Infinity.
10940 x.e = NaN;
10941 x.d = null;
10942 } else if (v.e < Decimal.minE) {
10943
10944 // Zero.
10945 x.e = 0;
10946 x.d = [0];
10947 } else {
10948 x.e = v.e;
10949 x.d = v.d.slice();
10950 }
10951 } else {
10952 x.e = v.e;
10953 x.d = v.d ? v.d.slice() : v.d;
10954 }
10955
10956 return;
10957 }
10958
10959 t = typeof v;
10960
10961 if (t === 'number') {
10962 if (v === 0) {
10963 x.s = 1 / v < 0 ? -1 : 1;
10964 x.e = 0;
10965 x.d = [0];
10966 return;
10967 }
10968
10969 if (v < 0) {
10970 v = -v;
10971 x.s = -1;
10972 } else {
10973 x.s = 1;
10974 }
10975
10976 // Fast path for small integers.
10977 if (v === ~~v && v < 1e7) {
10978 for (e = 0, i = v; i >= 10; i /= 10) e++;
10979
10980 if (external) {
10981 if (e > Decimal.maxE) {
10982 x.e = NaN;
10983 x.d = null;
10984 } else if (e < Decimal.minE) {
10985 x.e = 0;
10986 x.d = [0];
10987 } else {
10988 x.e = e;
10989 x.d = [v];
10990 }
10991 } else {
10992 x.e = e;
10993 x.d = [v];
10994 }
10995
10996 return;
10997
10998 // Infinity, NaN.
10999 } else if (v * 0 !== 0) {
11000 if (!v) x.s = NaN;
11001 x.e = NaN;
11002 x.d = null;
11003 return;
11004 }
11005
11006 return parseDecimal(x, v.toString());
11007
11008 } else if (t !== 'string') {
11009 throw Error(invalidArgument + v);
11010 }
11011
11012 // Minus sign?
11013 if ((i = v.charCodeAt(0)) === 45) {
11014 v = v.slice(1);
11015 x.s = -1;
11016 } else {
11017 // Plus sign?
11018 if (i === 43) v = v.slice(1);
11019 x.s = 1;
11020 }
11021
11022 return isDecimal.test(v) ? parseDecimal(x, v) : parseOther(x, v);
11023 }
11024
11025 Decimal.prototype = P;
11026
11027 Decimal.ROUND_UP = 0;
11028 Decimal.ROUND_DOWN = 1;
11029 Decimal.ROUND_CEIL = 2;
11030 Decimal.ROUND_FLOOR = 3;
11031 Decimal.ROUND_HALF_UP = 4;
11032 Decimal.ROUND_HALF_DOWN = 5;
11033 Decimal.ROUND_HALF_EVEN = 6;
11034 Decimal.ROUND_HALF_CEIL = 7;
11035 Decimal.ROUND_HALF_FLOOR = 8;
11036 Decimal.EUCLID = 9;
11037
11038 Decimal.config = Decimal.set = config;
11039 Decimal.clone = clone;
11040 Decimal.isDecimal = isDecimalInstance;
11041
11042 Decimal.abs = abs;
11043 Decimal.acos = acos;
11044 Decimal.acosh = acosh; // ES6
11045 Decimal.add = add;
11046 Decimal.asin = asin;
11047 Decimal.asinh = asinh; // ES6
11048 Decimal.atan = atan;
11049 Decimal.atanh = atanh; // ES6
11050 Decimal.atan2 = atan2;
11051 Decimal.cbrt = cbrt; // ES6
11052 Decimal.ceil = ceil;
11053 Decimal.cos = cos;
11054 Decimal.cosh = cosh; // ES6
11055 Decimal.div = div;
11056 Decimal.exp = exp;
11057 Decimal.floor = floor;
11058 Decimal.hypot = hypot; // ES6
11059 Decimal.ln = ln;
11060 Decimal.log = log;
11061 Decimal.log10 = log10; // ES6
11062 Decimal.log2 = log2; // ES6
11063 Decimal.max = max;
11064 Decimal.min = min;
11065 Decimal.mod = mod;
11066 Decimal.mul = mul;
11067 Decimal.pow = pow;
11068 Decimal.random = random;
11069 Decimal.round = round;
11070 Decimal.sign = sign; // ES6
11071 Decimal.sin = sin;
11072 Decimal.sinh = sinh; // ES6
11073 Decimal.sqrt = sqrt;
11074 Decimal.sub = sub;
11075 Decimal.tan = tan;
11076 Decimal.tanh = tanh; // ES6
11077 Decimal.trunc = trunc; // ES6
11078
11079 if (obj === void 0) obj = {};
11080 if (obj) {
11081 if (obj.defaults !== true) {
11082 ps = ['precision', 'rounding', 'toExpNeg', 'toExpPos', 'maxE', 'minE', 'modulo', 'crypto'];
11083 for (i = 0; i < ps.length;) if (!obj.hasOwnProperty(p = ps[i++])) obj[p] = this[p];
11084 }
11085 }
11086
11087 Decimal.config(obj);
11088
11089 return Decimal;
11090 }
11091
11092
11093 /*
11094 * Return a new Decimal whose value is `x` divided by `y`, rounded to `precision` significant
11095 * digits using rounding mode `rounding`.
11096 *
11097 * x {number|string|Decimal}
11098 * y {number|string|Decimal}
11099 *
11100 */
11101 function div(x, y) {
11102 return new this(x).div(y);
11103 }
11104
11105
11106 /*
11107 * Return a new Decimal whose value is the natural exponential of `x`, rounded to `precision`
11108 * significant digits using rounding mode `rounding`.
11109 *
11110 * x {number|string|Decimal} The power to which to raise the base of the natural log.
11111 *
11112 */
11113 function exp(x) {
11114 return new this(x).exp();
11115 }
11116
11117
11118 /*
11119 * Return a new Decimal whose value is `x` round to an integer using `ROUND_FLOOR`.
11120 *
11121 * x {number|string|Decimal}
11122 *
11123 */
11124 function floor(x) {
11125 return finalise(x = new this(x), x.e + 1, 3);
11126 }
11127
11128
11129 /*
11130 * Return a new Decimal whose value is the square root of the sum of the squares of the arguments,
11131 * rounded to `precision` significant digits using rounding mode `rounding`.
11132 *
11133 * hypot(a, b, ...) = sqrt(a^2 + b^2 + ...)
11134 *
11135 * arguments {number|string|Decimal}
11136 *
11137 */
11138 function hypot() {
11139 var i, n,
11140 t = new this(0);
11141
11142 external = false;
11143
11144 for (i = 0; i < arguments.length;) {
11145 n = new this(arguments[i++]);
11146 if (!n.d) {
11147 if (n.s) {
11148 external = true;
11149 return new this(1 / 0);
11150 }
11151 t = n;
11152 } else if (t.d) {
11153 t = t.plus(n.times(n));
11154 }
11155 }
11156
11157 external = true;
11158
11159 return t.sqrt();
11160 }
11161
11162
11163 /*
11164 * Return true if object is a Decimal instance (where Decimal is any Decimal constructor),
11165 * otherwise return false.
11166 *
11167 */
11168 function isDecimalInstance(obj) {
11169 return obj instanceof Decimal || obj && obj.name === '[object Decimal]' || false;
11170 }
11171
11172
11173 /*
11174 * Return a new Decimal whose value is the natural logarithm of `x`, rounded to `precision`
11175 * significant digits using rounding mode `rounding`.
11176 *
11177 * x {number|string|Decimal}
11178 *
11179 */
11180 function ln(x) {
11181 return new this(x).ln();
11182 }
11183
11184
11185 /*
11186 * Return a new Decimal whose value is the log of `x` to the base `y`, or to base 10 if no base
11187 * is specified, rounded to `precision` significant digits using rounding mode `rounding`.
11188 *
11189 * log[y](x)
11190 *
11191 * x {number|string|Decimal} The argument of the logarithm.
11192 * y {number|string|Decimal} The base of the logarithm.
11193 *
11194 */
11195 function log(x, y) {
11196 return new this(x).log(y);
11197 }
11198
11199
11200 /*
11201 * Return a new Decimal whose value is the base 2 logarithm of `x`, rounded to `precision`
11202 * significant digits using rounding mode `rounding`.
11203 *
11204 * x {number|string|Decimal}
11205 *
11206 */
11207 function log2(x) {
11208 return new this(x).log(2);
11209 }
11210
11211
11212 /*
11213 * Return a new Decimal whose value is the base 10 logarithm of `x`, rounded to `precision`
11214 * significant digits using rounding mode `rounding`.
11215 *
11216 * x {number|string|Decimal}
11217 *
11218 */
11219 function log10(x) {
11220 return new this(x).log(10);
11221 }
11222
11223
11224 /*
11225 * Return a new Decimal whose value is the maximum of the arguments.
11226 *
11227 * arguments {number|string|Decimal}
11228 *
11229 */
11230 function max() {
11231 return maxOrMin(this, arguments, 'lt');
11232 }
11233
11234
11235 /*
11236 * Return a new Decimal whose value is the minimum of the arguments.
11237 *
11238 * arguments {number|string|Decimal}
11239 *
11240 */
11241 function min() {
11242 return maxOrMin(this, arguments, 'gt');
11243 }
11244
11245
11246 /*
11247 * Return a new Decimal whose value is `x` modulo `y`, rounded to `precision` significant digits
11248 * using rounding mode `rounding`.
11249 *
11250 * x {number|string|Decimal}
11251 * y {number|string|Decimal}
11252 *
11253 */
11254 function mod(x, y) {
11255 return new this(x).mod(y);
11256 }
11257
11258
11259 /*
11260 * Return a new Decimal whose value is `x` multiplied by `y`, rounded to `precision` significant
11261 * digits using rounding mode `rounding`.
11262 *
11263 * x {number|string|Decimal}
11264 * y {number|string|Decimal}
11265 *
11266 */
11267 function mul(x, y) {
11268 return new this(x).mul(y);
11269 }
11270
11271
11272 /*
11273 * Return a new Decimal whose value is `x` raised to the power `y`, rounded to precision
11274 * significant digits using rounding mode `rounding`.
11275 *
11276 * x {number|string|Decimal} The base.
11277 * y {number|string|Decimal} The exponent.
11278 *
11279 */
11280 function pow(x, y) {
11281 return new this(x).pow(y);
11282 }
11283
11284
11285 /*
11286 * Returns a new Decimal with a random value equal to or greater than 0 and less than 1, and with
11287 * `sd`, or `Decimal.precision` if `sd` is omitted, significant digits (or less if trailing zeros
11288 * are produced).
11289 *
11290 * [sd] {number} Significant digits. Integer, 0 to MAX_DIGITS inclusive.
11291 *
11292 */
11293 function random(sd) {
11294 var d, e, k, n,
11295 i = 0,
11296 r = new this(1),
11297 rd = [];
11298
11299 if (sd === void 0) sd = this.precision;
11300 else checkInt32(sd, 1, MAX_DIGITS);
11301
11302 k = Math.ceil(sd / LOG_BASE);
11303
11304 if (!this.crypto) {
11305 for (; i < k;) rd[i++] = Math.random() * 1e7 | 0;
11306
11307 // Browsers supporting crypto.getRandomValues.
11308 } else if (crypto.getRandomValues) {
11309 d = crypto.getRandomValues(new Uint32Array(k));
11310
11311 for (; i < k;) {
11312 n = d[i];
11313
11314 // 0 <= n < 4294967296
11315 // Probability n >= 4.29e9, is 4967296 / 4294967296 = 0.00116 (1 in 865).
11316 if (n >= 4.29e9) {
11317 d[i] = crypto.getRandomValues(new Uint32Array(1))[0];
11318 } else {
11319
11320 // 0 <= n <= 4289999999
11321 // 0 <= (n % 1e7) <= 9999999
11322 rd[i++] = n % 1e7;
11323 }
11324 }
11325
11326 // Node.js supporting crypto.randomBytes.
11327 } else if (crypto.randomBytes) {
11328
11329 // buffer
11330 d = crypto.randomBytes(k *= 4);
11331
11332 for (; i < k;) {
11333
11334 // 0 <= n < 2147483648
11335 n = d[i] + (d[i + 1] << 8) + (d[i + 2] << 16) + ((d[i + 3] & 0x7f) << 24);
11336
11337 // Probability n >= 2.14e9, is 7483648 / 2147483648 = 0.0035 (1 in 286).
11338 if (n >= 2.14e9) {
11339 crypto.randomBytes(4).copy(d, i);
11340 } else {
11341
11342 // 0 <= n <= 2139999999
11343 // 0 <= (n % 1e7) <= 9999999
11344 rd.push(n % 1e7);
11345 i += 4;
11346 }
11347 }
11348
11349 i = k / 4;
11350 } else {
11351 throw Error(cryptoUnavailable);
11352 }
11353
11354 k = rd[--i];
11355 sd %= LOG_BASE;
11356
11357 // Convert trailing digits to zeros according to sd.
11358 if (k && sd) {
11359 n = mathpow(10, LOG_BASE - sd);
11360 rd[i] = (k / n | 0) * n;
11361 }
11362
11363 // Remove trailing words which are zero.
11364 for (; rd[i] === 0; i--) rd.pop();
11365
11366 // Zero?
11367 if (i < 0) {
11368 e = 0;
11369 rd = [0];
11370 } else {
11371 e = -1;
11372
11373 // Remove leading words which are zero and adjust exponent accordingly.
11374 for (; rd[0] === 0; e -= LOG_BASE) rd.shift();
11375
11376 // Count the digits of the first word of rd to determine leading zeros.
11377 for (k = 1, n = rd[0]; n >= 10; n /= 10) k++;
11378
11379 // Adjust the exponent for leading zeros of the first word of rd.
11380 if (k < LOG_BASE) e -= LOG_BASE - k;
11381 }
11382
11383 r.e = e;
11384 r.d = rd;
11385
11386 return r;
11387 }
11388
11389
11390 /*
11391 * Return a new Decimal whose value is `x` rounded to an integer using rounding mode `rounding`.
11392 *
11393 * To emulate `Math.round`, set rounding to 7 (ROUND_HALF_CEIL).
11394 *
11395 * x {number|string|Decimal}
11396 *
11397 */
11398 function round(x) {
11399 return finalise(x = new this(x), x.e + 1, this.rounding);
11400 }
11401
11402
11403 /*
11404 * Return
11405 * 1 if x > 0,
11406 * -1 if x < 0,
11407 * 0 if x is 0,
11408 * -0 if x is -0,
11409 * NaN otherwise
11410 *
11411 * x {number|string|Decimal}
11412 *
11413 */
11414 function sign(x) {
11415 x = new this(x);
11416 return x.d ? (x.d[0] ? x.s : 0 * x.s) : x.s || NaN;
11417 }
11418
11419
11420 /*
11421 * Return a new Decimal whose value is the sine of `x`, rounded to `precision` significant digits
11422 * using rounding mode `rounding`.
11423 *
11424 * x {number|string|Decimal} A value in radians.
11425 *
11426 */
11427 function sin(x) {
11428 return new this(x).sin();
11429 }
11430
11431
11432 /*
11433 * Return a new Decimal whose value is the hyperbolic sine of `x`, rounded to `precision`
11434 * significant digits using rounding mode `rounding`.
11435 *
11436 * x {number|string|Decimal} A value in radians.
11437 *
11438 */
11439 function sinh(x) {
11440 return new this(x).sinh();
11441 }
11442
11443
11444 /*
11445 * Return a new Decimal whose value is the square root of `x`, rounded to `precision` significant
11446 * digits using rounding mode `rounding`.
11447 *
11448 * x {number|string|Decimal}
11449 *
11450 */
11451 function sqrt(x) {
11452 return new this(x).sqrt();
11453 }
11454
11455
11456 /*
11457 * Return a new Decimal whose value is `x` minus `y`, rounded to `precision` significant digits
11458 * using rounding mode `rounding`.
11459 *
11460 * x {number|string|Decimal}
11461 * y {number|string|Decimal}
11462 *
11463 */
11464 function sub(x, y) {
11465 return new this(x).sub(y);
11466 }
11467
11468
11469 /*
11470 * Return a new Decimal whose value is the tangent of `x`, rounded to `precision` significant
11471 * digits using rounding mode `rounding`.
11472 *
11473 * x {number|string|Decimal} A value in radians.
11474 *
11475 */
11476 function tan(x) {
11477 return new this(x).tan();
11478 }
11479
11480
11481 /*
11482 * Return a new Decimal whose value is the hyperbolic tangent of `x`, rounded to `precision`
11483 * significant digits using rounding mode `rounding`.
11484 *
11485 * x {number|string|Decimal} A value in radians.
11486 *
11487 */
11488 function tanh(x) {
11489 return new this(x).tanh();
11490 }
11491
11492
11493 /*
11494 * Return a new Decimal whose value is `x` truncated to an integer.
11495 *
11496 * x {number|string|Decimal}
11497 *
11498 */
11499 function trunc(x) {
11500 return finalise(x = new this(x), x.e + 1, 1);
11501 }
11502
11503
11504 // Create and configure initial Decimal constructor.
11505 Decimal = clone(DEFAULTS);
11506
11507 Decimal['default'] = Decimal.Decimal = Decimal;
11508
11509 // Create the internal constants from their string values.
11510 LN10 = new Decimal(LN10);
11511 PI = new Decimal(PI);
11512
11513
11514 // Export.
11515
11516
11517 // AMD.
11518 if (true) {
11519 !(__WEBPACK_AMD_DEFINE_RESULT__ = (function () {
11520 return Decimal;
11521 }).call(exports, __webpack_require__, exports, module),
11522 __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
11523
11524 // Node and other environments that support module.exports.
11525 } else {}
11526})(this);
11527
11528
11529/***/ }),
11530/* 17 */
11531/***/ (function(module, exports, __webpack_require__) {
11532
11533"use strict";
11534
11535
11536// Map the characters to escape to their escaped values. The list is derived
11537// from http://www.cespedes.org/blog/85/how-to-escape-latex-special-characters
11538
11539var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
11540
11541var defaultEscapes = {
11542 "{": "\\{",
11543 "}": "\\}",
11544 "\\": "\\textbackslash{}",
11545 "#": "\\#",
11546 $: "\\$",
11547 "%": "\\%",
11548 "&": "\\&",
11549 "^": "\\textasciicircum{}",
11550 _: "\\_",
11551 "~": "\\textasciitilde{}"
11552};
11553var formatEscapes = {
11554 "\u2013": "\\--",
11555 "\u2014": "\\---",
11556 " ": "~",
11557 "\t": "\\qquad{}",
11558 "\r\n": "\\newline{}",
11559 "\n": "\\newline{}"
11560};
11561
11562var defaultEscapeMapFn = function defaultEscapeMapFn(defaultEscapes, formatEscapes) {
11563 return _extends({}, defaultEscapes, formatEscapes);
11564};
11565
11566/**
11567 * Escape a string to be used in LaTeX documents.
11568 * @param {string} str the string to be escaped.
11569 * @param {boolean} params.preserveFormatting whether formatting escapes should
11570 * be performed (default: false).
11571 * @param {function} params.escapeMapFn the function to modify the escape maps.
11572 * @return {string} the escaped string, ready to be used in LaTeX.
11573 */
11574module.exports = function (str) {
11575 var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
11576 _ref$preserveFormatti = _ref.preserveFormatting,
11577 preserveFormatting = _ref$preserveFormatti === undefined ? false : _ref$preserveFormatti,
11578 _ref$escapeMapFn = _ref.escapeMapFn,
11579 escapeMapFn = _ref$escapeMapFn === undefined ? defaultEscapeMapFn : _ref$escapeMapFn;
11580
11581 var runningStr = String(str);
11582 var result = "";
11583
11584 var escapes = escapeMapFn(_extends({}, defaultEscapes), preserveFormatting ? _extends({}, formatEscapes) : {});
11585 var escapeKeys = Object.keys(escapes); // as it is reused later on
11586
11587 // Algorithm: Go through the string character by character, if it matches
11588 // with one of the special characters then we'll replace it with the escaped
11589 // version.
11590
11591 var _loop = function _loop() {
11592 var specialCharFound = false;
11593 escapeKeys.forEach(function (key, index) {
11594 if (specialCharFound) {
11595 return;
11596 }
11597 if (runningStr.length >= key.length && runningStr.slice(0, key.length) === key) {
11598 result += escapes[escapeKeys[index]];
11599 runningStr = runningStr.slice(key.length, runningStr.length);
11600 specialCharFound = true;
11601 }
11602 });
11603 if (!specialCharFound) {
11604 result += runningStr.slice(0, 1);
11605 runningStr = runningStr.slice(1, runningStr.length);
11606 }
11607 };
11608
11609 while (runningStr) {
11610 _loop();
11611 }
11612 return result;
11613};
11614
11615/***/ }),
11616/* 18 */
11617/***/ (function(module, exports) {
11618
11619function E () {
11620 // Keep this empty so it's easier to inherit from
11621 // (via https://github.com/lipsmack from https://github.com/scottcorgan/tiny-emitter/issues/3)
11622}
11623
11624E.prototype = {
11625 on: function (name, callback, ctx) {
11626 var e = this.e || (this.e = {});
11627
11628 (e[name] || (e[name] = [])).push({
11629 fn: callback,
11630 ctx: ctx
11631 });
11632
11633 return this;
11634 },
11635
11636 once: function (name, callback, ctx) {
11637 var self = this;
11638 function listener () {
11639 self.off(name, listener);
11640 callback.apply(ctx, arguments);
11641 };
11642
11643 listener._ = callback
11644 return this.on(name, listener, ctx);
11645 },
11646
11647 emit: function (name) {
11648 var data = [].slice.call(arguments, 1);
11649 var evtArr = ((this.e || (this.e = {}))[name] || []).slice();
11650 var i = 0;
11651 var len = evtArr.length;
11652
11653 for (i; i < len; i++) {
11654 evtArr[i].fn.apply(evtArr[i].ctx, data);
11655 }
11656
11657 return this;
11658 },
11659
11660 off: function (name, callback) {
11661 var e = this.e || (this.e = {});
11662 var evts = e[name];
11663 var liveEvents = [];
11664
11665 if (evts && callback) {
11666 for (var i = 0, len = evts.length; i < len; i++) {
11667 if (evts[i].fn !== callback && evts[i].fn._ !== callback)
11668 liveEvents.push(evts[i]);
11669 }
11670 }
11671
11672 // Remove event from queue to prevent memory leak
11673 // Suggested by https://github.com/lazd
11674 // Ref: https://github.com/scottcorgan/tiny-emitter/commit/c6ebfaa9bc973b33d110a84a307742b7cf94c953#commitcomment-5024910
11675
11676 (liveEvents.length)
11677 ? e[name] = liveEvents
11678 : delete e[name];
11679
11680 return this;
11681 }
11682};
11683
11684module.exports = E;
11685module.exports.TinyEmitter = E;
11686
11687
11688/***/ }),
11689/* 19 */
11690/***/ (function(module, exports, __webpack_require__) {
11691
11692var all = __webpack_require__(21);
11693
11694var _require = __webpack_require__(22),
11695 create = _require.create;
11696
11697var defaultInstance = create(all); // TODO: not nice having to revert to CommonJS, find an ES6 solution
11698
11699module.exports =
11700/* #__PURE__ */
11701defaultInstance;
11702
11703/***/ }),
11704/* 20 */
11705/***/ (function(module, exports) {
11706
11707var g;
11708
11709// This works in non-strict mode
11710g = (function() {
11711 return this;
11712})();
11713
11714try {
11715 // This works if eval is allowed (see CSP)
11716 g = g || new Function("return this")();
11717} catch (e) {
11718 // This works if the window reference is available
11719 if (typeof window === "object") g = window;
11720}
11721
11722// g can still be undefined, but nothing to do about it...
11723// We return undefined, instead of nothing here, so it's
11724// easier to handle this case. if(!global) { ...}
11725
11726module.exports = g;
11727
11728
11729/***/ }),
11730/* 21 */
11731/***/ (function(module, __webpack_exports__, __webpack_require__) {
11732
11733"use strict";
11734__webpack_require__.r(__webpack_exports__);
11735
11736// EXTERNAL MODULE: ./src/utils/is.js
11737var is = __webpack_require__(1);
11738
11739// EXTERNAL MODULE: ./node_modules/typed-function/typed-function.js
11740var typed_function = __webpack_require__(14);
11741var typed_function_default = /*#__PURE__*/__webpack_require__.n(typed_function);
11742
11743// EXTERNAL MODULE: ./src/utils/number.js
11744var utils_number = __webpack_require__(4);
11745
11746// EXTERNAL MODULE: ./src/utils/factory.js
11747var factory = __webpack_require__(0);
11748
11749// CONCATENATED MODULE: ./src/core/function/typed.js
11750/**
11751 * Create a typed-function which checks the types of the arguments and
11752 * can match them against multiple provided signatures. The typed-function
11753 * automatically converts inputs in order to find a matching signature.
11754 * Typed functions throw informative errors in case of wrong input arguments.
11755 *
11756 * See the library [typed-function](https://github.com/josdejong/typed-function)
11757 * for detailed documentation.
11758 *
11759 * Syntax:
11760 *
11761 * math.typed(name, signatures) : function
11762 * math.typed(signatures) : function
11763 *
11764 * Examples:
11765 *
11766 * // create a typed function with multiple types per argument (type union)
11767 * const fn2 = typed({
11768 * 'number | boolean': function (b) {
11769 * return 'b is a number or boolean'
11770 * },
11771 * 'string, number | boolean': function (a, b) {
11772 * return 'a is a string, b is a number or boolean'
11773 * }
11774 * })
11775 *
11776 * // create a typed function with an any type argument
11777 * const log = typed({
11778 * 'string, any': function (event, data) {
11779 * console.log('event: ' + event + ', data: ' + JSON.stringify(data))
11780 * }
11781 * })
11782 *
11783 * @param {string} [name] Optional name for the typed-function
11784 * @param {Object<string, function>} signatures Object with one or multiple function signatures
11785 * @returns {function} The created typed-function.
11786 */
11787
11788
11789
11790 // returns a new instance of typed-function
11791
11792var _createTyped2 = function _createTyped() {
11793 // initially, return the original instance of typed-function
11794 // consecutively, return a new instance from typed.create.
11795 _createTyped2 = typed_function_default.a.create;
11796 return typed_function_default.a;
11797};
11798
11799var typed_dependencies = ['?BigNumber', '?Complex', '?DenseMatrix', '?Fraction'];
11800/**
11801 * Factory function for creating a new typed instance
11802 * @param {Object} dependencies Object with data types like Complex and BigNumber
11803 * @returns {Function}
11804 */
11805
11806var typed_createTyped =
11807/* #__PURE__ */
11808Object(factory["a" /* factory */])('typed', typed_dependencies, function createTyped(_ref) {
11809 var BigNumber = _ref.BigNumber,
11810 Complex = _ref.Complex,
11811 DenseMatrix = _ref.DenseMatrix,
11812 Fraction = _ref.Fraction;
11813
11814 // TODO: typed-function must be able to silently ignore signatures with unknown data types
11815 // get a new instance of typed-function
11816 var typed = _createTyped2(); // define all types. The order of the types determines in which order function
11817 // arguments are type-checked (so for performance it's important to put the
11818 // most used types first).
11819
11820
11821 typed.types = [{
11822 name: 'number',
11823 test: is["y" /* isNumber */]
11824 }, {
11825 name: 'Complex',
11826 test: is["j" /* isComplex */]
11827 }, {
11828 name: 'BigNumber',
11829 test: is["e" /* isBigNumber */]
11830 }, {
11831 name: 'Fraction',
11832 test: is["o" /* isFraction */]
11833 }, {
11834 name: 'Unit',
11835 test: is["L" /* isUnit */]
11836 }, {
11837 name: 'string',
11838 test: is["I" /* isString */]
11839 }, {
11840 name: 'Chain',
11841 test: is["h" /* isChain */]
11842 }, {
11843 name: 'Array',
11844 test: is["b" /* isArray */]
11845 }, {
11846 name: 'Matrix',
11847 test: is["v" /* isMatrix */]
11848 }, {
11849 name: 'DenseMatrix',
11850 test: is["n" /* isDenseMatrix */]
11851 }, {
11852 name: 'SparseMatrix',
11853 test: is["H" /* isSparseMatrix */]
11854 }, {
11855 name: 'Range',
11856 test: is["D" /* isRange */]
11857 }, {
11858 name: 'Index',
11859 test: is["t" /* isIndex */]
11860 }, {
11861 name: 'boolean',
11862 test: is["g" /* isBoolean */]
11863 }, {
11864 name: 'ResultSet',
11865 test: is["G" /* isResultSet */]
11866 }, {
11867 name: 'Help',
11868 test: is["s" /* isHelp */]
11869 }, {
11870 name: 'function',
11871 test: is["p" /* isFunction */]
11872 }, {
11873 name: 'Date',
11874 test: is["m" /* isDate */]
11875 }, {
11876 name: 'RegExp',
11877 test: is["F" /* isRegExp */]
11878 }, {
11879 name: 'null',
11880 test: is["x" /* isNull */]
11881 }, {
11882 name: 'undefined',
11883 test: is["K" /* isUndefined */]
11884 }, {
11885 name: 'AccessorNode',
11886 test: is["a" /* isAccessorNode */]
11887 }, {
11888 name: 'ArrayNode',
11889 test: is["c" /* isArrayNode */]
11890 }, {
11891 name: 'AssignmentNode',
11892 test: is["d" /* isAssignmentNode */]
11893 }, {
11894 name: 'BlockNode',
11895 test: is["f" /* isBlockNode */]
11896 }, {
11897 name: 'ConditionalNode',
11898 test: is["k" /* isConditionalNode */]
11899 }, {
11900 name: 'ConstantNode',
11901 test: is["l" /* isConstantNode */]
11902 }, {
11903 name: 'FunctionNode',
11904 test: is["r" /* isFunctionNode */]
11905 }, {
11906 name: 'FunctionAssignmentNode',
11907 test: is["q" /* isFunctionAssignmentNode */]
11908 }, {
11909 name: 'IndexNode',
11910 test: is["u" /* isIndexNode */]
11911 }, {
11912 name: 'Node',
11913 test: is["w" /* isNode */]
11914 }, {
11915 name: 'ObjectNode',
11916 test: is["A" /* isObjectNode */]
11917 }, {
11918 name: 'OperatorNode',
11919 test: is["B" /* isOperatorNode */]
11920 }, {
11921 name: 'ParenthesisNode',
11922 test: is["C" /* isParenthesisNode */]
11923 }, {
11924 name: 'RangeNode',
11925 test: is["E" /* isRangeNode */]
11926 }, {
11927 name: 'SymbolNode',
11928 test: is["J" /* isSymbolNode */]
11929 }, {
11930 name: 'Object',
11931 test: is["z" /* isObject */]
11932 } // order 'Object' last, it matches on other classes too
11933 ];
11934 typed.conversions = [{
11935 from: 'number',
11936 to: 'BigNumber',
11937 convert: function convert(x) {
11938 if (!BigNumber) {
11939 throwNoBignumber(x);
11940 } // note: conversion from number to BigNumber can fail if x has >15 digits
11941
11942
11943 if (Object(utils_number["f" /* digits */])(x) > 15) {
11944 throw new TypeError('Cannot implicitly convert a number with >15 significant digits to BigNumber ' + '(value: ' + x + '). ' + 'Use function bignumber(x) to convert to BigNumber.');
11945 }
11946
11947 return new BigNumber(x);
11948 }
11949 }, {
11950 from: 'number',
11951 to: 'Complex',
11952 convert: function convert(x) {
11953 if (!Complex) {
11954 throwNoComplex(x);
11955 }
11956
11957 return new Complex(x, 0);
11958 }
11959 }, {
11960 from: 'number',
11961 to: 'string',
11962 convert: function convert(x) {
11963 return x + '';
11964 }
11965 }, {
11966 from: 'BigNumber',
11967 to: 'Complex',
11968 convert: function convert(x) {
11969 if (!Complex) {
11970 throwNoComplex(x);
11971 }
11972
11973 return new Complex(x.toNumber(), 0);
11974 }
11975 }, {
11976 from: 'Fraction',
11977 to: 'BigNumber',
11978 convert: function convert(x) {
11979 throw new TypeError('Cannot implicitly convert a Fraction to BigNumber or vice versa. ' + 'Use function bignumber(x) to convert to BigNumber or fraction(x) to convert to Fraction.');
11980 }
11981 }, {
11982 from: 'Fraction',
11983 to: 'Complex',
11984 convert: function convert(x) {
11985 if (!Complex) {
11986 throwNoComplex(x);
11987 }
11988
11989 return new Complex(x.valueOf(), 0);
11990 }
11991 }, {
11992 from: 'number',
11993 to: 'Fraction',
11994 convert: function convert(x) {
11995 if (!Fraction) {
11996 throwNoFraction(x);
11997 }
11998
11999 var f = new Fraction(x);
12000
12001 if (f.valueOf() !== x) {
12002 throw new TypeError('Cannot implicitly convert a number to a Fraction when there will be a loss of precision ' + '(value: ' + x + '). ' + 'Use function fraction(x) to convert to Fraction.');
12003 }
12004
12005 return f;
12006 }
12007 }, {
12008 // FIXME: add conversion from Fraction to number, for example for `sqrt(fraction(1,3))`
12009 // from: 'Fraction',
12010 // to: 'number',
12011 // convert: function (x) {
12012 // return x.valueOf()
12013 // }
12014 // }, {
12015 from: 'string',
12016 to: 'number',
12017 convert: function convert(x) {
12018 var n = Number(x);
12019
12020 if (isNaN(n)) {
12021 throw new Error('Cannot convert "' + x + '" to a number');
12022 }
12023
12024 return n;
12025 }
12026 }, {
12027 from: 'string',
12028 to: 'BigNumber',
12029 convert: function convert(x) {
12030 if (!BigNumber) {
12031 throwNoBignumber(x);
12032 }
12033
12034 try {
12035 return new BigNumber(x);
12036 } catch (err) {
12037 throw new Error('Cannot convert "' + x + '" to BigNumber');
12038 }
12039 }
12040 }, {
12041 from: 'string',
12042 to: 'Fraction',
12043 convert: function convert(x) {
12044 if (!Fraction) {
12045 throwNoFraction(x);
12046 }
12047
12048 try {
12049 return new Fraction(x);
12050 } catch (err) {
12051 throw new Error('Cannot convert "' + x + '" to Fraction');
12052 }
12053 }
12054 }, {
12055 from: 'string',
12056 to: 'Complex',
12057 convert: function convert(x) {
12058 if (!Complex) {
12059 throwNoComplex(x);
12060 }
12061
12062 try {
12063 return new Complex(x);
12064 } catch (err) {
12065 throw new Error('Cannot convert "' + x + '" to Complex');
12066 }
12067 }
12068 }, {
12069 from: 'boolean',
12070 to: 'number',
12071 convert: function convert(x) {
12072 return +x;
12073 }
12074 }, {
12075 from: 'boolean',
12076 to: 'BigNumber',
12077 convert: function convert(x) {
12078 if (!BigNumber) {
12079 throwNoBignumber(x);
12080 }
12081
12082 return new BigNumber(+x);
12083 }
12084 }, {
12085 from: 'boolean',
12086 to: 'Fraction',
12087 convert: function convert(x) {
12088 if (!Fraction) {
12089 throwNoFraction(x);
12090 }
12091
12092 return new Fraction(+x);
12093 }
12094 }, {
12095 from: 'boolean',
12096 to: 'string',
12097 convert: function convert(x) {
12098 return String(x);
12099 }
12100 }, {
12101 from: 'Array',
12102 to: 'Matrix',
12103 convert: function convert(array) {
12104 if (!DenseMatrix) {
12105 throwNoMatrix();
12106 }
12107
12108 return new DenseMatrix(array);
12109 }
12110 }, {
12111 from: 'Matrix',
12112 to: 'Array',
12113 convert: function convert(matrix) {
12114 return matrix.valueOf();
12115 }
12116 }];
12117 return typed;
12118});
12119
12120function throwNoBignumber(x) {
12121 throw new Error("Cannot convert value ".concat(x, " into a BigNumber: no class 'BigNumber' provided"));
12122}
12123
12124function throwNoComplex(x) {
12125 throw new Error("Cannot convert value ".concat(x, " into a Complex number: no class 'Complex' provided"));
12126}
12127
12128function throwNoMatrix() {
12129 throw new Error('Cannot convert array into a Matrix: no class \'DenseMatrix\' provided');
12130}
12131
12132function throwNoFraction(x) {
12133 throw new Error("Cannot convert value ".concat(x, " into a Fraction, no class 'Fraction' provided."));
12134}
12135// CONCATENATED MODULE: ./src/type/resultset/ResultSet.js
12136
12137var ResultSet_name = 'ResultSet';
12138var ResultSet_dependencies = [];
12139var createResultSet =
12140/* #__PURE__ */
12141Object(factory["a" /* factory */])(ResultSet_name, ResultSet_dependencies, function () {
12142 /**
12143 * A ResultSet contains a list or results
12144 * @class ResultSet
12145 * @param {Array} entries
12146 * @constructor ResultSet
12147 */
12148 function ResultSet(entries) {
12149 if (!(this instanceof ResultSet)) {
12150 throw new SyntaxError('Constructor must be called with the new operator');
12151 }
12152
12153 this.entries = entries || [];
12154 }
12155 /**
12156 * Attach type information
12157 */
12158
12159
12160 ResultSet.prototype.type = 'ResultSet';
12161 ResultSet.prototype.isResultSet = true;
12162 /**
12163 * Returns the array with results hold by this ResultSet
12164 * @memberof ResultSet
12165 * @returns {Array} entries
12166 */
12167
12168 ResultSet.prototype.valueOf = function () {
12169 return this.entries;
12170 };
12171 /**
12172 * Returns the stringified results of the ResultSet
12173 * @memberof ResultSet
12174 * @returns {string} string
12175 */
12176
12177
12178 ResultSet.prototype.toString = function () {
12179 return '[' + this.entries.join(', ') + ']';
12180 };
12181 /**
12182 * Get a JSON representation of the ResultSet
12183 * @memberof ResultSet
12184 * @returns {Object} Returns a JSON object structured as:
12185 * `{"mathjs": "ResultSet", "entries": [...]}`
12186 */
12187
12188
12189 ResultSet.prototype.toJSON = function () {
12190 return {
12191 mathjs: 'ResultSet',
12192 entries: this.entries
12193 };
12194 };
12195 /**
12196 * Instantiate a ResultSet from a JSON object
12197 * @memberof ResultSet
12198 * @param {Object} json A JSON object structured as:
12199 * `{"mathjs": "ResultSet", "entries": [...]}`
12200 * @return {ResultSet}
12201 */
12202
12203
12204 ResultSet.fromJSON = function (json) {
12205 return new ResultSet(json.entries);
12206 };
12207
12208 return ResultSet;
12209}, {
12210 isClass: true
12211});
12212// EXTERNAL MODULE: ./node_modules/decimal.js/decimal.js
12213var decimal = __webpack_require__(16);
12214var decimal_default = /*#__PURE__*/__webpack_require__.n(decimal);
12215
12216// CONCATENATED MODULE: ./src/type/bignumber/BigNumber.js
12217
12218
12219var BigNumber_name = 'BigNumber';
12220var BigNumber_dependencies = ['?on', 'config'];
12221var createBigNumberClass =
12222/* #__PURE__ */
12223Object(factory["a" /* factory */])(BigNumber_name, BigNumber_dependencies, function (_ref) {
12224 var on = _ref.on,
12225 config = _ref.config;
12226 var BigNumber = decimal_default.a.clone({
12227 precision: config.precision
12228 });
12229 /**
12230 * Attach type information
12231 */
12232
12233 BigNumber.prototype.type = 'BigNumber';
12234 BigNumber.prototype.isBigNumber = true;
12235 /**
12236 * Get a JSON representation of a BigNumber containing
12237 * type information
12238 * @returns {Object} Returns a JSON object structured as:
12239 * `{"mathjs": "BigNumber", "value": "0.2"}`
12240 */
12241
12242 BigNumber.prototype.toJSON = function () {
12243 return {
12244 mathjs: 'BigNumber',
12245 value: this.toString()
12246 };
12247 };
12248 /**
12249 * Instantiate a BigNumber from a JSON object
12250 * @param {Object} json a JSON object structured as:
12251 * `{"mathjs": "BigNumber", "value": "0.2"}`
12252 * @return {BigNumber}
12253 */
12254
12255
12256 BigNumber.fromJSON = function (json) {
12257 return new BigNumber(json.value);
12258 };
12259
12260 if (on) {
12261 // listen for changed in the configuration, automatically apply changed precision
12262 on('config', function (curr, prev) {
12263 if (curr.precision !== prev.precision) {
12264 BigNumber.config({
12265 precision: curr.precision
12266 });
12267 }
12268 });
12269 }
12270
12271 return BigNumber;
12272}, {
12273 isClass: true
12274});
12275// EXTERNAL MODULE: ./node_modules/complex.js/complex.js
12276var complex_js_complex = __webpack_require__(9);
12277var complex_default = /*#__PURE__*/__webpack_require__.n(complex_js_complex);
12278
12279// CONCATENATED MODULE: ./src/type/complex/Complex.js
12280function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
12281
12282
12283
12284
12285
12286var Complex_name = 'Complex';
12287var Complex_dependencies = [];
12288var createComplexClass =
12289/* #__PURE__ */
12290Object(factory["a" /* factory */])(Complex_name, Complex_dependencies, function () {
12291 /**
12292 * Attach type information
12293 */
12294 complex_default.a.prototype.type = 'Complex';
12295 complex_default.a.prototype.isComplex = true;
12296 /**
12297 * Get a JSON representation of the complex number
12298 * @returns {Object} Returns a JSON object structured as:
12299 * `{"mathjs": "Complex", "re": 2, "im": 3}`
12300 */
12301
12302 complex_default.a.prototype.toJSON = function () {
12303 return {
12304 mathjs: 'Complex',
12305 re: this.re,
12306 im: this.im
12307 };
12308 };
12309 /*
12310 * Return the value of the complex number in polar notation
12311 * The angle phi will be set in the interval of [-pi, pi].
12312 * @return {{r: number, phi: number}} Returns and object with properties r and phi.
12313 */
12314
12315
12316 complex_default.a.prototype.toPolar = function () {
12317 return {
12318 r: this.abs(),
12319 phi: this.arg()
12320 };
12321 };
12322 /**
12323 * Get a string representation of the complex number,
12324 * with optional formatting options.
12325 * @param {Object | number | Function} [options] Formatting options. See
12326 * lib/utils/number:format for a
12327 * description of the available
12328 * options.
12329 * @return {string} str
12330 */
12331
12332
12333 complex_default.a.prototype.format = function (options) {
12334 var str = '';
12335 var im = this.im;
12336 var re = this.re;
12337 var strRe = Object(utils_number["h" /* format */])(this.re, options);
12338 var strIm = Object(utils_number["h" /* format */])(this.im, options); // round either re or im when smaller than the configured precision
12339
12340 var precision = Object(is["y" /* isNumber */])(options) ? options : options ? options.precision : null;
12341
12342 if (precision !== null) {
12343 var epsilon = Math.pow(10, -precision);
12344
12345 if (Math.abs(re / im) < epsilon) {
12346 re = 0;
12347 }
12348
12349 if (Math.abs(im / re) < epsilon) {
12350 im = 0;
12351 }
12352 }
12353
12354 if (im === 0) {
12355 // real value
12356 str = strRe;
12357 } else if (re === 0) {
12358 // purely complex value
12359 if (im === 1) {
12360 str = 'i';
12361 } else if (im === -1) {
12362 str = '-i';
12363 } else {
12364 str = strIm + 'i';
12365 }
12366 } else {
12367 // complex value
12368 if (im < 0) {
12369 if (im === -1) {
12370 str = strRe + ' - i';
12371 } else {
12372 str = strRe + ' - ' + strIm.substring(1) + 'i';
12373 }
12374 } else {
12375 if (im === 1) {
12376 str = strRe + ' + i';
12377 } else {
12378 str = strRe + ' + ' + strIm + 'i';
12379 }
12380 }
12381 }
12382
12383 return str;
12384 };
12385 /**
12386 * Create a complex number from polar coordinates
12387 *
12388 * Usage:
12389 *
12390 * Complex.fromPolar(r: number, phi: number) : Complex
12391 * Complex.fromPolar({r: number, phi: number}) : Complex
12392 *
12393 * @param {*} args...
12394 * @return {Complex}
12395 */
12396
12397
12398 complex_default.a.fromPolar = function (args) {
12399 switch (arguments.length) {
12400 case 1:
12401 {
12402 var arg = arguments[0];
12403
12404 if (_typeof(arg) === 'object') {
12405 return complex_default()(arg);
12406 } else {
12407 throw new TypeError('Input has to be an object with r and phi keys.');
12408 }
12409 }
12410
12411 case 2:
12412 {
12413 var r = arguments[0];
12414 var phi = arguments[1];
12415
12416 if (Object(is["y" /* isNumber */])(r)) {
12417 if (Object(is["L" /* isUnit */])(phi) && phi.hasBase('ANGLE')) {
12418 // convert unit to a number in radians
12419 phi = phi.toNumber('rad');
12420 }
12421
12422 if (Object(is["y" /* isNumber */])(phi)) {
12423 return new complex_default.a({
12424 r: r,
12425 phi: phi
12426 });
12427 }
12428
12429 throw new TypeError('Phi is not a number nor an angle unit.');
12430 } else {
12431 throw new TypeError('Radius r is not a number.');
12432 }
12433 }
12434
12435 default:
12436 throw new SyntaxError('Wrong number of arguments in function fromPolar');
12437 }
12438 };
12439
12440 complex_default.a.prototype.valueOf = complex_default.a.prototype.toString;
12441 /**
12442 * Create a Complex number from a JSON object
12443 * @param {Object} json A JSON Object structured as
12444 * {"mathjs": "Complex", "re": 2, "im": 3}
12445 * All properties are optional, default values
12446 * for `re` and `im` are 0.
12447 * @return {Complex} Returns a new Complex number
12448 */
12449
12450 complex_default.a.fromJSON = function (json) {
12451 return new complex_default.a(json);
12452 };
12453 /**
12454 * Compare two complex numbers, `a` and `b`:
12455 *
12456 * - Returns 1 when the real part of `a` is larger than the real part of `b`
12457 * - Returns -1 when the real part of `a` is smaller than the real part of `b`
12458 * - Returns 1 when the real parts are equal
12459 * and the imaginary part of `a` is larger than the imaginary part of `b`
12460 * - Returns -1 when the real parts are equal
12461 * and the imaginary part of `a` is smaller than the imaginary part of `b`
12462 * - Returns 0 when both real and imaginary parts are equal.
12463 *
12464 * @params {Complex} a
12465 * @params {Complex} b
12466 * @returns {number} Returns the comparison result: -1, 0, or 1
12467 */
12468
12469
12470 complex_default.a.compare = function (a, b) {
12471 if (a.re > b.re) {
12472 return 1;
12473 }
12474
12475 if (a.re < b.re) {
12476 return -1;
12477 }
12478
12479 if (a.im > b.im) {
12480 return 1;
12481 }
12482
12483 if (a.im < b.im) {
12484 return -1;
12485 }
12486
12487 return 0;
12488 };
12489
12490 return complex_default.a;
12491}, {
12492 isClass: true
12493});
12494// EXTERNAL MODULE: ./node_modules/fraction.js/fraction.js
12495var fraction_js_fraction = __webpack_require__(11);
12496var fraction_default = /*#__PURE__*/__webpack_require__.n(fraction_js_fraction);
12497
12498// CONCATENATED MODULE: ./src/type/fraction/Fraction.js
12499
12500
12501var Fraction_name = 'Fraction';
12502var Fraction_dependencies = [];
12503var createFractionClass =
12504/* #__PURE__ */
12505Object(factory["a" /* factory */])(Fraction_name, Fraction_dependencies, function () {
12506 /**
12507 * Attach type information
12508 */
12509 fraction_default.a.prototype.type = 'Fraction';
12510 fraction_default.a.prototype.isFraction = true;
12511 /**
12512 * Get a JSON representation of a Fraction containing type information
12513 * @returns {Object} Returns a JSON object structured as:
12514 * `{"mathjs": "Fraction", "n": 3, "d": 8}`
12515 */
12516
12517 fraction_default.a.prototype.toJSON = function () {
12518 return {
12519 mathjs: 'Fraction',
12520 n: this.s * this.n,
12521 d: this.d
12522 };
12523 };
12524 /**
12525 * Instantiate a Fraction from a JSON object
12526 * @param {Object} json a JSON object structured as:
12527 * `{"mathjs": "Fraction", "n": 3, "d": 8}`
12528 * @return {BigNumber}
12529 */
12530
12531
12532 fraction_default.a.fromJSON = function (json) {
12533 return new fraction_default.a(json);
12534 };
12535
12536 return fraction_default.a;
12537}, {
12538 isClass: true
12539});
12540// CONCATENATED MODULE: ./src/type/matrix/Range.js
12541
12542
12543
12544var Range_name = 'Range';
12545var Range_dependencies = [];
12546var createRangeClass =
12547/* #__PURE__ */
12548Object(factory["a" /* factory */])(Range_name, Range_dependencies, function () {
12549 /**
12550 * Create a range. A range has a start, step, and end, and contains functions
12551 * to iterate over the range.
12552 *
12553 * A range can be constructed as:
12554 *
12555 * const range = new Range(start, end)
12556 * const range = new Range(start, end, step)
12557 *
12558 * To get the result of the range:
12559 * range.forEach(function (x) {
12560 * console.log(x)
12561 * })
12562 * range.map(function (x) {
12563 * return math.sin(x)
12564 * })
12565 * range.toArray()
12566 *
12567 * Example usage:
12568 *
12569 * const c = new Range(2, 6) // 2:1:5
12570 * c.toArray() // [2, 3, 4, 5]
12571 * const d = new Range(2, -3, -1) // 2:-1:-2
12572 * d.toArray() // [2, 1, 0, -1, -2]
12573 *
12574 * @class Range
12575 * @constructor Range
12576 * @param {number} start included lower bound
12577 * @param {number} end excluded upper bound
12578 * @param {number} [step] step size, default value is 1
12579 */
12580 function Range(start, end, step) {
12581 if (!(this instanceof Range)) {
12582 throw new SyntaxError('Constructor must be called with the new operator');
12583 }
12584
12585 var hasStart = start !== null && start !== undefined;
12586 var hasEnd = end !== null && end !== undefined;
12587 var hasStep = step !== null && step !== undefined;
12588
12589 if (hasStart) {
12590 if (Object(is["e" /* isBigNumber */])(start)) {
12591 start = start.toNumber();
12592 } else if (typeof start !== 'number') {
12593 throw new TypeError('Parameter start must be a number');
12594 }
12595 }
12596
12597 if (hasEnd) {
12598 if (Object(is["e" /* isBigNumber */])(end)) {
12599 end = end.toNumber();
12600 } else if (typeof end !== 'number') {
12601 throw new TypeError('Parameter end must be a number');
12602 }
12603 }
12604
12605 if (hasStep) {
12606 if (Object(is["e" /* isBigNumber */])(step)) {
12607 step = step.toNumber();
12608 } else if (typeof step !== 'number') {
12609 throw new TypeError('Parameter step must be a number');
12610 }
12611 }
12612
12613 this.start = hasStart ? parseFloat(start) : 0;
12614 this.end = hasEnd ? parseFloat(end) : 0;
12615 this.step = hasStep ? parseFloat(step) : 1;
12616 }
12617 /**
12618 * Attach type information
12619 */
12620
12621
12622 Range.prototype.type = 'Range';
12623 Range.prototype.isRange = true;
12624 /**
12625 * Parse a string into a range,
12626 * The string contains the start, optional step, and end, separated by a colon.
12627 * If the string does not contain a valid range, null is returned.
12628 * For example str='0:2:11'.
12629 * @memberof Range
12630 * @param {string} str
12631 * @return {Range | null} range
12632 */
12633
12634 Range.parse = function (str) {
12635 if (typeof str !== 'string') {
12636 return null;
12637 }
12638
12639 var args = str.split(':');
12640 var nums = args.map(function (arg) {
12641 return parseFloat(arg);
12642 });
12643 var invalid = nums.some(function (num) {
12644 return isNaN(num);
12645 });
12646
12647 if (invalid) {
12648 return null;
12649 }
12650
12651 switch (nums.length) {
12652 case 2:
12653 return new Range(nums[0], nums[1]);
12654
12655 case 3:
12656 return new Range(nums[0], nums[2], nums[1]);
12657
12658 default:
12659 return null;
12660 }
12661 };
12662 /**
12663 * Create a clone of the range
12664 * @return {Range} clone
12665 */
12666
12667
12668 Range.prototype.clone = function () {
12669 return new Range(this.start, this.end, this.step);
12670 };
12671 /**
12672 * Retrieve the size of the range.
12673 * Returns an array containing one number, the number of elements in the range.
12674 * @memberof Range
12675 * @returns {number[]} size
12676 */
12677
12678
12679 Range.prototype.size = function () {
12680 var len = 0;
12681 var start = this.start;
12682 var step = this.step;
12683 var end = this.end;
12684 var diff = end - start;
12685
12686 if (Object(utils_number["n" /* sign */])(step) === Object(utils_number["n" /* sign */])(diff)) {
12687 len = Math.ceil(diff / step);
12688 } else if (diff === 0) {
12689 len = 0;
12690 }
12691
12692 if (isNaN(len)) {
12693 len = 0;
12694 }
12695
12696 return [len];
12697 };
12698 /**
12699 * Calculate the minimum value in the range
12700 * @memberof Range
12701 * @return {number | undefined} min
12702 */
12703
12704
12705 Range.prototype.min = function () {
12706 var size = this.size()[0];
12707
12708 if (size > 0) {
12709 if (this.step > 0) {
12710 // positive step
12711 return this.start;
12712 } else {
12713 // negative step
12714 return this.start + (size - 1) * this.step;
12715 }
12716 } else {
12717 return undefined;
12718 }
12719 };
12720 /**
12721 * Calculate the maximum value in the range
12722 * @memberof Range
12723 * @return {number | undefined} max
12724 */
12725
12726
12727 Range.prototype.max = function () {
12728 var size = this.size()[0];
12729
12730 if (size > 0) {
12731 if (this.step > 0) {
12732 // positive step
12733 return this.start + (size - 1) * this.step;
12734 } else {
12735 // negative step
12736 return this.start;
12737 }
12738 } else {
12739 return undefined;
12740 }
12741 };
12742 /**
12743 * Execute a callback function for each value in the range.
12744 * @memberof Range
12745 * @param {function} callback The callback method is invoked with three
12746 * parameters: the value of the element, the index
12747 * of the element, and the Range being traversed.
12748 */
12749
12750
12751 Range.prototype.forEach = function (callback) {
12752 var x = this.start;
12753 var step = this.step;
12754 var end = this.end;
12755 var i = 0;
12756
12757 if (step > 0) {
12758 while (x < end) {
12759 callback(x, [i], this);
12760 x += step;
12761 i++;
12762 }
12763 } else if (step < 0) {
12764 while (x > end) {
12765 callback(x, [i], this);
12766 x += step;
12767 i++;
12768 }
12769 }
12770 };
12771 /**
12772 * Execute a callback function for each value in the Range, and return the
12773 * results as an array
12774 * @memberof Range
12775 * @param {function} callback The callback method is invoked with three
12776 * parameters: the value of the element, the index
12777 * of the element, and the Matrix being traversed.
12778 * @returns {Array} array
12779 */
12780
12781
12782 Range.prototype.map = function (callback) {
12783 var array = [];
12784 this.forEach(function (value, index, obj) {
12785 array[index[0]] = callback(value, index, obj);
12786 });
12787 return array;
12788 };
12789 /**
12790 * Create an Array with a copy of the Ranges data
12791 * @memberof Range
12792 * @returns {Array} array
12793 */
12794
12795
12796 Range.prototype.toArray = function () {
12797 var array = [];
12798 this.forEach(function (value, index) {
12799 array[index[0]] = value;
12800 });
12801 return array;
12802 };
12803 /**
12804 * Get the primitive value of the Range, a one dimensional array
12805 * @memberof Range
12806 * @returns {Array} array
12807 */
12808
12809
12810 Range.prototype.valueOf = function () {
12811 // TODO: implement a caching mechanism for range.valueOf()
12812 return this.toArray();
12813 };
12814 /**
12815 * Get a string representation of the range, with optional formatting options.
12816 * Output is formatted as 'start:step:end', for example '2:6' or '0:0.2:11'
12817 * @memberof Range
12818 * @param {Object | number | function} [options] Formatting options. See
12819 * lib/utils/number:format for a
12820 * description of the available
12821 * options.
12822 * @returns {string} str
12823 */
12824
12825
12826 Range.prototype.format = function (options) {
12827 var str = Object(utils_number["h" /* format */])(this.start, options);
12828
12829 if (this.step !== 1) {
12830 str += ':' + Object(utils_number["h" /* format */])(this.step, options);
12831 }
12832
12833 str += ':' + Object(utils_number["h" /* format */])(this.end, options);
12834 return str;
12835 };
12836 /**
12837 * Get a string representation of the range.
12838 * @memberof Range
12839 * @returns {string}
12840 */
12841
12842
12843 Range.prototype.toString = function () {
12844 return this.format();
12845 };
12846 /**
12847 * Get a JSON representation of the range
12848 * @memberof Range
12849 * @returns {Object} Returns a JSON object structured as:
12850 * `{"mathjs": "Range", "start": 2, "end": 4, "step": 1}`
12851 */
12852
12853
12854 Range.prototype.toJSON = function () {
12855 return {
12856 mathjs: 'Range',
12857 start: this.start,
12858 end: this.end,
12859 step: this.step
12860 };
12861 };
12862 /**
12863 * Instantiate a Range from a JSON object
12864 * @memberof Range
12865 * @param {Object} json A JSON object structured as:
12866 * `{"mathjs": "Range", "start": 2, "end": 4, "step": 1}`
12867 * @return {Range}
12868 */
12869
12870
12871 Range.fromJSON = function (json) {
12872 return new Range(json.start, json.end, json.step);
12873 };
12874
12875 return Range;
12876}, {
12877 isClass: true
12878});
12879// CONCATENATED MODULE: ./src/type/matrix/Matrix.js
12880
12881var Matrix_name = 'Matrix';
12882var Matrix_dependencies = [];
12883var createMatrixClass =
12884/* #__PURE__ */
12885Object(factory["a" /* factory */])(Matrix_name, Matrix_dependencies, function () {
12886 /**
12887 * @constructor Matrix
12888 *
12889 * A Matrix is a wrapper around an Array. A matrix can hold a multi dimensional
12890 * array. A matrix can be constructed as:
12891 *
12892 * let matrix = math.matrix(data)
12893 *
12894 * Matrix contains the functions to resize, get and set values, get the size,
12895 * clone the matrix and to convert the matrix to a vector, array, or scalar.
12896 * Furthermore, one can iterate over the matrix using map and forEach.
12897 * The internal Array of the Matrix can be accessed using the function valueOf.
12898 *
12899 * Example usage:
12900 *
12901 * let matrix = math.matrix([[1, 2], [3, 4]])
12902 * matix.size() // [2, 2]
12903 * matrix.resize([3, 2], 5)
12904 * matrix.valueOf() // [[1, 2], [3, 4], [5, 5]]
12905 * matrix.subset([1,2]) // 3 (indexes are zero-based)
12906 *
12907 */
12908 function Matrix() {
12909 if (!(this instanceof Matrix)) {
12910 throw new SyntaxError('Constructor must be called with the new operator');
12911 }
12912 }
12913 /**
12914 * Attach type information
12915 */
12916
12917
12918 Matrix.prototype.type = 'Matrix';
12919 Matrix.prototype.isMatrix = true;
12920 /**
12921 * Get the Matrix storage constructor for the given format.
12922 *
12923 * @param {string} format The Matrix storage format.
12924 *
12925 * @return {Function} The Matrix storage constructor.
12926 */
12927
12928 Matrix.storage = function (format) {
12929 // TODO: deprecated since v6.0.0. Clean up some day
12930 throw new Error('Matrix.storage is deprecated since v6.0.0. ' + 'Use the factory function math.matrix instead.');
12931 };
12932 /**
12933 * Get the storage format used by the matrix.
12934 *
12935 * Usage:
12936 * const format = matrix.storage() // retrieve storage format
12937 *
12938 * @return {string} The storage format.
12939 */
12940
12941
12942 Matrix.prototype.storage = function () {
12943 // must be implemented by each of the Matrix implementations
12944 throw new Error('Cannot invoke storage on a Matrix interface');
12945 };
12946 /**
12947 * Get the datatype of the data stored in the matrix.
12948 *
12949 * Usage:
12950 * const format = matrix.datatype() // retrieve matrix datatype
12951 *
12952 * @return {string} The datatype.
12953 */
12954
12955
12956 Matrix.prototype.datatype = function () {
12957 // must be implemented by each of the Matrix implementations
12958 throw new Error('Cannot invoke datatype on a Matrix interface');
12959 };
12960 /**
12961 * Create a new Matrix With the type of the current matrix instance
12962 * @param {Array | Object} data
12963 * @param {string} [datatype]
12964 */
12965
12966
12967 Matrix.prototype.create = function (data, datatype) {
12968 throw new Error('Cannot invoke create on a Matrix interface');
12969 };
12970 /**
12971 * Get a subset of the matrix, or replace a subset of the matrix.
12972 *
12973 * Usage:
12974 * const subset = matrix.subset(index) // retrieve subset
12975 * const value = matrix.subset(index, replacement) // replace subset
12976 *
12977 * @param {Index} index
12978 * @param {Array | Matrix | *} [replacement]
12979 * @param {*} [defaultValue=0] Default value, filled in on new entries when
12980 * the matrix is resized. If not provided,
12981 * new matrix elements will be filled with zeros.
12982 */
12983
12984
12985 Matrix.prototype.subset = function (index, replacement, defaultValue) {
12986 // must be implemented by each of the Matrix implementations
12987 throw new Error('Cannot invoke subset on a Matrix interface');
12988 };
12989 /**
12990 * Get a single element from the matrix.
12991 * @param {number[]} index Zero-based index
12992 * @return {*} value
12993 */
12994
12995
12996 Matrix.prototype.get = function (index) {
12997 // must be implemented by each of the Matrix implementations
12998 throw new Error('Cannot invoke get on a Matrix interface');
12999 };
13000 /**
13001 * Replace a single element in the matrix.
13002 * @param {number[]} index Zero-based index
13003 * @param {*} value
13004 * @param {*} [defaultValue] Default value, filled in on new entries when
13005 * the matrix is resized. If not provided,
13006 * new matrix elements will be left undefined.
13007 * @return {Matrix} self
13008 */
13009
13010
13011 Matrix.prototype.set = function (index, value, defaultValue) {
13012 // must be implemented by each of the Matrix implementations
13013 throw new Error('Cannot invoke set on a Matrix interface');
13014 };
13015 /**
13016 * Resize the matrix to the given size. Returns a copy of the matrix when
13017 * `copy=true`, otherwise return the matrix itself (resize in place).
13018 *
13019 * @param {number[]} size The new size the matrix should have.
13020 * @param {*} [defaultValue=0] Default value, filled in on new entries.
13021 * If not provided, the matrix elements will
13022 * be filled with zeros.
13023 * @param {boolean} [copy] Return a resized copy of the matrix
13024 *
13025 * @return {Matrix} The resized matrix
13026 */
13027
13028
13029 Matrix.prototype.resize = function (size, defaultValue) {
13030 // must be implemented by each of the Matrix implementations
13031 throw new Error('Cannot invoke resize on a Matrix interface');
13032 };
13033 /**
13034 * Reshape the matrix to the given size. Returns a copy of the matrix when
13035 * `copy=true`, otherwise return the matrix itself (reshape in place).
13036 *
13037 * @param {number[]} size The new size the matrix should have.
13038 * @param {boolean} [copy] Return a reshaped copy of the matrix
13039 *
13040 * @return {Matrix} The reshaped matrix
13041 */
13042
13043
13044 Matrix.prototype.reshape = function (size, defaultValue) {
13045 // must be implemented by each of the Matrix implementations
13046 throw new Error('Cannot invoke reshape on a Matrix interface');
13047 };
13048 /**
13049 * Create a clone of the matrix
13050 * @return {Matrix} clone
13051 */
13052
13053
13054 Matrix.prototype.clone = function () {
13055 // must be implemented by each of the Matrix implementations
13056 throw new Error('Cannot invoke clone on a Matrix interface');
13057 };
13058 /**
13059 * Retrieve the size of the matrix.
13060 * @returns {number[]} size
13061 */
13062
13063
13064 Matrix.prototype.size = function () {
13065 // must be implemented by each of the Matrix implementations
13066 throw new Error('Cannot invoke size on a Matrix interface');
13067 };
13068 /**
13069 * Create a new matrix with the results of the callback function executed on
13070 * each entry of the matrix.
13071 * @param {Function} callback The callback function is invoked with three
13072 * parameters: the value of the element, the index
13073 * of the element, and the Matrix being traversed.
13074 * @param {boolean} [skipZeros] Invoke callback function for non-zero values only.
13075 *
13076 * @return {Matrix} matrix
13077 */
13078
13079
13080 Matrix.prototype.map = function (callback, skipZeros) {
13081 // must be implemented by each of the Matrix implementations
13082 throw new Error('Cannot invoke map on a Matrix interface');
13083 };
13084 /**
13085 * Execute a callback function on each entry of the matrix.
13086 * @param {Function} callback The callback function is invoked with three
13087 * parameters: the value of the element, the index
13088 * of the element, and the Matrix being traversed.
13089 */
13090
13091
13092 Matrix.prototype.forEach = function (callback) {
13093 // must be implemented by each of the Matrix implementations
13094 throw new Error('Cannot invoke forEach on a Matrix interface');
13095 };
13096 /**
13097 * Create an Array with a copy of the data of the Matrix
13098 * @returns {Array} array
13099 */
13100
13101
13102 Matrix.prototype.toArray = function () {
13103 // must be implemented by each of the Matrix implementations
13104 throw new Error('Cannot invoke toArray on a Matrix interface');
13105 };
13106 /**
13107 * Get the primitive value of the Matrix: a multidimensional array
13108 * @returns {Array} array
13109 */
13110
13111
13112 Matrix.prototype.valueOf = function () {
13113 // must be implemented by each of the Matrix implementations
13114 throw new Error('Cannot invoke valueOf on a Matrix interface');
13115 };
13116 /**
13117 * Get a string representation of the matrix, with optional formatting options.
13118 * @param {Object | number | Function} [options] Formatting options. See
13119 * lib/utils/number:format for a
13120 * description of the available
13121 * options.
13122 * @returns {string} str
13123 */
13124
13125
13126 Matrix.prototype.format = function (options) {
13127 // must be implemented by each of the Matrix implementations
13128 throw new Error('Cannot invoke format on a Matrix interface');
13129 };
13130 /**
13131 * Get a string representation of the matrix
13132 * @returns {string} str
13133 */
13134
13135
13136 Matrix.prototype.toString = function () {
13137 // must be implemented by each of the Matrix implementations
13138 throw new Error('Cannot invoke toString on a Matrix interface');
13139 };
13140
13141 return Matrix;
13142}, {
13143 isClass: true
13144});
13145// EXTERNAL MODULE: ./src/utils/array.js
13146var utils_array = __webpack_require__(2);
13147
13148// EXTERNAL MODULE: ./src/utils/string.js + 1 modules
13149var utils_string = __webpack_require__(5);
13150
13151// EXTERNAL MODULE: ./src/utils/object.js
13152var utils_object = __webpack_require__(3);
13153
13154// EXTERNAL MODULE: ./src/error/DimensionError.js
13155var DimensionError = __webpack_require__(6);
13156
13157// CONCATENATED MODULE: ./src/type/matrix/DenseMatrix.js
13158
13159
13160
13161
13162
13163
13164
13165var DenseMatrix_name = 'DenseMatrix';
13166var DenseMatrix_dependencies = ['Matrix'];
13167var createDenseMatrixClass =
13168/* #__PURE__ */
13169Object(factory["a" /* factory */])(DenseMatrix_name, DenseMatrix_dependencies, function (_ref) {
13170 var Matrix = _ref.Matrix;
13171
13172 /**
13173 * Dense Matrix implementation. A regular, dense matrix, supporting multi-dimensional matrices. This is the default matrix type.
13174 * @class DenseMatrix
13175 */
13176 function DenseMatrix(data, datatype) {
13177 if (!(this instanceof DenseMatrix)) {
13178 throw new SyntaxError('Constructor must be called with the new operator');
13179 }
13180
13181 if (datatype && !Object(is["I" /* isString */])(datatype)) {
13182 throw new Error('Invalid datatype: ' + datatype);
13183 }
13184
13185 if (Object(is["v" /* isMatrix */])(data)) {
13186 // check data is a DenseMatrix
13187 if (data.type === 'DenseMatrix') {
13188 // clone data & size
13189 this._data = Object(utils_object["a" /* clone */])(data._data);
13190 this._size = Object(utils_object["a" /* clone */])(data._size);
13191 this._datatype = datatype || data._datatype;
13192 } else {
13193 // build data from existing matrix
13194 this._data = data.toArray();
13195 this._size = data.size();
13196 this._datatype = datatype || data._datatype;
13197 }
13198 } else if (data && Object(is["b" /* isArray */])(data.data) && Object(is["b" /* isArray */])(data.size)) {
13199 // initialize fields from JSON representation
13200 this._data = data.data;
13201 this._size = data.size;
13202 this._datatype = datatype || data.datatype;
13203 } else if (Object(is["b" /* isArray */])(data)) {
13204 // replace nested Matrices with Arrays
13205 this._data = preprocess(data); // get the dimensions of the array
13206
13207 this._size = Object(utils_array["a" /* arraySize */])(this._data); // verify the dimensions of the array, TODO: compute size while processing array
13208
13209 Object(utils_array["r" /* validate */])(this._data, this._size); // data type unknown
13210
13211 this._datatype = datatype;
13212 } else if (data) {
13213 // unsupported type
13214 throw new TypeError('Unsupported type of data (' + Object(is["M" /* typeOf */])(data) + ')');
13215 } else {
13216 // nothing provided
13217 this._data = [];
13218 this._size = [0];
13219 this._datatype = datatype;
13220 }
13221 }
13222
13223 DenseMatrix.prototype = new Matrix();
13224 /**
13225 * Create a new DenseMatrix
13226 */
13227
13228 DenseMatrix.prototype.createDenseMatrix = function (data, datatype) {
13229 return new DenseMatrix(data, datatype);
13230 };
13231 /**
13232 * Attach type information
13233 */
13234
13235
13236 DenseMatrix.prototype.type = 'DenseMatrix';
13237 DenseMatrix.prototype.isDenseMatrix = true;
13238 /**
13239 * Get the matrix type
13240 *
13241 * Usage:
13242 * const matrixType = matrix.getDataType() // retrieves the matrix type
13243 *
13244 * @memberOf DenseMatrix
13245 * @return {string} type information; if multiple types are found from the Matrix, it will return "mixed"
13246 */
13247
13248 DenseMatrix.prototype.getDataType = function () {
13249 return Object(utils_array["h" /* getArrayDataType */])(this._data, is["M" /* typeOf */]);
13250 };
13251 /**
13252 * Get the storage format used by the matrix.
13253 *
13254 * Usage:
13255 * const format = matrix.storage() // retrieve storage format
13256 *
13257 * @memberof DenseMatrix
13258 * @return {string} The storage format.
13259 */
13260
13261
13262 DenseMatrix.prototype.storage = function () {
13263 return 'dense';
13264 };
13265 /**
13266 * Get the datatype of the data stored in the matrix.
13267 *
13268 * Usage:
13269 * const format = matrix.datatype() // retrieve matrix datatype
13270 *
13271 * @memberof DenseMatrix
13272 * @return {string} The datatype.
13273 */
13274
13275
13276 DenseMatrix.prototype.datatype = function () {
13277 return this._datatype;
13278 };
13279 /**
13280 * Create a new DenseMatrix
13281 * @memberof DenseMatrix
13282 * @param {Array} data
13283 * @param {string} [datatype]
13284 */
13285
13286
13287 DenseMatrix.prototype.create = function (data, datatype) {
13288 return new DenseMatrix(data, datatype);
13289 };
13290 /**
13291 * Get a subset of the matrix, or replace a subset of the matrix.
13292 *
13293 * Usage:
13294 * const subset = matrix.subset(index) // retrieve subset
13295 * const value = matrix.subset(index, replacement) // replace subset
13296 *
13297 * @memberof DenseMatrix
13298 * @param {Index} index
13299 * @param {Array | Matrix | *} [replacement]
13300 * @param {*} [defaultValue=0] Default value, filled in on new entries when
13301 * the matrix is resized. If not provided,
13302 * new matrix elements will be filled with zeros.
13303 */
13304
13305
13306 DenseMatrix.prototype.subset = function (index, replacement, defaultValue) {
13307 switch (arguments.length) {
13308 case 1:
13309 return _get(this, index);
13310 // intentional fall through
13311
13312 case 2:
13313 case 3:
13314 return _set(this, index, replacement, defaultValue);
13315
13316 default:
13317 throw new SyntaxError('Wrong number of arguments');
13318 }
13319 };
13320 /**
13321 * Get a single element from the matrix.
13322 * @memberof DenseMatrix
13323 * @param {number[]} index Zero-based index
13324 * @return {*} value
13325 */
13326
13327
13328 DenseMatrix.prototype.get = function (index) {
13329 if (!Object(is["b" /* isArray */])(index)) {
13330 throw new TypeError('Array expected');
13331 }
13332
13333 if (index.length !== this._size.length) {
13334 throw new DimensionError["a" /* DimensionError */](index.length, this._size.length);
13335 } // check index
13336
13337
13338 for (var x = 0; x < index.length; x++) {
13339 Object(utils_array["s" /* validateIndex */])(index[x], this._size[x]);
13340 }
13341
13342 var data = this._data;
13343
13344 for (var i = 0, ii = index.length; i < ii; i++) {
13345 var indexI = index[i];
13346 Object(utils_array["s" /* validateIndex */])(indexI, data.length);
13347 data = data[indexI];
13348 }
13349
13350 return data;
13351 };
13352 /**
13353 * Replace a single element in the matrix.
13354 * @memberof DenseMatrix
13355 * @param {number[]} index Zero-based index
13356 * @param {*} value
13357 * @param {*} [defaultValue] Default value, filled in on new entries when
13358 * the matrix is resized. If not provided,
13359 * new matrix elements will be left undefined.
13360 * @return {DenseMatrix} self
13361 */
13362
13363
13364 DenseMatrix.prototype.set = function (index, value, defaultValue) {
13365 if (!Object(is["b" /* isArray */])(index)) {
13366 throw new TypeError('Array expected');
13367 }
13368
13369 if (index.length < this._size.length) {
13370 throw new DimensionError["a" /* DimensionError */](index.length, this._size.length, '<');
13371 }
13372
13373 var i, ii, indexI; // enlarge matrix when needed
13374
13375 var size = index.map(function (i) {
13376 return i + 1;
13377 });
13378
13379 _fit(this, size, defaultValue); // traverse over the dimensions
13380
13381
13382 var data = this._data;
13383
13384 for (i = 0, ii = index.length - 1; i < ii; i++) {
13385 indexI = index[i];
13386 Object(utils_array["s" /* validateIndex */])(indexI, data.length);
13387 data = data[indexI];
13388 } // set new value
13389
13390
13391 indexI = index[index.length - 1];
13392 Object(utils_array["s" /* validateIndex */])(indexI, data.length);
13393 data[indexI] = value;
13394 return this;
13395 };
13396 /**
13397 * Get a submatrix of this matrix
13398 * @memberof DenseMatrix
13399 * @param {DenseMatrix} matrix
13400 * @param {Index} index Zero-based index
13401 * @private
13402 */
13403
13404
13405 function _get(matrix, index) {
13406 if (!Object(is["t" /* isIndex */])(index)) {
13407 throw new TypeError('Invalid index');
13408 }
13409
13410 var isScalar = index.isScalar();
13411
13412 if (isScalar) {
13413 // return a scalar
13414 return matrix.get(index.min());
13415 } else {
13416 // validate dimensions
13417 var size = index.size();
13418
13419 if (size.length !== matrix._size.length) {
13420 throw new DimensionError["a" /* DimensionError */](size.length, matrix._size.length);
13421 } // validate if any of the ranges in the index is out of range
13422
13423
13424 var min = index.min();
13425 var max = index.max();
13426
13427 for (var i = 0, ii = matrix._size.length; i < ii; i++) {
13428 Object(utils_array["s" /* validateIndex */])(min[i], matrix._size[i]);
13429 Object(utils_array["s" /* validateIndex */])(max[i], matrix._size[i]);
13430 } // retrieve submatrix
13431 // TODO: more efficient when creating an empty matrix and setting _data and _size manually
13432
13433
13434 return new DenseMatrix(_getSubmatrix(matrix._data, index, size.length, 0), matrix._datatype);
13435 }
13436 }
13437 /**
13438 * Recursively get a submatrix of a multi dimensional matrix.
13439 * Index is not checked for correct number or length of dimensions.
13440 * @memberof DenseMatrix
13441 * @param {Array} data
13442 * @param {Index} index
13443 * @param {number} dims Total number of dimensions
13444 * @param {number} dim Current dimension
13445 * @return {Array} submatrix
13446 * @private
13447 */
13448
13449
13450 function _getSubmatrix(data, index, dims, dim) {
13451 var last = dim === dims - 1;
13452 var range = index.dimension(dim);
13453
13454 if (last) {
13455 return range.map(function (i) {
13456 Object(utils_array["s" /* validateIndex */])(i, data.length);
13457 return data[i];
13458 }).valueOf();
13459 } else {
13460 return range.map(function (i) {
13461 Object(utils_array["s" /* validateIndex */])(i, data.length);
13462 var child = data[i];
13463 return _getSubmatrix(child, index, dims, dim + 1);
13464 }).valueOf();
13465 }
13466 }
13467 /**
13468 * Replace a submatrix in this matrix
13469 * Indexes are zero-based.
13470 * @memberof DenseMatrix
13471 * @param {DenseMatrix} matrix
13472 * @param {Index} index
13473 * @param {DenseMatrix | Array | *} submatrix
13474 * @param {*} defaultValue Default value, filled in on new entries when
13475 * the matrix is resized.
13476 * @return {DenseMatrix} matrix
13477 * @private
13478 */
13479
13480
13481 function _set(matrix, index, submatrix, defaultValue) {
13482 if (!index || index.isIndex !== true) {
13483 throw new TypeError('Invalid index');
13484 } // get index size and check whether the index contains a single value
13485
13486
13487 var iSize = index.size();
13488 var isScalar = index.isScalar(); // calculate the size of the submatrix, and convert it into an Array if needed
13489
13490 var sSize;
13491
13492 if (Object(is["v" /* isMatrix */])(submatrix)) {
13493 sSize = submatrix.size();
13494 submatrix = submatrix.valueOf();
13495 } else {
13496 sSize = Object(utils_array["a" /* arraySize */])(submatrix);
13497 }
13498
13499 if (isScalar) {
13500 // set a scalar
13501 // check whether submatrix is a scalar
13502 if (sSize.length !== 0) {
13503 throw new TypeError('Scalar expected');
13504 }
13505
13506 matrix.set(index.min(), submatrix, defaultValue);
13507 } else {
13508 // set a submatrix
13509 // validate dimensions
13510 if (iSize.length < matrix._size.length) {
13511 throw new DimensionError["a" /* DimensionError */](iSize.length, matrix._size.length, '<');
13512 }
13513
13514 if (sSize.length < iSize.length) {
13515 // calculate number of missing outer dimensions
13516 var i = 0;
13517 var outer = 0;
13518
13519 while (iSize[i] === 1 && sSize[i] === 1) {
13520 i++;
13521 }
13522
13523 while (iSize[i] === 1) {
13524 outer++;
13525 i++;
13526 } // unsqueeze both outer and inner dimensions
13527
13528
13529 submatrix = Object(utils_array["q" /* unsqueeze */])(submatrix, iSize.length, outer, sSize);
13530 } // check whether the size of the submatrix matches the index size
13531
13532
13533 if (!Object(utils_object["d" /* deepStrictEqual */])(iSize, sSize)) {
13534 throw new DimensionError["a" /* DimensionError */](iSize, sSize, '>');
13535 } // enlarge matrix when needed
13536
13537
13538 var size = index.max().map(function (i) {
13539 return i + 1;
13540 });
13541
13542 _fit(matrix, size, defaultValue); // insert the sub matrix
13543
13544
13545 var dims = iSize.length;
13546 var dim = 0;
13547
13548 _setSubmatrix(matrix._data, index, submatrix, dims, dim);
13549 }
13550
13551 return matrix;
13552 }
13553 /**
13554 * Replace a submatrix of a multi dimensional matrix.
13555 * @memberof DenseMatrix
13556 * @param {Array} data
13557 * @param {Index} index
13558 * @param {Array} submatrix
13559 * @param {number} dims Total number of dimensions
13560 * @param {number} dim
13561 * @private
13562 */
13563
13564
13565 function _setSubmatrix(data, index, submatrix, dims, dim) {
13566 var last = dim === dims - 1;
13567 var range = index.dimension(dim);
13568
13569 if (last) {
13570 range.forEach(function (dataIndex, subIndex) {
13571 Object(utils_array["s" /* validateIndex */])(dataIndex);
13572 data[dataIndex] = submatrix[subIndex[0]];
13573 });
13574 } else {
13575 range.forEach(function (dataIndex, subIndex) {
13576 Object(utils_array["s" /* validateIndex */])(dataIndex);
13577
13578 _setSubmatrix(data[dataIndex], index, submatrix[subIndex[0]], dims, dim + 1);
13579 });
13580 }
13581 }
13582 /**
13583 * Resize the matrix to the given size. Returns a copy of the matrix when
13584 * `copy=true`, otherwise return the matrix itself (resize in place).
13585 *
13586 * @memberof DenseMatrix
13587 * @param {number[]} size The new size the matrix should have.
13588 * @param {*} [defaultValue=0] Default value, filled in on new entries.
13589 * If not provided, the matrix elements will
13590 * be filled with zeros.
13591 * @param {boolean} [copy] Return a resized copy of the matrix
13592 *
13593 * @return {Matrix} The resized matrix
13594 */
13595
13596
13597 DenseMatrix.prototype.resize = function (size, defaultValue, copy) {
13598 // validate arguments
13599 if (!Object(is["b" /* isArray */])(size)) {
13600 throw new TypeError('Array expected');
13601 } // matrix to resize
13602
13603
13604 var m = copy ? this.clone() : this; // resize matrix
13605
13606 return _resize(m, size, defaultValue);
13607 };
13608
13609 function _resize(matrix, size, defaultValue) {
13610 // check size
13611 if (size.length === 0) {
13612 // first value in matrix
13613 var v = matrix._data; // go deep
13614
13615 while (Object(is["b" /* isArray */])(v)) {
13616 v = v[0];
13617 }
13618
13619 return v;
13620 } // resize matrix
13621
13622
13623 matrix._size = size.slice(0); // copy the array
13624
13625 matrix._data = Object(utils_array["o" /* resize */])(matrix._data, matrix._size, defaultValue); // return matrix
13626
13627 return matrix;
13628 }
13629 /**
13630 * Reshape the matrix to the given size. Returns a copy of the matrix when
13631 * `copy=true`, otherwise return the matrix itself (reshape in place).
13632 *
13633 * NOTE: This might be better suited to copy by default, instead of modifying
13634 * in place. For now, it operates in place to remain consistent with
13635 * resize().
13636 *
13637 * @memberof DenseMatrix
13638 * @param {number[]} size The new size the matrix should have.
13639 * @param {boolean} [copy] Return a reshaped copy of the matrix
13640 *
13641 * @return {Matrix} The reshaped matrix
13642 */
13643
13644
13645 DenseMatrix.prototype.reshape = function (size, copy) {
13646 var m = copy ? this.clone() : this;
13647 m._data = Object(utils_array["n" /* reshape */])(m._data, size);
13648 m._size = size.slice(0);
13649 return m;
13650 };
13651 /**
13652 * Enlarge the matrix when it is smaller than given size.
13653 * If the matrix is larger or equal sized, nothing is done.
13654 * @memberof DenseMatrix
13655 * @param {DenseMatrix} matrix The matrix to be resized
13656 * @param {number[]} size
13657 * @param {*} defaultValue Default value, filled in on new entries.
13658 * @private
13659 */
13660
13661
13662 function _fit(matrix, size, defaultValue) {
13663 var // copy the array
13664 newSize = matrix._size.slice(0);
13665
13666 var changed = false; // add dimensions when needed
13667
13668 while (newSize.length < size.length) {
13669 newSize.push(0);
13670 changed = true;
13671 } // enlarge size when needed
13672
13673
13674 for (var i = 0, ii = size.length; i < ii; i++) {
13675 if (size[i] > newSize[i]) {
13676 newSize[i] = size[i];
13677 changed = true;
13678 }
13679 }
13680
13681 if (changed) {
13682 // resize only when size is changed
13683 _resize(matrix, newSize, defaultValue);
13684 }
13685 }
13686 /**
13687 * Create a clone of the matrix
13688 * @memberof DenseMatrix
13689 * @return {DenseMatrix} clone
13690 */
13691
13692
13693 DenseMatrix.prototype.clone = function () {
13694 var m = new DenseMatrix({
13695 data: Object(utils_object["a" /* clone */])(this._data),
13696 size: Object(utils_object["a" /* clone */])(this._size),
13697 datatype: this._datatype
13698 });
13699 return m;
13700 };
13701 /**
13702 * Retrieve the size of the matrix.
13703 * @memberof DenseMatrix
13704 * @returns {number[]} size
13705 */
13706
13707
13708 DenseMatrix.prototype.size = function () {
13709 return this._size.slice(0); // return a clone of _size
13710 };
13711 /**
13712 * Create a new matrix with the results of the callback function executed on
13713 * each entry of the matrix.
13714 * @memberof DenseMatrix
13715 * @param {Function} callback The callback function is invoked with three
13716 * parameters: the value of the element, the index
13717 * of the element, and the Matrix being traversed.
13718 *
13719 * @return {DenseMatrix} matrix
13720 */
13721
13722
13723 DenseMatrix.prototype.map = function (callback) {
13724 // matrix instance
13725 var me = this;
13726
13727 var recurse = function recurse(value, index) {
13728 if (Object(is["b" /* isArray */])(value)) {
13729 return value.map(function (child, i) {
13730 return recurse(child, index.concat(i));
13731 });
13732 } else {
13733 return callback(value, index, me);
13734 }
13735 }; // return dense format
13736
13737
13738 return new DenseMatrix({
13739 data: recurse(this._data, []),
13740 size: Object(utils_object["a" /* clone */])(this._size),
13741 datatype: this._datatype
13742 });
13743 };
13744 /**
13745 * Execute a callback function on each entry of the matrix.
13746 * @memberof DenseMatrix
13747 * @param {Function} callback The callback function is invoked with three
13748 * parameters: the value of the element, the index
13749 * of the element, and the Matrix being traversed.
13750 */
13751
13752
13753 DenseMatrix.prototype.forEach = function (callback) {
13754 // matrix instance
13755 var me = this;
13756
13757 var recurse = function recurse(value, index) {
13758 if (Object(is["b" /* isArray */])(value)) {
13759 value.forEach(function (child, i) {
13760 recurse(child, index.concat(i));
13761 });
13762 } else {
13763 callback(value, index, me);
13764 }
13765 };
13766
13767 recurse(this._data, []);
13768 };
13769 /**
13770 * Create an Array with a copy of the data of the DenseMatrix
13771 * @memberof DenseMatrix
13772 * @returns {Array} array
13773 */
13774
13775
13776 DenseMatrix.prototype.toArray = function () {
13777 return Object(utils_object["a" /* clone */])(this._data);
13778 };
13779 /**
13780 * Get the primitive value of the DenseMatrix: a multidimensional array
13781 * @memberof DenseMatrix
13782 * @returns {Array} array
13783 */
13784
13785
13786 DenseMatrix.prototype.valueOf = function () {
13787 return this._data;
13788 };
13789 /**
13790 * Get a string representation of the matrix, with optional formatting options.
13791 * @memberof DenseMatrix
13792 * @param {Object | number | Function} [options] Formatting options. See
13793 * lib/utils/number:format for a
13794 * description of the available
13795 * options.
13796 * @returns {string} str
13797 */
13798
13799
13800 DenseMatrix.prototype.format = function (options) {
13801 return Object(utils_string["d" /* format */])(this._data, options);
13802 };
13803 /**
13804 * Get a string representation of the matrix
13805 * @memberof DenseMatrix
13806 * @returns {string} str
13807 */
13808
13809
13810 DenseMatrix.prototype.toString = function () {
13811 return Object(utils_string["d" /* format */])(this._data);
13812 };
13813 /**
13814 * Get a JSON representation of the matrix
13815 * @memberof DenseMatrix
13816 * @returns {Object}
13817 */
13818
13819
13820 DenseMatrix.prototype.toJSON = function () {
13821 return {
13822 mathjs: 'DenseMatrix',
13823 data: this._data,
13824 size: this._size,
13825 datatype: this._datatype
13826 };
13827 };
13828 /**
13829 * Get the kth Matrix diagonal.
13830 *
13831 * @memberof DenseMatrix
13832 * @param {number | BigNumber} [k=0] The kth diagonal where the vector will retrieved.
13833 *
13834 * @returns {Matrix} The matrix with the diagonal values.
13835 */
13836
13837
13838 DenseMatrix.prototype.diagonal = function (k) {
13839 // validate k if any
13840 if (k) {
13841 // convert BigNumber to a number
13842 if (Object(is["e" /* isBigNumber */])(k)) {
13843 k = k.toNumber();
13844 } // is must be an integer
13845
13846
13847 if (!Object(is["y" /* isNumber */])(k) || !Object(utils_number["i" /* isInteger */])(k)) {
13848 throw new TypeError('The parameter k must be an integer number');
13849 }
13850 } else {
13851 // default value
13852 k = 0;
13853 }
13854
13855 var kSuper = k > 0 ? k : 0;
13856 var kSub = k < 0 ? -k : 0; // rows & columns
13857
13858 var rows = this._size[0];
13859 var columns = this._size[1]; // number diagonal values
13860
13861 var n = Math.min(rows - kSub, columns - kSuper); // x is a matrix get diagonal from matrix
13862
13863 var data = []; // loop rows
13864
13865 for (var i = 0; i < n; i++) {
13866 data[i] = this._data[i + kSub][i + kSuper];
13867 } // create DenseMatrix
13868
13869
13870 return new DenseMatrix({
13871 data: data,
13872 size: [n],
13873 datatype: this._datatype
13874 });
13875 };
13876 /**
13877 * Create a diagonal matrix.
13878 *
13879 * @memberof DenseMatrix
13880 * @param {Array} size The matrix size.
13881 * @param {number | Matrix | Array } value The values for the diagonal.
13882 * @param {number | BigNumber} [k=0] The kth diagonal where the vector will be filled in.
13883 * @param {number} [defaultValue] The default value for non-diagonal
13884 * @param {string} [datatype] The datatype for the diagonal
13885 *
13886 * @returns {DenseMatrix}
13887 */
13888
13889
13890 DenseMatrix.diagonal = function (size, value, k, defaultValue) {
13891 if (!Object(is["b" /* isArray */])(size)) {
13892 throw new TypeError('Array expected, size parameter');
13893 }
13894
13895 if (size.length !== 2) {
13896 throw new Error('Only two dimensions matrix are supported');
13897 } // map size & validate
13898
13899
13900 size = size.map(function (s) {
13901 // check it is a big number
13902 if (Object(is["e" /* isBigNumber */])(s)) {
13903 // convert it
13904 s = s.toNumber();
13905 } // validate arguments
13906
13907
13908 if (!Object(is["y" /* isNumber */])(s) || !Object(utils_number["i" /* isInteger */])(s) || s < 1) {
13909 throw new Error('Size values must be positive integers');
13910 }
13911
13912 return s;
13913 }); // validate k if any
13914
13915 if (k) {
13916 // convert BigNumber to a number
13917 if (Object(is["e" /* isBigNumber */])(k)) {
13918 k = k.toNumber();
13919 } // is must be an integer
13920
13921
13922 if (!Object(is["y" /* isNumber */])(k) || !Object(utils_number["i" /* isInteger */])(k)) {
13923 throw new TypeError('The parameter k must be an integer number');
13924 }
13925 } else {
13926 // default value
13927 k = 0;
13928 }
13929
13930 var kSuper = k > 0 ? k : 0;
13931 var kSub = k < 0 ? -k : 0; // rows and columns
13932
13933 var rows = size[0];
13934 var columns = size[1]; // number of non-zero items
13935
13936 var n = Math.min(rows - kSub, columns - kSuper); // value extraction function
13937
13938 var _value; // check value
13939
13940
13941 if (Object(is["b" /* isArray */])(value)) {
13942 // validate array
13943 if (value.length !== n) {
13944 // number of values in array must be n
13945 throw new Error('Invalid value array length');
13946 } // define function
13947
13948
13949 _value = function _value(i) {
13950 // return value @ i
13951 return value[i];
13952 };
13953 } else if (Object(is["v" /* isMatrix */])(value)) {
13954 // matrix size
13955 var ms = value.size(); // validate matrix
13956
13957 if (ms.length !== 1 || ms[0] !== n) {
13958 // number of values in array must be n
13959 throw new Error('Invalid matrix length');
13960 } // define function
13961
13962
13963 _value = function _value(i) {
13964 // return value @ i
13965 return value.get([i]);
13966 };
13967 } else {
13968 // define function
13969 _value = function _value() {
13970 // return value
13971 return value;
13972 };
13973 } // discover default value if needed
13974
13975
13976 if (!defaultValue) {
13977 // check first value in array
13978 defaultValue = Object(is["e" /* isBigNumber */])(_value(0)) ? _value(0).mul(0) // trick to create a BigNumber with value zero
13979 : 0;
13980 } // empty array
13981
13982
13983 var data = []; // check we need to resize array
13984
13985 if (size.length > 0) {
13986 // resize array
13987 data = Object(utils_array["o" /* resize */])(data, size, defaultValue); // fill diagonal
13988
13989 for (var d = 0; d < n; d++) {
13990 data[d + kSub][d + kSuper] = _value(d);
13991 }
13992 } // create DenseMatrix
13993
13994
13995 return new DenseMatrix({
13996 data: data,
13997 size: [rows, columns]
13998 });
13999 };
14000 /**
14001 * Generate a matrix from a JSON object
14002 * @memberof DenseMatrix
14003 * @param {Object} json An object structured like
14004 * `{"mathjs": "DenseMatrix", data: [], size: []}`,
14005 * where mathjs is optional
14006 * @returns {DenseMatrix}
14007 */
14008
14009
14010 DenseMatrix.fromJSON = function (json) {
14011 return new DenseMatrix(json);
14012 };
14013 /**
14014 * Swap rows i and j in Matrix.
14015 *
14016 * @memberof DenseMatrix
14017 * @param {number} i Matrix row index 1
14018 * @param {number} j Matrix row index 2
14019 *
14020 * @return {Matrix} The matrix reference
14021 */
14022
14023
14024 DenseMatrix.prototype.swapRows = function (i, j) {
14025 // check index
14026 if (!Object(is["y" /* isNumber */])(i) || !Object(utils_number["i" /* isInteger */])(i) || !Object(is["y" /* isNumber */])(j) || !Object(utils_number["i" /* isInteger */])(j)) {
14027 throw new Error('Row index must be positive integers');
14028 } // check dimensions
14029
14030
14031 if (this._size.length !== 2) {
14032 throw new Error('Only two dimensional matrix is supported');
14033 } // validate index
14034
14035
14036 Object(utils_array["s" /* validateIndex */])(i, this._size[0]);
14037 Object(utils_array["s" /* validateIndex */])(j, this._size[0]); // swap rows
14038
14039 DenseMatrix._swapRows(i, j, this._data); // return current instance
14040
14041
14042 return this;
14043 };
14044 /**
14045 * Swap rows i and j in Dense Matrix data structure.
14046 *
14047 * @param {number} i Matrix row index 1
14048 * @param {number} j Matrix row index 2
14049 * @param {Array} data Matrix data
14050 */
14051
14052
14053 DenseMatrix._swapRows = function (i, j, data) {
14054 // swap values i <-> j
14055 var vi = data[i];
14056 data[i] = data[j];
14057 data[j] = vi;
14058 };
14059 /**
14060 * Preprocess data, which can be an Array or DenseMatrix with nested Arrays and
14061 * Matrices. Replaces all nested Matrices with Arrays
14062 * @memberof DenseMatrix
14063 * @param {Array} data
14064 * @return {Array} data
14065 */
14066
14067
14068 function preprocess(data) {
14069 for (var i = 0, ii = data.length; i < ii; i++) {
14070 var elem = data[i];
14071
14072 if (Object(is["b" /* isArray */])(elem)) {
14073 data[i] = preprocess(elem);
14074 } else if (elem && elem.isMatrix === true) {
14075 data[i] = preprocess(elem.valueOf());
14076 }
14077 }
14078
14079 return data;
14080 }
14081
14082 return DenseMatrix;
14083}, {
14084 isClass: true
14085});
14086// CONCATENATED MODULE: ./src/function/utils/clone.js
14087
14088
14089var clone_name = 'clone';
14090var clone_dependencies = ['typed'];
14091var createClone =
14092/* #__PURE__ */
14093Object(factory["a" /* factory */])(clone_name, clone_dependencies, function (_ref) {
14094 var typed = _ref.typed;
14095
14096 /**
14097 * Clone an object.
14098 *
14099 * Syntax:
14100 *
14101 * math.clone(x)
14102 *
14103 * Examples:
14104 *
14105 * math.clone(3.5) // returns number 3.5
14106 * math.clone(math.complex('2-4i') // returns Complex 2 - 4i
14107 * math.clone(math.unit(45, 'deg')) // returns Unit 45 deg
14108 * math.clone([[1, 2], [3, 4]]) // returns Array [[1, 2], [3, 4]]
14109 * math.clone("hello world") // returns string "hello world"
14110 *
14111 * @param {*} x Object to be cloned
14112 * @return {*} A clone of object x
14113 */
14114 return typed(clone_name, {
14115 any: utils_object["a" /* clone */]
14116 });
14117});
14118// EXTERNAL MODULE: ./src/error/IndexError.js
14119var IndexError = __webpack_require__(10);
14120
14121// CONCATENATED MODULE: ./src/utils/collection.js
14122
14123
14124
14125/**
14126 * Test whether an array contains collections
14127 * @param {Array} array
14128 * @returns {boolean} Returns true when the array contains one or multiple
14129 * collections (Arrays or Matrices). Returns false otherwise.
14130 */
14131
14132function containsCollections(array) {
14133 for (var i = 0; i < array.length; i++) {
14134 if (Object(is["i" /* isCollection */])(array[i])) {
14135 return true;
14136 }
14137 }
14138
14139 return false;
14140}
14141/**
14142 * Recursively loop over all elements in a given multi dimensional array
14143 * and invoke the callback on each of the elements.
14144 * @param {Array | Matrix} array
14145 * @param {Function} callback The callback method is invoked with one
14146 * parameter: the current element in the array
14147 */
14148
14149function deepForEach(array, callback) {
14150 if (Object(is["v" /* isMatrix */])(array)) {
14151 array = array.valueOf();
14152 }
14153
14154 for (var i = 0, ii = array.length; i < ii; i++) {
14155 var value = array[i];
14156
14157 if (Array.isArray(value)) {
14158 deepForEach(value, callback);
14159 } else {
14160 callback(value);
14161 }
14162 }
14163}
14164/**
14165 * Execute the callback function element wise for each element in array and any
14166 * nested array
14167 * Returns an array with the results
14168 * @param {Array | Matrix} array
14169 * @param {Function} callback The callback is called with two parameters:
14170 * value1 and value2, which contain the current
14171 * element of both arrays.
14172 * @param {boolean} [skipZeros] Invoke callback function for non-zero values only.
14173 *
14174 * @return {Array | Matrix} res
14175 */
14176
14177function deepMap(array, callback, skipZeros) {
14178 if (array && typeof array.map === 'function') {
14179 // TODO: replace array.map with a for loop to improve performance
14180 return array.map(function (x) {
14181 return deepMap(x, callback, skipZeros);
14182 });
14183 } else {
14184 return callback(array);
14185 }
14186}
14187/**
14188 * Reduce a given matrix or array to a new matrix or
14189 * array with one less dimension, applying the given
14190 * callback in the selected dimension.
14191 * @param {Array | Matrix} mat
14192 * @param {number} dim
14193 * @param {Function} callback
14194 * @return {Array | Matrix} res
14195 */
14196
14197function reduce(mat, dim, callback) {
14198 var size = Array.isArray(mat) ? Object(utils_array["a" /* arraySize */])(mat) : mat.size();
14199
14200 if (dim < 0 || dim >= size.length) {
14201 // TODO: would be more clear when throwing a DimensionError here
14202 throw new IndexError["a" /* IndexError */](dim, size.length);
14203 }
14204
14205 if (Object(is["v" /* isMatrix */])(mat)) {
14206 return mat.create(_reduce(mat.valueOf(), dim, callback));
14207 } else {
14208 return _reduce(mat, dim, callback);
14209 }
14210}
14211/**
14212 * Recursively reduce a matrix
14213 * @param {Array} mat
14214 * @param {number} dim
14215 * @param {Function} callback
14216 * @returns {Array} ret
14217 * @private
14218 */
14219
14220function _reduce(mat, dim, callback) {
14221 var i, ret, val, tran;
14222
14223 if (dim <= 0) {
14224 if (!Array.isArray(mat[0])) {
14225 val = mat[0];
14226
14227 for (i = 1; i < mat.length; i++) {
14228 val = callback(val, mat[i]);
14229 }
14230
14231 return val;
14232 } else {
14233 tran = _switch(mat);
14234 ret = [];
14235
14236 for (i = 0; i < tran.length; i++) {
14237 ret[i] = _reduce(tran[i], dim - 1, callback);
14238 }
14239
14240 return ret;
14241 }
14242 } else {
14243 ret = [];
14244
14245 for (i = 0; i < mat.length; i++) {
14246 ret[i] = _reduce(mat[i], dim - 1, callback);
14247 }
14248
14249 return ret;
14250 }
14251}
14252/**
14253 * Transpose a matrix
14254 * @param {Array} mat
14255 * @returns {Array} ret
14256 * @private
14257 */
14258
14259
14260function _switch(mat) {
14261 var I = mat.length;
14262 var J = mat[0].length;
14263 var i, j;
14264 var ret = [];
14265
14266 for (j = 0; j < J; j++) {
14267 var tmp = [];
14268
14269 for (i = 0; i < I; i++) {
14270 tmp.push(mat[i][j]);
14271 }
14272
14273 ret.push(tmp);
14274 }
14275
14276 return ret;
14277} // TODO: document function scatter
14278
14279
14280function scatter(a, j, w, x, u, mark, c, f, inverse, update, value) {
14281 // a arrays
14282 var avalues = a._values;
14283 var aindex = a._index;
14284 var aptr = a._ptr; // c arrays
14285
14286 var cindex = c._index; // vars
14287
14288 var k, k0, k1, i; // check we need to process values (pattern matrix)
14289
14290 if (x) {
14291 // values in j
14292 for (k0 = aptr[j], k1 = aptr[j + 1], k = k0; k < k1; k++) {
14293 // row
14294 i = aindex[k]; // check value exists in current j
14295
14296 if (w[i] !== mark) {
14297 // i is new entry in j
14298 w[i] = mark; // add i to pattern of C
14299
14300 cindex.push(i); // x(i) = A, check we need to call function this time
14301
14302 if (update) {
14303 // copy value to workspace calling callback function
14304 x[i] = inverse ? f(avalues[k], value) : f(value, avalues[k]); // function was called on current row
14305
14306 u[i] = mark;
14307 } else {
14308 // copy value to workspace
14309 x[i] = avalues[k];
14310 }
14311 } else {
14312 // i exists in C already
14313 x[i] = inverse ? f(avalues[k], x[i]) : f(x[i], avalues[k]); // function was called on current row
14314
14315 u[i] = mark;
14316 }
14317 }
14318 } else {
14319 // values in j
14320 for (k0 = aptr[j], k1 = aptr[j + 1], k = k0; k < k1; k++) {
14321 // row
14322 i = aindex[k]; // check value exists in current j
14323
14324 if (w[i] !== mark) {
14325 // i is new entry in j
14326 w[i] = mark; // add i to pattern of C
14327
14328 cindex.push(i);
14329 } else {
14330 // indicate function was called on current row
14331 u[i] = mark;
14332 }
14333 }
14334 }
14335}
14336// CONCATENATED MODULE: ./src/function/utils/isInteger.js
14337
14338
14339
14340var isInteger_name = 'isInteger';
14341var isInteger_dependencies = ['typed'];
14342var createIsInteger =
14343/* #__PURE__ */
14344Object(factory["a" /* factory */])(isInteger_name, isInteger_dependencies, function (_ref) {
14345 var typed = _ref.typed;
14346
14347 /**
14348 * Test whether a value is an integer number.
14349 * The function supports `number`, `BigNumber`, and `Fraction`.
14350 *
14351 * The function is evaluated element-wise in case of Array or Matrix input.
14352 *
14353 * Syntax:
14354 *
14355 * math.isInteger(x)
14356 *
14357 * Examples:
14358 *
14359 * math.isInteger(2) // returns true
14360 * math.isInteger(0) // returns true
14361 * math.isInteger(0.5) // returns false
14362 * math.isInteger(math.bignumber(500)) // returns true
14363 * math.isInteger(math.fraction(4)) // returns true
14364 * math.isInteger('3') // returns true
14365 * math.isInteger([3, 0.5, -2]) // returns [true, false, true]
14366 * math.isInteger(math.complex('2-4i') // throws an error
14367 *
14368 * See also:
14369 *
14370 * isNumeric, isPositive, isNegative, isZero
14371 *
14372 * @param {number | BigNumber | Fraction | Array | Matrix} x Value to be tested
14373 * @return {boolean} Returns true when `x` contains a numeric, integer value.
14374 * Throws an error in case of an unknown data type.
14375 */
14376 var isInteger = typed(isInteger_name, {
14377 number: utils_number["i" /* isInteger */],
14378 // TODO: what to do with isInteger(add(0.1, 0.2)) ?
14379 BigNumber: function BigNumber(x) {
14380 return x.isInt();
14381 },
14382 Fraction: function Fraction(x) {
14383 return x.d === 1 && isFinite(x.n);
14384 },
14385 'Array | Matrix': function ArrayMatrix(x) {
14386 return deepMap(x, isInteger);
14387 }
14388 });
14389 return isInteger;
14390});
14391// CONCATENATED MODULE: ./src/plain/number/utils.js
14392
14393var utils_n1 = 'number';
14394function isIntegerNumber(x) {
14395 return Object(utils_number["i" /* isInteger */])(x);
14396}
14397isIntegerNumber.signature = utils_n1;
14398function isNegativeNumber(x) {
14399 return x < 0;
14400}
14401isNegativeNumber.signature = utils_n1;
14402function isPositiveNumber(x) {
14403 return x > 0;
14404}
14405isPositiveNumber.signature = utils_n1;
14406function isZeroNumber(x) {
14407 return x === 0;
14408}
14409isZeroNumber.signature = utils_n1;
14410function isNaNNumber(x) {
14411 return Number.isNaN(x);
14412}
14413isNaNNumber.signature = utils_n1;
14414// CONCATENATED MODULE: ./src/function/utils/isNegative.js
14415
14416
14417
14418var isNegative_name = 'isNegative';
14419var isNegative_dependencies = ['typed'];
14420var createIsNegative =
14421/* #__PURE__ */
14422Object(factory["a" /* factory */])(isNegative_name, isNegative_dependencies, function (_ref) {
14423 var typed = _ref.typed;
14424
14425 /**
14426 * Test whether a value is negative: smaller than zero.
14427 * The function supports types `number`, `BigNumber`, `Fraction`, and `Unit`.
14428 *
14429 * The function is evaluated element-wise in case of Array or Matrix input.
14430 *
14431 * Syntax:
14432 *
14433 * math.isNegative(x)
14434 *
14435 * Examples:
14436 *
14437 * math.isNegative(3) // returns false
14438 * math.isNegative(-2) // returns true
14439 * math.isNegative(0) // returns false
14440 * math.isNegative(-0) // returns false
14441 * math.isNegative(math.bignumber(2)) // returns false
14442 * math.isNegative(math.fraction(-2, 5)) // returns true
14443 * math.isNegative('-2') // returns true
14444 * math.isNegative([2, 0, -3]') // returns [false, false, true]
14445 *
14446 * See also:
14447 *
14448 * isNumeric, isPositive, isZero, isInteger
14449 *
14450 * @param {number | BigNumber | Fraction | Unit | Array | Matrix} x Value to be tested
14451 * @return {boolean} Returns true when `x` is larger than zero.
14452 * Throws an error in case of an unknown data type.
14453 */
14454 var isNegative = typed(isNegative_name, {
14455 number: isNegativeNumber,
14456 BigNumber: function BigNumber(x) {
14457 return x.isNeg() && !x.isZero() && !x.isNaN();
14458 },
14459 Fraction: function Fraction(x) {
14460 return x.s < 0; // It's enough to decide on the sign
14461 },
14462 Unit: function Unit(x) {
14463 return isNegative(x.value);
14464 },
14465 'Array | Matrix': function ArrayMatrix(x) {
14466 return deepMap(x, isNegative);
14467 }
14468 });
14469 return isNegative;
14470});
14471// CONCATENATED MODULE: ./src/function/utils/isNumeric.js
14472
14473
14474var isNumeric_name = 'isNumeric';
14475var isNumeric_dependencies = ['typed'];
14476var createIsNumeric =
14477/* #__PURE__ */
14478Object(factory["a" /* factory */])(isNumeric_name, isNumeric_dependencies, function (_ref) {
14479 var typed = _ref.typed;
14480
14481 /**
14482 * Test whether a value is an numeric value.
14483 *
14484 * The function is evaluated element-wise in case of Array or Matrix input.
14485 *
14486 * Syntax:
14487 *
14488 * math.isNumeric(x)
14489 *
14490 * Examples:
14491 *
14492 * math.isNumeric(2) // returns true
14493 * math.isNumeric('2') // returns false
14494 * math.hasNumericValue('2') // returns true
14495 * math.isNumeric(0) // returns true
14496 * math.isNumeric(math.bignumber(500)) // returns true
14497 * math.isNumeric(math.fraction(4)) // returns true
14498 * math.isNumeric(math.complex('2-4i') // returns false
14499 * math.isNumeric([2.3, 'foo', false]) // returns [true, false, true]
14500 *
14501 * See also:
14502 *
14503 * isZero, isPositive, isNegative, isInteger, hasNumericValue
14504 *
14505 * @param {*} x Value to be tested
14506 * @return {boolean} Returns true when `x` is a `number`, `BigNumber`,
14507 * `Fraction`, or `boolean`. Returns false for other types.
14508 * Throws an error in case of unknown types.
14509 */
14510 var isNumeric = typed(isNumeric_name, {
14511 'number | BigNumber | Fraction | boolean': function numberBigNumberFractionBoolean() {
14512 return true;
14513 },
14514 'Complex | Unit | string | null | undefined | Node': function ComplexUnitStringNullUndefinedNode() {
14515 return false;
14516 },
14517 'Array | Matrix': function ArrayMatrix(x) {
14518 return deepMap(x, isNumeric);
14519 }
14520 });
14521 return isNumeric;
14522});
14523// CONCATENATED MODULE: ./src/function/utils/hasNumericValue.js
14524
14525var hasNumericValue_name = 'hasNumericValue';
14526var hasNumericValue_dependencies = ['typed', 'isNumeric'];
14527var createHasNumericValue =
14528/* #__PURE__ */
14529Object(factory["a" /* factory */])(hasNumericValue_name, hasNumericValue_dependencies, function (_ref) {
14530 var typed = _ref.typed,
14531 isNumeric = _ref.isNumeric;
14532
14533 /**
14534 * Test whether a value is an numeric value.
14535 *
14536 * In case of a string, true is returned if the string contains a numeric value.
14537 *
14538 * Syntax:
14539 *
14540 * math.hasNumericValue(x)
14541 *
14542 * Examples:
14543 *
14544 * math.hasNumericValue(2) // returns true
14545 * math.hasNumericValue('2') // returns true
14546 * math.isNumeric('2') // returns false
14547 * math.hasNumericValue(0) // returns true
14548 * math.hasNumericValue(math.bignumber(500)) // returns true
14549 * math.hasNumericValue(math.fraction(4)) // returns true
14550 * math.hasNumericValue(math.complex('2-4i') // returns false
14551 * math.hasNumericValue([2.3, 'foo', false]) // returns [true, false, true]
14552 *
14553 * See also:
14554 *
14555 * isZero, isPositive, isNegative, isInteger, isNumeric
14556 *
14557 * @param {*} x Value to be tested
14558 * @return {boolean} Returns true when `x` is a `number`, `BigNumber`,
14559 * `Fraction`, `Boolean`, or a `String` containing number. Returns false for other types.
14560 * Throws an error in case of unknown types.
14561 */
14562 return typed(hasNumericValue_name, {
14563 string: function string(x) {
14564 return x.trim().length > 0 && !isNaN(Number(x));
14565 },
14566 any: function any(x) {
14567 return isNumeric(x);
14568 }
14569 });
14570});
14571// CONCATENATED MODULE: ./src/function/utils/isPositive.js
14572
14573
14574
14575var isPositive_name = 'isPositive';
14576var isPositive_dependencies = ['typed'];
14577var createIsPositive =
14578/* #__PURE__ */
14579Object(factory["a" /* factory */])(isPositive_name, isPositive_dependencies, function (_ref) {
14580 var typed = _ref.typed;
14581
14582 /**
14583 * Test whether a value is positive: larger than zero.
14584 * The function supports types `number`, `BigNumber`, `Fraction`, and `Unit`.
14585 *
14586 * The function is evaluated element-wise in case of Array or Matrix input.
14587 *
14588 * Syntax:
14589 *
14590 * math.isPositive(x)
14591 *
14592 * Examples:
14593 *
14594 * math.isPositive(3) // returns true
14595 * math.isPositive(-2) // returns false
14596 * math.isPositive(0) // returns false
14597 * math.isPositive(-0) // returns false
14598 * math.isPositive(0.5) // returns true
14599 * math.isPositive(math.bignumber(2)) // returns true
14600 * math.isPositive(math.fraction(-2, 5)) // returns false
14601 * math.isPositive(math.fraction(1,3)) // returns false
14602 * math.isPositive('2') // returns true
14603 * math.isPositive([2, 0, -3]) // returns [true, false, false]
14604 *
14605 * See also:
14606 *
14607 * isNumeric, isZero, isNegative, isInteger
14608 *
14609 * @param {number | BigNumber | Fraction | Unit | Array | Matrix} x Value to be tested
14610 * @return {boolean} Returns true when `x` is larger than zero.
14611 * Throws an error in case of an unknown data type.
14612 */
14613 var isPositive = typed(isPositive_name, {
14614 number: isPositiveNumber,
14615 BigNumber: function BigNumber(x) {
14616 return !x.isNeg() && !x.isZero() && !x.isNaN();
14617 },
14618 Fraction: function Fraction(x) {
14619 return x.s > 0 && x.n > 0;
14620 },
14621 Unit: function Unit(x) {
14622 return isPositive(x.value);
14623 },
14624 'Array | Matrix': function ArrayMatrix(x) {
14625 return deepMap(x, isPositive);
14626 }
14627 });
14628 return isPositive;
14629});
14630// CONCATENATED MODULE: ./src/function/utils/isZero.js
14631
14632
14633
14634var isZero_name = 'isZero';
14635var isZero_dependencies = ['typed'];
14636var createIsZero =
14637/* #__PURE__ */
14638Object(factory["a" /* factory */])(isZero_name, isZero_dependencies, function (_ref) {
14639 var typed = _ref.typed;
14640
14641 /**
14642 * Test whether a value is zero.
14643 * The function can check for zero for types `number`, `BigNumber`, `Fraction`,
14644 * `Complex`, and `Unit`.
14645 *
14646 * The function is evaluated element-wise in case of Array or Matrix input.
14647 *
14648 * Syntax:
14649 *
14650 * math.isZero(x)
14651 *
14652 * Examples:
14653 *
14654 * math.isZero(0) // returns true
14655 * math.isZero(2) // returns false
14656 * math.isZero(0.5) // returns false
14657 * math.isZero(math.bignumber(0)) // returns true
14658 * math.isZero(math.fraction(0)) // returns true
14659 * math.isZero(math.fraction(1,3)) // returns false
14660 * math.isZero(math.complex('2 - 4i') // returns false
14661 * math.isZero(math.complex('0i') // returns true
14662 * math.isZero('0') // returns true
14663 * math.isZero('2') // returns false
14664 * math.isZero([2, 0, -3]') // returns [false, true, false]
14665 *
14666 * See also:
14667 *
14668 * isNumeric, isPositive, isNegative, isInteger
14669 *
14670 * @param {number | BigNumber | Complex | Fraction | Unit | Array | Matrix} x Value to be tested
14671 * @return {boolean} Returns true when `x` is zero.
14672 * Throws an error in case of an unknown data type.
14673 */
14674 var isZero = typed(isZero_name, {
14675 number: isZeroNumber,
14676 BigNumber: function BigNumber(x) {
14677 return x.isZero();
14678 },
14679 Complex: function Complex(x) {
14680 return x.re === 0 && x.im === 0;
14681 },
14682 Fraction: function Fraction(x) {
14683 return x.d === 1 && x.n === 0;
14684 },
14685 Unit: function Unit(x) {
14686 return isZero(x.value);
14687 },
14688 'Array | Matrix': function ArrayMatrix(x) {
14689 return deepMap(x, isZero);
14690 }
14691 });
14692 return isZero;
14693});
14694// CONCATENATED MODULE: ./src/function/utils/isNaN.js
14695
14696
14697
14698var isNaN_name = 'isNaN';
14699var isNaN_dependencies = ['typed'];
14700var createIsNaN =
14701/* #__PURE__ */
14702Object(factory["a" /* factory */])(isNaN_name, isNaN_dependencies, function (_ref) {
14703 var typed = _ref.typed;
14704
14705 /**
14706 * Test whether a value is NaN (not a number).
14707 * The function supports types `number`, `BigNumber`, `Fraction`, `Unit` and `Complex`.
14708 *
14709 * The function is evaluated element-wise in case of Array or Matrix input.
14710 *
14711 * Syntax:
14712 *
14713 * math.isNaN(x)
14714 *
14715 * Examples:
14716 *
14717 * math.isNaN(3) // returns false
14718 * math.isNaN(NaN) // returns true
14719 * math.isNaN(0) // returns false
14720 * math.isNaN(math.bignumber(NaN)) // returns true
14721 * math.isNaN(math.bignumber(0)) // returns false
14722 * math.isNaN(math.fraction(-2, 5)) // returns false
14723 * math.isNaN('-2') // returns false
14724 * math.isNaN([2, 0, -3, NaN]') // returns [false, false, false, true]
14725 *
14726 * See also:
14727 *
14728 * isNumeric, isNegative, isPositive, isZero, isInteger
14729 *
14730 * @param {number | BigNumber | Fraction | Unit | Array | Matrix} x Value to be tested
14731 * @return {boolean} Returns true when `x` is NaN.
14732 * Throws an error in case of an unknown data type.
14733 */
14734 return typed(isNaN_name, {
14735 number: isNaNNumber,
14736 BigNumber: function BigNumber(x) {
14737 return x.isNaN();
14738 },
14739 Fraction: function Fraction(x) {
14740 return false;
14741 },
14742 Complex: function Complex(x) {
14743 return x.isNaN();
14744 },
14745 Unit: function Unit(x) {
14746 return Number.isNaN(x.value);
14747 },
14748 'Array | Matrix': function ArrayMatrix(x) {
14749 return deepMap(x, Number.isNaN);
14750 }
14751 });
14752});
14753// EXTERNAL MODULE: ./src/utils/log.js
14754var utils_log = __webpack_require__(8);
14755
14756// CONCATENATED MODULE: ./src/function/utils/typeOf.js
14757
14758
14759
14760var typeOf_name = 'typeOf';
14761var typeOf_dependencies = ['typed'];
14762var createTypeOf =
14763/* #__PURE__ */
14764Object(factory["a" /* factory */])(typeOf_name, typeOf_dependencies, function (_ref) {
14765 var typed = _ref.typed;
14766
14767 /**
14768 * Determine the type of a variable.
14769 *
14770 * Function `typeOf` recognizes the following types of objects:
14771 *
14772 * Object | Returns | Example
14773 * ---------------------- | ------------- | ------------------------------------------
14774 * null | `'null'` | `math.typeOf(null)`
14775 * number | `'number'` | `math.typeOf(3.5)`
14776 * boolean | `'boolean'` | `math.typeOf(true)`
14777 * string | `'string'` | `math.typeOf('hello world')`
14778 * Array | `'Array'` | `math.typeOf([1, 2, 3])`
14779 * Date | `'Date'` | `math.typeOf(new Date())`
14780 * Function | `'Function'` | `math.typeOf(function () {})`
14781 * Object | `'Object'` | `math.typeOf({a: 2, b: 3})`
14782 * RegExp | `'RegExp'` | `math.typeOf(/a regexp/)`
14783 * undefined | `'undefined'` | `math.typeOf(undefined)`
14784 * math.BigNumber | `'BigNumber'` | `math.typeOf(math.bignumber('2.3e500'))`
14785 * math.Chain | `'Chain'` | `math.typeOf(math.chain(2))`
14786 * math.Complex | `'Complex'` | `math.typeOf(math.complex(2, 3))`
14787 * math.Fraction | `'Fraction'` | `math.typeOf(math.fraction(1, 3))`
14788 * math.Help | `'Help'` | `math.typeOf(math.help('sqrt'))`
14789 * math.Help | `'Help'` | `math.typeOf(math.help('sqrt'))`
14790 * math.Index | `'Index'` | `math.typeOf(math.index(1, 3))`
14791 * math.Matrix | `'Matrix'` | `math.typeOf(math.matrix([[1,2], [3, 4]]))`
14792 * math.Range | `'Range'` | `math.typeOf(math.range(0, 10))`
14793 * math.ResultSet | `'ResultSet'` | `math.typeOf(math.evaluate('a=2\nb=3'))`
14794 * math.Unit | `'Unit'` | `math.typeOf(math.unit('45 deg'))`
14795 * math.AccessorNode | `'AccessorNode'` | `math.typeOf(math.parse('A[2]'))`
14796 * math.ArrayNode | `'ArrayNode'` | `math.typeOf(math.parse('[1,2,3]'))`
14797 * math.AssignmentNode | `'AssignmentNode'` | `math.typeOf(math.parse('x=2'))`
14798 * math.BlockNode | `'BlockNode'` | `math.typeOf(math.parse('a=2; b=3'))`
14799 * math.ConditionalNode | `'ConditionalNode'` | `math.typeOf(math.parse('x<0 ? -x : x'))`
14800 * math.ConstantNode | `'ConstantNode'` | `math.typeOf(math.parse('2.3'))`
14801 * math.FunctionAssignmentNode | `'FunctionAssignmentNode'` | `math.typeOf(math.parse('f(x)=x^2'))`
14802 * math.FunctionNode | `'FunctionNode'` | `math.typeOf(math.parse('sqrt(4)'))`
14803 * math.IndexNode | `'IndexNode'` | `math.typeOf(math.parse('A[2]').index)`
14804 * math.ObjectNode | `'ObjectNode'` | `math.typeOf(math.parse('{a:2}'))`
14805 * math.ParenthesisNode | `'ParenthesisNode'` | `math.typeOf(math.parse('(2+3)'))`
14806 * math.RangeNode | `'RangeNode'` | `math.typeOf(math.parse('1:10'))`
14807 * math.SymbolNode | `'SymbolNode'` | `math.typeOf(math.parse('x'))`
14808 *
14809 * Syntax:
14810 *
14811 * math.typeOf(x)
14812 *
14813 * Examples:
14814 *
14815 * math.typeOf(3.5) // returns 'number'
14816 * math.typeOf(math.complex('2-4i')) // returns 'Complex'
14817 * math.typeOf(math.unit('45 deg')) // returns 'Unit'
14818 * math.typeOf('hello world') // returns 'string'
14819 *
14820 * @param {*} x The variable for which to test the type.
14821 * @return {string} Returns the name of the type. Primitive types are lower case,
14822 * non-primitive types are upper-camel-case.
14823 * For example 'number', 'string', 'Array', 'Date'.
14824 */
14825 return typed(typeOf_name, {
14826 any: is["M" /* typeOf */]
14827 });
14828}); // For backward compatibility, deprecated since version 6.0.0. Date: 2018-11-06
14829
14830var createDeprecatedTypeof =
14831/* #__PURE__ */
14832Object(factory["a" /* factory */])('typeof', [], function () {
14833 return function () {
14834 Object(utils_log["a" /* warnOnce */])('Function "typeof" has been renamed to "typeOf" in v6.0.0, please use the new function instead.');
14835
14836 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
14837 args[_key] = arguments[_key];
14838 }
14839
14840 return is["M" /* typeOf */].apply(is["M" /* typeOf */], args);
14841 };
14842});
14843// CONCATENATED MODULE: ./src/utils/bignumber/nearlyEqual.js
14844/**
14845 * Compares two BigNumbers.
14846 * @param {BigNumber} x First value to compare
14847 * @param {BigNumber} y Second value to compare
14848 * @param {number} [epsilon] The maximum relative difference between x and y
14849 * If epsilon is undefined or null, the function will
14850 * test whether x and y are exactly equal.
14851 * @return {boolean} whether the two numbers are nearly equal
14852 */
14853function nearlyEqual(x, y, epsilon) {
14854 // if epsilon is null or undefined, test whether x and y are exactly equal
14855 if (epsilon === null || epsilon === undefined) {
14856 return x.eq(y);
14857 } // use "==" operator, handles infinities
14858
14859
14860 if (x.eq(y)) {
14861 return true;
14862 } // NaN
14863
14864
14865 if (x.isNaN() || y.isNaN()) {
14866 return false;
14867 } // at this point x and y should be finite
14868
14869
14870 if (x.isFinite() && y.isFinite()) {
14871 // check numbers are very close, needed when comparing numbers near zero
14872 var diff = x.minus(y).abs();
14873
14874 if (diff.isZero()) {
14875 return true;
14876 } else {
14877 // use relative error
14878 var max = x.constructor.max(x.abs(), y.abs());
14879 return diff.lte(max.times(epsilon));
14880 }
14881 } // Infinite and Number or negative Infinite and positive Infinite cases
14882
14883
14884 return false;
14885}
14886// CONCATENATED MODULE: ./src/utils/complex.js
14887
14888/**
14889 * Test whether two complex values are equal provided a given epsilon.
14890 * Does not use or change the global Complex.EPSILON setting
14891 * @param {Complex} x
14892 * @param {Complex} y
14893 * @param {number} epsilon
14894 * @returns {boolean}
14895 */
14896
14897function complexEquals(x, y, epsilon) {
14898 return Object(utils_number["m" /* nearlyEqual */])(x.re, y.re, epsilon) && Object(utils_number["m" /* nearlyEqual */])(x.im, y.im, epsilon);
14899}
14900// CONCATENATED MODULE: ./src/function/relational/equalScalar.js
14901
14902
14903
14904
14905var equalScalar_name = 'equalScalar';
14906var equalScalar_dependencies = ['typed', 'config'];
14907var createEqualScalar =
14908/* #__PURE__ */
14909Object(factory["a" /* factory */])(equalScalar_name, equalScalar_dependencies, function (_ref) {
14910 var typed = _ref.typed,
14911 config = _ref.config;
14912
14913 /**
14914 * Test whether two scalar values are nearly equal.
14915 *
14916 * @param {number | BigNumber | Fraction | boolean | Complex | Unit} x First value to compare
14917 * @param {number | BigNumber | Fraction | boolean | Complex} y Second value to compare
14918 * @return {boolean} Returns true when the compared values are equal, else returns false
14919 * @private
14920 */
14921 var equalScalar = typed(equalScalar_name, {
14922 'boolean, boolean': function booleanBoolean(x, y) {
14923 return x === y;
14924 },
14925 'number, number': function numberNumber(x, y) {
14926 return Object(utils_number["m" /* nearlyEqual */])(x, y, config.epsilon);
14927 },
14928 'BigNumber, BigNumber': function BigNumberBigNumber(x, y) {
14929 return x.eq(y) || nearlyEqual(x, y, config.epsilon);
14930 },
14931 'Fraction, Fraction': function FractionFraction(x, y) {
14932 return x.equals(y);
14933 },
14934 'Complex, Complex': function ComplexComplex(x, y) {
14935 return complexEquals(x, y, config.epsilon);
14936 },
14937 'Unit, Unit': function UnitUnit(x, y) {
14938 if (!x.equalBase(y)) {
14939 throw new Error('Cannot compare units with different base');
14940 }
14941
14942 return equalScalar(x.value, y.value);
14943 }
14944 });
14945 return equalScalar;
14946});
14947var createEqualScalarNumber = Object(factory["a" /* factory */])(equalScalar_name, ['typed', 'config'], function (_ref2) {
14948 var typed = _ref2.typed,
14949 config = _ref2.config;
14950 return typed(equalScalar_name, {
14951 'number, number': function numberNumber(x, y) {
14952 return Object(utils_number["m" /* nearlyEqual */])(x, y, config.epsilon);
14953 }
14954 });
14955});
14956// CONCATENATED MODULE: ./src/type/matrix/SparseMatrix.js
14957
14958
14959
14960
14961
14962
14963
14964var SparseMatrix_name = 'SparseMatrix';
14965var SparseMatrix_dependencies = ['typed', 'equalScalar', 'Matrix'];
14966var createSparseMatrixClass =
14967/* #__PURE__ */
14968Object(factory["a" /* factory */])(SparseMatrix_name, SparseMatrix_dependencies, function (_ref) {
14969 var typed = _ref.typed,
14970 equalScalar = _ref.equalScalar,
14971 Matrix = _ref.Matrix;
14972
14973 /**
14974 * Sparse Matrix implementation. This type implements a Compressed Column Storage format
14975 * for sparse matrices.
14976 * @class SparseMatrix
14977 */
14978 function SparseMatrix(data, datatype) {
14979 if (!(this instanceof SparseMatrix)) {
14980 throw new SyntaxError('Constructor must be called with the new operator');
14981 }
14982
14983 if (datatype && !Object(is["I" /* isString */])(datatype)) {
14984 throw new Error('Invalid datatype: ' + datatype);
14985 }
14986
14987 if (Object(is["v" /* isMatrix */])(data)) {
14988 // create from matrix
14989 _createFromMatrix(this, data, datatype);
14990 } else if (data && Object(is["b" /* isArray */])(data.index) && Object(is["b" /* isArray */])(data.ptr) && Object(is["b" /* isArray */])(data.size)) {
14991 // initialize fields
14992 this._values = data.values;
14993 this._index = data.index;
14994 this._ptr = data.ptr;
14995 this._size = data.size;
14996 this._datatype = datatype || data.datatype;
14997 } else if (Object(is["b" /* isArray */])(data)) {
14998 // create from array
14999 _createFromArray(this, data, datatype);
15000 } else if (data) {
15001 // unsupported type
15002 throw new TypeError('Unsupported type of data (' + Object(is["M" /* typeOf */])(data) + ')');
15003 } else {
15004 // nothing provided
15005 this._values = [];
15006 this._index = [];
15007 this._ptr = [0];
15008 this._size = [0, 0];
15009 this._datatype = datatype;
15010 }
15011 }
15012
15013 function _createFromMatrix(matrix, source, datatype) {
15014 // check matrix type
15015 if (source.type === 'SparseMatrix') {
15016 // clone arrays
15017 matrix._values = source._values ? Object(utils_object["a" /* clone */])(source._values) : undefined;
15018 matrix._index = Object(utils_object["a" /* clone */])(source._index);
15019 matrix._ptr = Object(utils_object["a" /* clone */])(source._ptr);
15020 matrix._size = Object(utils_object["a" /* clone */])(source._size);
15021 matrix._datatype = datatype || source._datatype;
15022 } else {
15023 // build from matrix data
15024 _createFromArray(matrix, source.valueOf(), datatype || source._datatype);
15025 }
15026 }
15027
15028 function _createFromArray(matrix, data, datatype) {
15029 // initialize fields
15030 matrix._values = [];
15031 matrix._index = [];
15032 matrix._ptr = [];
15033 matrix._datatype = datatype; // discover rows & columns, do not use math.size() to avoid looping array twice
15034
15035 var rows = data.length;
15036 var columns = 0; // equal signature to use
15037
15038 var eq = equalScalar; // zero value
15039
15040 var zero = 0;
15041
15042 if (Object(is["I" /* isString */])(datatype)) {
15043 // find signature that matches (datatype, datatype)
15044 eq = typed.find(equalScalar, [datatype, datatype]) || equalScalar; // convert 0 to the same datatype
15045
15046 zero = typed.convert(0, datatype);
15047 } // check we have rows (empty array)
15048
15049
15050 if (rows > 0) {
15051 // column index
15052 var j = 0;
15053
15054 do {
15055 // store pointer to values index
15056 matrix._ptr.push(matrix._index.length); // loop rows
15057
15058
15059 for (var i = 0; i < rows; i++) {
15060 // current row
15061 var row = data[i]; // check row is an array
15062
15063 if (Object(is["b" /* isArray */])(row)) {
15064 // update columns if needed (only on first column)
15065 if (j === 0 && columns < row.length) {
15066 columns = row.length;
15067 } // check row has column
15068
15069
15070 if (j < row.length) {
15071 // value
15072 var v = row[j]; // check value != 0
15073
15074 if (!eq(v, zero)) {
15075 // store value
15076 matrix._values.push(v); // index
15077
15078
15079 matrix._index.push(i);
15080 }
15081 }
15082 } else {
15083 // update columns if needed (only on first column)
15084 if (j === 0 && columns < 1) {
15085 columns = 1;
15086 } // check value != 0 (row is a scalar)
15087
15088
15089 if (!eq(row, zero)) {
15090 // store value
15091 matrix._values.push(row); // index
15092
15093
15094 matrix._index.push(i);
15095 }
15096 }
15097 } // increment index
15098
15099
15100 j++;
15101 } while (j < columns);
15102 } // store number of values in ptr
15103
15104
15105 matrix._ptr.push(matrix._index.length); // size
15106
15107
15108 matrix._size = [rows, columns];
15109 }
15110
15111 SparseMatrix.prototype = new Matrix();
15112 /**
15113 * Create a new SparseMatrix
15114 */
15115
15116 SparseMatrix.prototype.createSparseMatrix = function (data, datatype) {
15117 return new SparseMatrix(data, datatype);
15118 };
15119 /**
15120 * Attach type information
15121 */
15122
15123
15124 SparseMatrix.prototype.type = 'SparseMatrix';
15125 SparseMatrix.prototype.isSparseMatrix = true;
15126 /**
15127 * Get the matrix type
15128 *
15129 * Usage:
15130 * const matrixType = matrix.getDataType() // retrieves the matrix type
15131 *
15132 * @memberOf SparseMatrix
15133 * @return {string} type information; if multiple types are found from the Matrix, it will return "mixed"
15134 */
15135
15136 SparseMatrix.prototype.getDataType = function () {
15137 return Object(utils_array["h" /* getArrayDataType */])(this._values, is["M" /* typeOf */]);
15138 };
15139 /**
15140 * Get the storage format used by the matrix.
15141 *
15142 * Usage:
15143 * const format = matrix.storage() // retrieve storage format
15144 *
15145 * @memberof SparseMatrix
15146 * @return {string} The storage format.
15147 */
15148
15149
15150 SparseMatrix.prototype.storage = function () {
15151 return 'sparse';
15152 };
15153 /**
15154 * Get the datatype of the data stored in the matrix.
15155 *
15156 * Usage:
15157 * const format = matrix.datatype() // retrieve matrix datatype
15158 *
15159 * @memberof SparseMatrix
15160 * @return {string} The datatype.
15161 */
15162
15163
15164 SparseMatrix.prototype.datatype = function () {
15165 return this._datatype;
15166 };
15167 /**
15168 * Create a new SparseMatrix
15169 * @memberof SparseMatrix
15170 * @param {Array} data
15171 * @param {string} [datatype]
15172 */
15173
15174
15175 SparseMatrix.prototype.create = function (data, datatype) {
15176 return new SparseMatrix(data, datatype);
15177 };
15178 /**
15179 * Get the matrix density.
15180 *
15181 * Usage:
15182 * const density = matrix.density() // retrieve matrix density
15183 *
15184 * @memberof SparseMatrix
15185 * @return {number} The matrix density.
15186 */
15187
15188
15189 SparseMatrix.prototype.density = function () {
15190 // rows & columns
15191 var rows = this._size[0];
15192 var columns = this._size[1]; // calculate density
15193
15194 return rows !== 0 && columns !== 0 ? this._index.length / (rows * columns) : 0;
15195 };
15196 /**
15197 * Get a subset of the matrix, or replace a subset of the matrix.
15198 *
15199 * Usage:
15200 * const subset = matrix.subset(index) // retrieve subset
15201 * const value = matrix.subset(index, replacement) // replace subset
15202 *
15203 * @memberof SparseMatrix
15204 * @param {Index} index
15205 * @param {Array | Matrix | *} [replacement]
15206 * @param {*} [defaultValue=0] Default value, filled in on new entries when
15207 * the matrix is resized. If not provided,
15208 * new matrix elements will be filled with zeros.
15209 */
15210
15211
15212 SparseMatrix.prototype.subset = function (index, replacement, defaultValue) {
15213 // check it is a pattern matrix
15214 if (!this._values) {
15215 throw new Error('Cannot invoke subset on a Pattern only matrix');
15216 } // check arguments
15217
15218
15219 switch (arguments.length) {
15220 case 1:
15221 return _getsubset(this, index);
15222 // intentional fall through
15223
15224 case 2:
15225 case 3:
15226 return _setsubset(this, index, replacement, defaultValue);
15227
15228 default:
15229 throw new SyntaxError('Wrong number of arguments');
15230 }
15231 };
15232
15233 function _getsubset(matrix, idx) {
15234 // check idx
15235 if (!Object(is["t" /* isIndex */])(idx)) {
15236 throw new TypeError('Invalid index');
15237 }
15238
15239 var isScalar = idx.isScalar();
15240
15241 if (isScalar) {
15242 // return a scalar
15243 return matrix.get(idx.min());
15244 } // validate dimensions
15245
15246
15247 var size = idx.size();
15248
15249 if (size.length !== matrix._size.length) {
15250 throw new DimensionError["a" /* DimensionError */](size.length, matrix._size.length);
15251 } // vars
15252
15253
15254 var i, ii, k, kk; // validate if any of the ranges in the index is out of range
15255
15256 var min = idx.min();
15257 var max = idx.max();
15258
15259 for (i = 0, ii = matrix._size.length; i < ii; i++) {
15260 Object(utils_array["s" /* validateIndex */])(min[i], matrix._size[i]);
15261 Object(utils_array["s" /* validateIndex */])(max[i], matrix._size[i]);
15262 } // matrix arrays
15263
15264
15265 var mvalues = matrix._values;
15266 var mindex = matrix._index;
15267 var mptr = matrix._ptr; // rows & columns dimensions for result matrix
15268
15269 var rows = idx.dimension(0);
15270 var columns = idx.dimension(1); // workspace & permutation vector
15271
15272 var w = [];
15273 var pv = []; // loop rows in resulting matrix
15274
15275 rows.forEach(function (i, r) {
15276 // update permutation vector
15277 pv[i] = r[0]; // mark i in workspace
15278
15279 w[i] = true;
15280 }); // result matrix arrays
15281
15282 var values = mvalues ? [] : undefined;
15283 var index = [];
15284 var ptr = []; // loop columns in result matrix
15285
15286 columns.forEach(function (j) {
15287 // update ptr
15288 ptr.push(index.length); // loop values in column j
15289
15290 for (k = mptr[j], kk = mptr[j + 1]; k < kk; k++) {
15291 // row
15292 i = mindex[k]; // check row is in result matrix
15293
15294 if (w[i] === true) {
15295 // push index
15296 index.push(pv[i]); // check we need to process values
15297
15298 if (values) {
15299 values.push(mvalues[k]);
15300 }
15301 }
15302 }
15303 }); // update ptr
15304
15305 ptr.push(index.length); // return matrix
15306
15307 return new SparseMatrix({
15308 values: values,
15309 index: index,
15310 ptr: ptr,
15311 size: size,
15312 datatype: matrix._datatype
15313 });
15314 }
15315
15316 function _setsubset(matrix, index, submatrix, defaultValue) {
15317 // check index
15318 if (!index || index.isIndex !== true) {
15319 throw new TypeError('Invalid index');
15320 } // get index size and check whether the index contains a single value
15321
15322
15323 var iSize = index.size();
15324 var isScalar = index.isScalar(); // calculate the size of the submatrix, and convert it into an Array if needed
15325
15326 var sSize;
15327
15328 if (Object(is["v" /* isMatrix */])(submatrix)) {
15329 // submatrix size
15330 sSize = submatrix.size(); // use array representation
15331
15332 submatrix = submatrix.toArray();
15333 } else {
15334 // get submatrix size (array, scalar)
15335 sSize = Object(utils_array["a" /* arraySize */])(submatrix);
15336 } // check index is a scalar
15337
15338
15339 if (isScalar) {
15340 // verify submatrix is a scalar
15341 if (sSize.length !== 0) {
15342 throw new TypeError('Scalar expected');
15343 } // set value
15344
15345
15346 matrix.set(index.min(), submatrix, defaultValue);
15347 } else {
15348 // validate dimensions, index size must be one or two dimensions
15349 if (iSize.length !== 1 && iSize.length !== 2) {
15350 throw new DimensionError["a" /* DimensionError */](iSize.length, matrix._size.length, '<');
15351 } // check submatrix and index have the same dimensions
15352
15353
15354 if (sSize.length < iSize.length) {
15355 // calculate number of missing outer dimensions
15356 var i = 0;
15357 var outer = 0;
15358
15359 while (iSize[i] === 1 && sSize[i] === 1) {
15360 i++;
15361 }
15362
15363 while (iSize[i] === 1) {
15364 outer++;
15365 i++;
15366 } // unsqueeze both outer and inner dimensions
15367
15368
15369 submatrix = Object(utils_array["q" /* unsqueeze */])(submatrix, iSize.length, outer, sSize);
15370 } // check whether the size of the submatrix matches the index size
15371
15372
15373 if (!Object(utils_object["d" /* deepStrictEqual */])(iSize, sSize)) {
15374 throw new DimensionError["a" /* DimensionError */](iSize, sSize, '>');
15375 } // offsets
15376
15377
15378 var x0 = index.min()[0];
15379 var y0 = index.min()[1]; // submatrix rows and columns
15380
15381 var m = sSize[0];
15382 var n = sSize[1]; // loop submatrix
15383
15384 for (var x = 0; x < m; x++) {
15385 // loop columns
15386 for (var y = 0; y < n; y++) {
15387 // value at i, j
15388 var v = submatrix[x][y]; // invoke set (zero value will remove entry from matrix)
15389
15390 matrix.set([x + x0, y + y0], v, defaultValue);
15391 }
15392 }
15393 }
15394
15395 return matrix;
15396 }
15397 /**
15398 * Get a single element from the matrix.
15399 * @memberof SparseMatrix
15400 * @param {number[]} index Zero-based index
15401 * @return {*} value
15402 */
15403
15404
15405 SparseMatrix.prototype.get = function (index) {
15406 if (!Object(is["b" /* isArray */])(index)) {
15407 throw new TypeError('Array expected');
15408 }
15409
15410 if (index.length !== this._size.length) {
15411 throw new DimensionError["a" /* DimensionError */](index.length, this._size.length);
15412 } // check it is a pattern matrix
15413
15414
15415 if (!this._values) {
15416 throw new Error('Cannot invoke get on a Pattern only matrix');
15417 } // row and column
15418
15419
15420 var i = index[0];
15421 var j = index[1]; // check i, j are valid
15422
15423 Object(utils_array["s" /* validateIndex */])(i, this._size[0]);
15424 Object(utils_array["s" /* validateIndex */])(j, this._size[1]); // find value index
15425
15426 var k = _getValueIndex(i, this._ptr[j], this._ptr[j + 1], this._index); // check k is prior to next column k and it is in the correct row
15427
15428
15429 if (k < this._ptr[j + 1] && this._index[k] === i) {
15430 return this._values[k];
15431 }
15432
15433 return 0;
15434 };
15435 /**
15436 * Replace a single element in the matrix.
15437 * @memberof SparseMatrix
15438 * @param {number[]} index Zero-based index
15439 * @param {*} v
15440 * @param {*} [defaultValue] Default value, filled in on new entries when
15441 * the matrix is resized. If not provided,
15442 * new matrix elements will be set to zero.
15443 * @return {SparseMatrix} self
15444 */
15445
15446
15447 SparseMatrix.prototype.set = function (index, v, defaultValue) {
15448 if (!Object(is["b" /* isArray */])(index)) {
15449 throw new TypeError('Array expected');
15450 }
15451
15452 if (index.length !== this._size.length) {
15453 throw new DimensionError["a" /* DimensionError */](index.length, this._size.length);
15454 } // check it is a pattern matrix
15455
15456
15457 if (!this._values) {
15458 throw new Error('Cannot invoke set on a Pattern only matrix');
15459 } // row and column
15460
15461
15462 var i = index[0];
15463 var j = index[1]; // rows & columns
15464
15465 var rows = this._size[0];
15466 var columns = this._size[1]; // equal signature to use
15467
15468 var eq = equalScalar; // zero value
15469
15470 var zero = 0;
15471
15472 if (Object(is["I" /* isString */])(this._datatype)) {
15473 // find signature that matches (datatype, datatype)
15474 eq = typed.find(equalScalar, [this._datatype, this._datatype]) || equalScalar; // convert 0 to the same datatype
15475
15476 zero = typed.convert(0, this._datatype);
15477 } // check we need to resize matrix
15478
15479
15480 if (i > rows - 1 || j > columns - 1) {
15481 // resize matrix
15482 _resize(this, Math.max(i + 1, rows), Math.max(j + 1, columns), defaultValue); // update rows & columns
15483
15484
15485 rows = this._size[0];
15486 columns = this._size[1];
15487 } // check i, j are valid
15488
15489
15490 Object(utils_array["s" /* validateIndex */])(i, rows);
15491 Object(utils_array["s" /* validateIndex */])(j, columns); // find value index
15492
15493 var k = _getValueIndex(i, this._ptr[j], this._ptr[j + 1], this._index); // check k is prior to next column k and it is in the correct row
15494
15495
15496 if (k < this._ptr[j + 1] && this._index[k] === i) {
15497 // check value != 0
15498 if (!eq(v, zero)) {
15499 // update value
15500 this._values[k] = v;
15501 } else {
15502 // remove value from matrix
15503 _remove(k, j, this._values, this._index, this._ptr);
15504 }
15505 } else {
15506 // insert value @ (i, j)
15507 _insert(k, i, j, v, this._values, this._index, this._ptr);
15508 }
15509
15510 return this;
15511 };
15512
15513 function _getValueIndex(i, top, bottom, index) {
15514 // check row is on the bottom side
15515 if (bottom - top === 0) {
15516 return bottom;
15517 } // loop rows [top, bottom[
15518
15519
15520 for (var r = top; r < bottom; r++) {
15521 // check we found value index
15522 if (index[r] === i) {
15523 return r;
15524 }
15525 } // we did not find row
15526
15527
15528 return top;
15529 }
15530
15531 function _remove(k, j, values, index, ptr) {
15532 // remove value @ k
15533 values.splice(k, 1);
15534 index.splice(k, 1); // update pointers
15535
15536 for (var x = j + 1; x < ptr.length; x++) {
15537 ptr[x]--;
15538 }
15539 }
15540
15541 function _insert(k, i, j, v, values, index, ptr) {
15542 // insert value
15543 values.splice(k, 0, v); // update row for k
15544
15545 index.splice(k, 0, i); // update column pointers
15546
15547 for (var x = j + 1; x < ptr.length; x++) {
15548 ptr[x]++;
15549 }
15550 }
15551 /**
15552 * Resize the matrix to the given size. Returns a copy of the matrix when
15553 * `copy=true`, otherwise return the matrix itself (resize in place).
15554 *
15555 * @memberof SparseMatrix
15556 * @param {number[]} size The new size the matrix should have.
15557 * @param {*} [defaultValue=0] Default value, filled in on new entries.
15558 * If not provided, the matrix elements will
15559 * be filled with zeros.
15560 * @param {boolean} [copy] Return a resized copy of the matrix
15561 *
15562 * @return {Matrix} The resized matrix
15563 */
15564
15565
15566 SparseMatrix.prototype.resize = function (size, defaultValue, copy) {
15567 // validate arguments
15568 if (!Object(is["b" /* isArray */])(size)) {
15569 throw new TypeError('Array expected');
15570 }
15571
15572 if (size.length !== 2) {
15573 throw new Error('Only two dimensions matrix are supported');
15574 } // check sizes
15575
15576
15577 size.forEach(function (value) {
15578 if (!Object(is["y" /* isNumber */])(value) || !Object(utils_number["i" /* isInteger */])(value) || value < 0) {
15579 throw new TypeError('Invalid size, must contain positive integers ' + '(size: ' + Object(utils_string["d" /* format */])(size) + ')');
15580 }
15581 }); // matrix to resize
15582
15583 var m = copy ? this.clone() : this; // resize matrix
15584
15585 return _resize(m, size[0], size[1], defaultValue);
15586 };
15587
15588 function _resize(matrix, rows, columns, defaultValue) {
15589 // value to insert at the time of growing matrix
15590 var value = defaultValue || 0; // equal signature to use
15591
15592 var eq = equalScalar; // zero value
15593
15594 var zero = 0;
15595
15596 if (Object(is["I" /* isString */])(matrix._datatype)) {
15597 // find signature that matches (datatype, datatype)
15598 eq = typed.find(equalScalar, [matrix._datatype, matrix._datatype]) || equalScalar; // convert 0 to the same datatype
15599
15600 zero = typed.convert(0, matrix._datatype); // convert value to the same datatype
15601
15602 value = typed.convert(value, matrix._datatype);
15603 } // should we insert the value?
15604
15605
15606 var ins = !eq(value, zero); // old columns and rows
15607
15608 var r = matrix._size[0];
15609 var c = matrix._size[1];
15610 var i, j, k; // check we need to increase columns
15611
15612 if (columns > c) {
15613 // loop new columns
15614 for (j = c; j < columns; j++) {
15615 // update matrix._ptr for current column
15616 matrix._ptr[j] = matrix._values.length; // check we need to insert matrix._values
15617
15618 if (ins) {
15619 // loop rows
15620 for (i = 0; i < r; i++) {
15621 // add new matrix._values
15622 matrix._values.push(value); // update matrix._index
15623
15624
15625 matrix._index.push(i);
15626 }
15627 }
15628 } // store number of matrix._values in matrix._ptr
15629
15630
15631 matrix._ptr[columns] = matrix._values.length;
15632 } else if (columns < c) {
15633 // truncate matrix._ptr
15634 matrix._ptr.splice(columns + 1, c - columns); // truncate matrix._values and matrix._index
15635
15636
15637 matrix._values.splice(matrix._ptr[columns], matrix._values.length);
15638
15639 matrix._index.splice(matrix._ptr[columns], matrix._index.length);
15640 } // update columns
15641
15642
15643 c = columns; // check we need to increase rows
15644
15645 if (rows > r) {
15646 // check we have to insert values
15647 if (ins) {
15648 // inserts
15649 var n = 0; // loop columns
15650
15651 for (j = 0; j < c; j++) {
15652 // update matrix._ptr for current column
15653 matrix._ptr[j] = matrix._ptr[j] + n; // where to insert matrix._values
15654
15655 k = matrix._ptr[j + 1] + n; // pointer
15656
15657 var p = 0; // loop new rows, initialize pointer
15658
15659 for (i = r; i < rows; i++, p++) {
15660 // add value
15661 matrix._values.splice(k + p, 0, value); // update matrix._index
15662
15663
15664 matrix._index.splice(k + p, 0, i); // increment inserts
15665
15666
15667 n++;
15668 }
15669 } // store number of matrix._values in matrix._ptr
15670
15671
15672 matrix._ptr[c] = matrix._values.length;
15673 }
15674 } else if (rows < r) {
15675 // deletes
15676 var d = 0; // loop columns
15677
15678 for (j = 0; j < c; j++) {
15679 // update matrix._ptr for current column
15680 matrix._ptr[j] = matrix._ptr[j] - d; // where matrix._values start for next column
15681
15682 var k0 = matrix._ptr[j];
15683 var k1 = matrix._ptr[j + 1] - d; // loop matrix._index
15684
15685 for (k = k0; k < k1; k++) {
15686 // row
15687 i = matrix._index[k]; // check we need to delete value and matrix._index
15688
15689 if (i > rows - 1) {
15690 // remove value
15691 matrix._values.splice(k, 1); // remove item from matrix._index
15692
15693
15694 matrix._index.splice(k, 1); // increase deletes
15695
15696
15697 d++;
15698 }
15699 }
15700 } // update matrix._ptr for current column
15701
15702
15703 matrix._ptr[j] = matrix._values.length;
15704 } // update matrix._size
15705
15706
15707 matrix._size[0] = rows;
15708 matrix._size[1] = columns; // return matrix
15709
15710 return matrix;
15711 }
15712 /**
15713 * Reshape the matrix to the given size. Returns a copy of the matrix when
15714 * `copy=true`, otherwise return the matrix itself (reshape in place).
15715 *
15716 * NOTE: This might be better suited to copy by default, instead of modifying
15717 * in place. For now, it operates in place to remain consistent with
15718 * resize().
15719 *
15720 * @memberof SparseMatrix
15721 * @param {number[]} size The new size the matrix should have.
15722 * @param {boolean} [copy] Return a reshaped copy of the matrix
15723 *
15724 * @return {Matrix} The reshaped matrix
15725 */
15726
15727
15728 SparseMatrix.prototype.reshape = function (size, copy) {
15729 // validate arguments
15730 if (!Object(is["b" /* isArray */])(size)) {
15731 throw new TypeError('Array expected');
15732 }
15733
15734 if (size.length !== 2) {
15735 throw new Error('Sparse matrices can only be reshaped in two dimensions');
15736 } // check sizes
15737
15738
15739 size.forEach(function (value) {
15740 if (!Object(is["y" /* isNumber */])(value) || !Object(utils_number["i" /* isInteger */])(value) || value < 0) {
15741 throw new TypeError('Invalid size, must contain positive integers ' + '(size: ' + Object(utils_string["d" /* format */])(size) + ')');
15742 }
15743 }); // m * n must not change
15744
15745 if (this._size[0] * this._size[1] !== size[0] * size[1]) {
15746 throw new Error('Reshaping sparse matrix will result in the wrong number of elements');
15747 } // matrix to reshape
15748
15749
15750 var m = copy ? this.clone() : this; // return unchanged if the same shape
15751
15752 if (this._size[0] === size[0] && this._size[1] === size[1]) {
15753 return m;
15754 } // Convert to COO format (generate a column index)
15755
15756
15757 var colIndex = [];
15758
15759 for (var i = 0; i < m._ptr.length; i++) {
15760 for (var j = 0; j < m._ptr[i + 1] - m._ptr[i]; j++) {
15761 colIndex.push(i);
15762 }
15763 } // Clone the values array
15764
15765
15766 var values = m._values.slice(); // Clone the row index array
15767
15768
15769 var rowIndex = m._index.slice(); // Transform the (row, column) indices
15770
15771
15772 for (var _i = 0; _i < m._index.length; _i++) {
15773 var r1 = rowIndex[_i];
15774 var c1 = colIndex[_i];
15775 var flat = r1 * m._size[1] + c1;
15776 colIndex[_i] = flat % size[1];
15777 rowIndex[_i] = Math.floor(flat / size[1]);
15778 } // Now reshaping is supposed to preserve the row-major order, BUT these sparse matrices are stored
15779 // in column-major order, so we have to reorder the value array now. One option is to use a multisort,
15780 // sorting several arrays based on some other array.
15781 // OR, we could easily just:
15782 // 1. Remove all values from the matrix
15783
15784
15785 m._values.length = 0;
15786 m._index.length = 0;
15787 m._ptr.length = size[1] + 1;
15788 m._size = size.slice();
15789
15790 for (var _i2 = 0; _i2 < m._ptr.length; _i2++) {
15791 m._ptr[_i2] = 0;
15792 } // 2. Re-insert all elements in the proper order (simplified code from SparseMatrix.prototype.set)
15793 // This step is probably the most time-consuming
15794
15795
15796 for (var h = 0; h < values.length; h++) {
15797 var _i3 = rowIndex[h];
15798 var _j = colIndex[h];
15799 var v = values[h];
15800
15801 var k = _getValueIndex(_i3, m._ptr[_j], m._ptr[_j + 1], m._index);
15802
15803 _insert(k, _i3, _j, v, m._values, m._index, m._ptr);
15804 } // The value indices are inserted out of order, but apparently that's... still OK?
15805
15806
15807 return m;
15808 };
15809 /**
15810 * Create a clone of the matrix
15811 * @memberof SparseMatrix
15812 * @return {SparseMatrix} clone
15813 */
15814
15815
15816 SparseMatrix.prototype.clone = function () {
15817 var m = new SparseMatrix({
15818 values: this._values ? Object(utils_object["a" /* clone */])(this._values) : undefined,
15819 index: Object(utils_object["a" /* clone */])(this._index),
15820 ptr: Object(utils_object["a" /* clone */])(this._ptr),
15821 size: Object(utils_object["a" /* clone */])(this._size),
15822 datatype: this._datatype
15823 });
15824 return m;
15825 };
15826 /**
15827 * Retrieve the size of the matrix.
15828 * @memberof SparseMatrix
15829 * @returns {number[]} size
15830 */
15831
15832
15833 SparseMatrix.prototype.size = function () {
15834 return this._size.slice(0); // copy the Array
15835 };
15836 /**
15837 * Create a new matrix with the results of the callback function executed on
15838 * each entry of the matrix.
15839 * @memberof SparseMatrix
15840 * @param {Function} callback The callback function is invoked with three
15841 * parameters: the value of the element, the index
15842 * of the element, and the Matrix being traversed.
15843 * @param {boolean} [skipZeros] Invoke callback function for non-zero values only.
15844 *
15845 * @return {SparseMatrix} matrix
15846 */
15847
15848
15849 SparseMatrix.prototype.map = function (callback, skipZeros) {
15850 // check it is a pattern matrix
15851 if (!this._values) {
15852 throw new Error('Cannot invoke map on a Pattern only matrix');
15853 } // matrix instance
15854
15855
15856 var me = this; // rows and columns
15857
15858 var rows = this._size[0];
15859 var columns = this._size[1]; // invoke callback
15860
15861 var invoke = function invoke(v, i, j) {
15862 // invoke callback
15863 return callback(v, [i, j], me);
15864 }; // invoke _map
15865
15866
15867 return _map(this, 0, rows - 1, 0, columns - 1, invoke, skipZeros);
15868 };
15869 /**
15870 * Create a new matrix with the results of the callback function executed on the interval
15871 * [minRow..maxRow, minColumn..maxColumn].
15872 */
15873
15874
15875 function _map(matrix, minRow, maxRow, minColumn, maxColumn, callback, skipZeros) {
15876 // result arrays
15877 var values = [];
15878 var index = [];
15879 var ptr = []; // equal signature to use
15880
15881 var eq = equalScalar; // zero value
15882
15883 var zero = 0;
15884
15885 if (Object(is["I" /* isString */])(matrix._datatype)) {
15886 // find signature that matches (datatype, datatype)
15887 eq = typed.find(equalScalar, [matrix._datatype, matrix._datatype]) || equalScalar; // convert 0 to the same datatype
15888
15889 zero = typed.convert(0, matrix._datatype);
15890 } // invoke callback
15891
15892
15893 var invoke = function invoke(v, x, y) {
15894 // invoke callback
15895 v = callback(v, x, y); // check value != 0
15896
15897 if (!eq(v, zero)) {
15898 // store value
15899 values.push(v); // index
15900
15901 index.push(x);
15902 }
15903 }; // loop columns
15904
15905
15906 for (var j = minColumn; j <= maxColumn; j++) {
15907 // store pointer to values index
15908 ptr.push(values.length); // k0 <= k < k1 where k0 = _ptr[j] && k1 = _ptr[j+1]
15909
15910 var k0 = matrix._ptr[j];
15911 var k1 = matrix._ptr[j + 1];
15912
15913 if (skipZeros) {
15914 // loop k within [k0, k1[
15915 for (var k = k0; k < k1; k++) {
15916 // row index
15917 var i = matrix._index[k]; // check i is in range
15918
15919 if (i >= minRow && i <= maxRow) {
15920 // value @ k
15921 invoke(matrix._values[k], i - minRow, j - minColumn);
15922 }
15923 }
15924 } else {
15925 // create a cache holding all defined values
15926 var _values = {};
15927
15928 for (var _k = k0; _k < k1; _k++) {
15929 var _i4 = matrix._index[_k];
15930 _values[_i4] = matrix._values[_k];
15931 } // loop over all rows (indexes can be unordered so we can't use that),
15932 // and either read the value or zero
15933
15934
15935 for (var _i5 = minRow; _i5 <= maxRow; _i5++) {
15936 var value = _i5 in _values ? _values[_i5] : 0;
15937 invoke(value, _i5 - minRow, j - minColumn);
15938 }
15939 }
15940 } // store number of values in ptr
15941
15942
15943 ptr.push(values.length); // return sparse matrix
15944
15945 return new SparseMatrix({
15946 values: values,
15947 index: index,
15948 ptr: ptr,
15949 size: [maxRow - minRow + 1, maxColumn - minColumn + 1]
15950 });
15951 }
15952 /**
15953 * Execute a callback function on each entry of the matrix.
15954 * @memberof SparseMatrix
15955 * @param {Function} callback The callback function is invoked with three
15956 * parameters: the value of the element, the index
15957 * of the element, and the Matrix being traversed.
15958 * @param {boolean} [skipZeros] Invoke callback function for non-zero values only.
15959 */
15960
15961
15962 SparseMatrix.prototype.forEach = function (callback, skipZeros) {
15963 // check it is a pattern matrix
15964 if (!this._values) {
15965 throw new Error('Cannot invoke forEach on a Pattern only matrix');
15966 } // matrix instance
15967
15968
15969 var me = this; // rows and columns
15970
15971 var rows = this._size[0];
15972 var columns = this._size[1]; // loop columns
15973
15974 for (var j = 0; j < columns; j++) {
15975 // k0 <= k < k1 where k0 = _ptr[j] && k1 = _ptr[j+1]
15976 var k0 = this._ptr[j];
15977 var k1 = this._ptr[j + 1];
15978
15979 if (skipZeros) {
15980 // loop k within [k0, k1[
15981 for (var k = k0; k < k1; k++) {
15982 // row index
15983 var i = this._index[k]; // value @ k
15984
15985 callback(this._values[k], [i, j], me);
15986 }
15987 } else {
15988 // create a cache holding all defined values
15989 var values = {};
15990
15991 for (var _k2 = k0; _k2 < k1; _k2++) {
15992 var _i6 = this._index[_k2];
15993 values[_i6] = this._values[_k2];
15994 } // loop over all rows (indexes can be unordered so we can't use that),
15995 // and either read the value or zero
15996
15997
15998 for (var _i7 = 0; _i7 < rows; _i7++) {
15999 var value = _i7 in values ? values[_i7] : 0;
16000 callback(value, [_i7, j], me);
16001 }
16002 }
16003 }
16004 };
16005 /**
16006 * Create an Array with a copy of the data of the SparseMatrix
16007 * @memberof SparseMatrix
16008 * @returns {Array} array
16009 */
16010
16011
16012 SparseMatrix.prototype.toArray = function () {
16013 return _toArray(this._values, this._index, this._ptr, this._size, true);
16014 };
16015 /**
16016 * Get the primitive value of the SparseMatrix: a two dimensions array
16017 * @memberof SparseMatrix
16018 * @returns {Array} array
16019 */
16020
16021
16022 SparseMatrix.prototype.valueOf = function () {
16023 return _toArray(this._values, this._index, this._ptr, this._size, false);
16024 };
16025
16026 function _toArray(values, index, ptr, size, copy) {
16027 // rows and columns
16028 var rows = size[0];
16029 var columns = size[1]; // result
16030
16031 var a = []; // vars
16032
16033 var i, j; // initialize array
16034
16035 for (i = 0; i < rows; i++) {
16036 a[i] = [];
16037
16038 for (j = 0; j < columns; j++) {
16039 a[i][j] = 0;
16040 }
16041 } // loop columns
16042
16043
16044 for (j = 0; j < columns; j++) {
16045 // k0 <= k < k1 where k0 = _ptr[j] && k1 = _ptr[j+1]
16046 var k0 = ptr[j];
16047 var k1 = ptr[j + 1]; // loop k within [k0, k1[
16048
16049 for (var k = k0; k < k1; k++) {
16050 // row index
16051 i = index[k]; // set value (use one for pattern matrix)
16052
16053 a[i][j] = values ? copy ? Object(utils_object["a" /* clone */])(values[k]) : values[k] : 1;
16054 }
16055 }
16056
16057 return a;
16058 }
16059 /**
16060 * Get a string representation of the matrix, with optional formatting options.
16061 * @memberof SparseMatrix
16062 * @param {Object | number | Function} [options] Formatting options. See
16063 * lib/utils/number:format for a
16064 * description of the available
16065 * options.
16066 * @returns {string} str
16067 */
16068
16069
16070 SparseMatrix.prototype.format = function (options) {
16071 // rows and columns
16072 var rows = this._size[0];
16073 var columns = this._size[1]; // density
16074
16075 var density = this.density(); // rows & columns
16076
16077 var str = 'Sparse Matrix [' + Object(utils_string["d" /* format */])(rows, options) + ' x ' + Object(utils_string["d" /* format */])(columns, options) + '] density: ' + Object(utils_string["d" /* format */])(density, options) + '\n'; // loop columns
16078
16079 for (var j = 0; j < columns; j++) {
16080 // k0 <= k < k1 where k0 = _ptr[j] && k1 = _ptr[j+1]
16081 var k0 = this._ptr[j];
16082 var k1 = this._ptr[j + 1]; // loop k within [k0, k1[
16083
16084 for (var k = k0; k < k1; k++) {
16085 // row index
16086 var i = this._index[k]; // append value
16087
16088 str += '\n (' + Object(utils_string["d" /* format */])(i, options) + ', ' + Object(utils_string["d" /* format */])(j, options) + ') ==> ' + (this._values ? Object(utils_string["d" /* format */])(this._values[k], options) : 'X');
16089 }
16090 }
16091
16092 return str;
16093 };
16094 /**
16095 * Get a string representation of the matrix
16096 * @memberof SparseMatrix
16097 * @returns {string} str
16098 */
16099
16100
16101 SparseMatrix.prototype.toString = function () {
16102 return Object(utils_string["d" /* format */])(this.toArray());
16103 };
16104 /**
16105 * Get a JSON representation of the matrix
16106 * @memberof SparseMatrix
16107 * @returns {Object}
16108 */
16109
16110
16111 SparseMatrix.prototype.toJSON = function () {
16112 return {
16113 mathjs: 'SparseMatrix',
16114 values: this._values,
16115 index: this._index,
16116 ptr: this._ptr,
16117 size: this._size,
16118 datatype: this._datatype
16119 };
16120 };
16121 /**
16122 * Get the kth Matrix diagonal.
16123 *
16124 * @memberof SparseMatrix
16125 * @param {number | BigNumber} [k=0] The kth diagonal where the vector will retrieved.
16126 *
16127 * @returns {Matrix} The matrix vector with the diagonal values.
16128 */
16129
16130
16131 SparseMatrix.prototype.diagonal = function (k) {
16132 // validate k if any
16133 if (k) {
16134 // convert BigNumber to a number
16135 if (Object(is["e" /* isBigNumber */])(k)) {
16136 k = k.toNumber();
16137 } // is must be an integer
16138
16139
16140 if (!Object(is["y" /* isNumber */])(k) || !Object(utils_number["i" /* isInteger */])(k)) {
16141 throw new TypeError('The parameter k must be an integer number');
16142 }
16143 } else {
16144 // default value
16145 k = 0;
16146 }
16147
16148 var kSuper = k > 0 ? k : 0;
16149 var kSub = k < 0 ? -k : 0; // rows & columns
16150
16151 var rows = this._size[0];
16152 var columns = this._size[1]; // number diagonal values
16153
16154 var n = Math.min(rows - kSub, columns - kSuper); // diagonal arrays
16155
16156 var values = [];
16157 var index = [];
16158 var ptr = []; // initial ptr value
16159
16160 ptr[0] = 0; // loop columns
16161
16162 for (var j = kSuper; j < columns && values.length < n; j++) {
16163 // k0 <= k < k1 where k0 = _ptr[j] && k1 = _ptr[j+1]
16164 var k0 = this._ptr[j];
16165 var k1 = this._ptr[j + 1]; // loop x within [k0, k1[
16166
16167 for (var x = k0; x < k1; x++) {
16168 // row index
16169 var i = this._index[x]; // check row
16170
16171 if (i === j - kSuper + kSub) {
16172 // value on this column
16173 values.push(this._values[x]); // store row
16174
16175 index[values.length - 1] = i - kSub; // exit loop
16176
16177 break;
16178 }
16179 }
16180 } // close ptr
16181
16182
16183 ptr.push(values.length); // return matrix
16184
16185 return new SparseMatrix({
16186 values: values,
16187 index: index,
16188 ptr: ptr,
16189 size: [n, 1]
16190 });
16191 };
16192 /**
16193 * Generate a matrix from a JSON object
16194 * @memberof SparseMatrix
16195 * @param {Object} json An object structured like
16196 * `{"mathjs": "SparseMatrix", "values": [], "index": [], "ptr": [], "size": []}`,
16197 * where mathjs is optional
16198 * @returns {SparseMatrix}
16199 */
16200
16201
16202 SparseMatrix.fromJSON = function (json) {
16203 return new SparseMatrix(json);
16204 };
16205 /**
16206 * Create a diagonal matrix.
16207 *
16208 * @memberof SparseMatrix
16209 * @param {Array} size The matrix size.
16210 * @param {number | Array | Matrix } value The values for the diagonal.
16211 * @param {number | BigNumber} [k=0] The kth diagonal where the vector will be filled in.
16212 * @param {number} [defaultValue] The default value for non-diagonal
16213 * @param {string} [datatype] The Matrix datatype, values must be of this datatype.
16214 *
16215 * @returns {SparseMatrix}
16216 */
16217
16218
16219 SparseMatrix.diagonal = function (size, value, k, defaultValue, datatype) {
16220 if (!Object(is["b" /* isArray */])(size)) {
16221 throw new TypeError('Array expected, size parameter');
16222 }
16223
16224 if (size.length !== 2) {
16225 throw new Error('Only two dimensions matrix are supported');
16226 } // map size & validate
16227
16228
16229 size = size.map(function (s) {
16230 // check it is a big number
16231 if (Object(is["e" /* isBigNumber */])(s)) {
16232 // convert it
16233 s = s.toNumber();
16234 } // validate arguments
16235
16236
16237 if (!Object(is["y" /* isNumber */])(s) || !Object(utils_number["i" /* isInteger */])(s) || s < 1) {
16238 throw new Error('Size values must be positive integers');
16239 }
16240
16241 return s;
16242 }); // validate k if any
16243
16244 if (k) {
16245 // convert BigNumber to a number
16246 if (Object(is["e" /* isBigNumber */])(k)) {
16247 k = k.toNumber();
16248 } // is must be an integer
16249
16250
16251 if (!Object(is["y" /* isNumber */])(k) || !Object(utils_number["i" /* isInteger */])(k)) {
16252 throw new TypeError('The parameter k must be an integer number');
16253 }
16254 } else {
16255 // default value
16256 k = 0;
16257 } // equal signature to use
16258
16259
16260 var eq = equalScalar; // zero value
16261
16262 var zero = 0;
16263
16264 if (Object(is["I" /* isString */])(datatype)) {
16265 // find signature that matches (datatype, datatype)
16266 eq = typed.find(equalScalar, [datatype, datatype]) || equalScalar; // convert 0 to the same datatype
16267
16268 zero = typed.convert(0, datatype);
16269 }
16270
16271 var kSuper = k > 0 ? k : 0;
16272 var kSub = k < 0 ? -k : 0; // rows and columns
16273
16274 var rows = size[0];
16275 var columns = size[1]; // number of non-zero items
16276
16277 var n = Math.min(rows - kSub, columns - kSuper); // value extraction function
16278
16279 var _value; // check value
16280
16281
16282 if (Object(is["b" /* isArray */])(value)) {
16283 // validate array
16284 if (value.length !== n) {
16285 // number of values in array must be n
16286 throw new Error('Invalid value array length');
16287 } // define function
16288
16289
16290 _value = function _value(i) {
16291 // return value @ i
16292 return value[i];
16293 };
16294 } else if (Object(is["v" /* isMatrix */])(value)) {
16295 // matrix size
16296 var ms = value.size(); // validate matrix
16297
16298 if (ms.length !== 1 || ms[0] !== n) {
16299 // number of values in array must be n
16300 throw new Error('Invalid matrix length');
16301 } // define function
16302
16303
16304 _value = function _value(i) {
16305 // return value @ i
16306 return value.get([i]);
16307 };
16308 } else {
16309 // define function
16310 _value = function _value() {
16311 // return value
16312 return value;
16313 };
16314 } // create arrays
16315
16316
16317 var values = [];
16318 var index = [];
16319 var ptr = []; // loop items
16320
16321 for (var j = 0; j < columns; j++) {
16322 // number of rows with value
16323 ptr.push(values.length); // diagonal index
16324
16325 var i = j - kSuper; // check we need to set diagonal value
16326
16327 if (i >= 0 && i < n) {
16328 // get value @ i
16329 var v = _value(i); // check for zero
16330
16331
16332 if (!eq(v, zero)) {
16333 // column
16334 index.push(i + kSub); // add value
16335
16336 values.push(v);
16337 }
16338 }
16339 } // last value should be number of values
16340
16341
16342 ptr.push(values.length); // create SparseMatrix
16343
16344 return new SparseMatrix({
16345 values: values,
16346 index: index,
16347 ptr: ptr,
16348 size: [rows, columns]
16349 });
16350 };
16351 /**
16352 * Swap rows i and j in Matrix.
16353 *
16354 * @memberof SparseMatrix
16355 * @param {number} i Matrix row index 1
16356 * @param {number} j Matrix row index 2
16357 *
16358 * @return {Matrix} The matrix reference
16359 */
16360
16361
16362 SparseMatrix.prototype.swapRows = function (i, j) {
16363 // check index
16364 if (!Object(is["y" /* isNumber */])(i) || !Object(utils_number["i" /* isInteger */])(i) || !Object(is["y" /* isNumber */])(j) || !Object(utils_number["i" /* isInteger */])(j)) {
16365 throw new Error('Row index must be positive integers');
16366 } // check dimensions
16367
16368
16369 if (this._size.length !== 2) {
16370 throw new Error('Only two dimensional matrix is supported');
16371 } // validate index
16372
16373
16374 Object(utils_array["s" /* validateIndex */])(i, this._size[0]);
16375 Object(utils_array["s" /* validateIndex */])(j, this._size[0]); // swap rows
16376
16377 SparseMatrix._swapRows(i, j, this._size[1], this._values, this._index, this._ptr); // return current instance
16378
16379
16380 return this;
16381 };
16382 /**
16383 * Loop rows with data in column j.
16384 *
16385 * @param {number} j Column
16386 * @param {Array} values Matrix values
16387 * @param {Array} index Matrix row indeces
16388 * @param {Array} ptr Matrix column pointers
16389 * @param {Function} callback Callback function invoked for every row in column j
16390 */
16391
16392
16393 SparseMatrix._forEachRow = function (j, values, index, ptr, callback) {
16394 // indeces for column j
16395 var k0 = ptr[j];
16396 var k1 = ptr[j + 1]; // loop
16397
16398 for (var k = k0; k < k1; k++) {
16399 // invoke callback
16400 callback(index[k], values[k]);
16401 }
16402 };
16403 /**
16404 * Swap rows x and y in Sparse Matrix data structures.
16405 *
16406 * @param {number} x Matrix row index 1
16407 * @param {number} y Matrix row index 2
16408 * @param {number} columns Number of columns in matrix
16409 * @param {Array} values Matrix values
16410 * @param {Array} index Matrix row indeces
16411 * @param {Array} ptr Matrix column pointers
16412 */
16413
16414
16415 SparseMatrix._swapRows = function (x, y, columns, values, index, ptr) {
16416 // loop columns
16417 for (var j = 0; j < columns; j++) {
16418 // k0 <= k < k1 where k0 = _ptr[j] && k1 = _ptr[j+1]
16419 var k0 = ptr[j];
16420 var k1 = ptr[j + 1]; // find value index @ x
16421
16422 var kx = _getValueIndex(x, k0, k1, index); // find value index @ x
16423
16424
16425 var ky = _getValueIndex(y, k0, k1, index); // check both rows exist in matrix
16426
16427
16428 if (kx < k1 && ky < k1 && index[kx] === x && index[ky] === y) {
16429 // swap values (check for pattern matrix)
16430 if (values) {
16431 var v = values[kx];
16432 values[kx] = values[ky];
16433 values[ky] = v;
16434 } // next column
16435
16436
16437 continue;
16438 } // check x row exist & no y row
16439
16440
16441 if (kx < k1 && index[kx] === x && (ky >= k1 || index[ky] !== y)) {
16442 // value @ x (check for pattern matrix)
16443 var vx = values ? values[kx] : undefined; // insert value @ y
16444
16445 index.splice(ky, 0, y);
16446
16447 if (values) {
16448 values.splice(ky, 0, vx);
16449 } // remove value @ x (adjust array index if needed)
16450
16451
16452 index.splice(ky <= kx ? kx + 1 : kx, 1);
16453
16454 if (values) {
16455 values.splice(ky <= kx ? kx + 1 : kx, 1);
16456 } // next column
16457
16458
16459 continue;
16460 } // check y row exist & no x row
16461
16462
16463 if (ky < k1 && index[ky] === y && (kx >= k1 || index[kx] !== x)) {
16464 // value @ y (check for pattern matrix)
16465 var vy = values ? values[ky] : undefined; // insert value @ x
16466
16467 index.splice(kx, 0, x);
16468
16469 if (values) {
16470 values.splice(kx, 0, vy);
16471 } // remove value @ y (adjust array index if needed)
16472
16473
16474 index.splice(kx <= ky ? ky + 1 : ky, 1);
16475
16476 if (values) {
16477 values.splice(kx <= ky ? ky + 1 : ky, 1);
16478 }
16479 }
16480 }
16481 };
16482
16483 return SparseMatrix;
16484}, {
16485 isClass: true
16486});
16487// CONCATENATED MODULE: ./src/type/number.js
16488
16489
16490var number_name = 'number';
16491var number_dependencies = ['typed'];
16492var createNumber =
16493/* #__PURE__ */
16494Object(factory["a" /* factory */])(number_name, number_dependencies, function (_ref) {
16495 var typed = _ref.typed;
16496
16497 /**
16498 * Create a number or convert a string, boolean, or unit to a number.
16499 * When value is a matrix, all elements will be converted to number.
16500 *
16501 * Syntax:
16502 *
16503 * math.number(value)
16504 * math.number(unit, valuelessUnit)
16505 *
16506 * Examples:
16507 *
16508 * math.number(2) // returns number 2
16509 * math.number('7.2') // returns number 7.2
16510 * math.number(true) // returns number 1
16511 * math.number([true, false, true, true]) // returns [1, 0, 1, 1]
16512 * math.number(math.unit('52cm'), 'm') // returns 0.52
16513 *
16514 * See also:
16515 *
16516 * bignumber, boolean, complex, index, matrix, string, unit
16517 *
16518 * @param {string | number | BigNumber | Fraction | boolean | Array | Matrix | Unit | null} [value] Value to be converted
16519 * @param {Unit | string} [valuelessUnit] A valueless unit, used to convert a unit to a number
16520 * @return {number | Array | Matrix} The created number
16521 */
16522 var number = typed('number', {
16523 '': function _() {
16524 return 0;
16525 },
16526 number: function number(x) {
16527 return x;
16528 },
16529 string: function string(x) {
16530 if (x === 'NaN') return NaN;
16531 var num = Number(x);
16532
16533 if (isNaN(num)) {
16534 throw new SyntaxError('String "' + x + '" is no valid number');
16535 }
16536
16537 return num;
16538 },
16539 BigNumber: function BigNumber(x) {
16540 return x.toNumber();
16541 },
16542 Fraction: function Fraction(x) {
16543 return x.valueOf();
16544 },
16545 Unit: function Unit(x) {
16546 throw new Error('Second argument with valueless unit expected');
16547 },
16548 "null": function _null(x) {
16549 return 0;
16550 },
16551 'Unit, string | Unit': function UnitStringUnit(unit, valuelessUnit) {
16552 return unit.toNumber(valuelessUnit);
16553 },
16554 'Array | Matrix': function ArrayMatrix(x) {
16555 return deepMap(x, number);
16556 }
16557 });
16558 return number;
16559});
16560// CONCATENATED MODULE: ./src/type/string.js
16561
16562
16563
16564var string_name = 'string';
16565var string_dependencies = ['typed'];
16566var createString =
16567/* #__PURE__ */
16568Object(factory["a" /* factory */])(string_name, string_dependencies, function (_ref) {
16569 var typed = _ref.typed;
16570
16571 /**
16572 * Create a string or convert any object into a string.
16573 * Elements of Arrays and Matrices are processed element wise.
16574 *
16575 * Syntax:
16576 *
16577 * math.string(value)
16578 *
16579 * Examples:
16580 *
16581 * math.string(4.2) // returns string '4.2'
16582 * math.string(math.complex(3, 2) // returns string '3 + 2i'
16583 *
16584 * const u = math.unit(5, 'km')
16585 * math.string(u.to('m')) // returns string '5000 m'
16586 *
16587 * math.string([true, false]) // returns ['true', 'false']
16588 *
16589 * See also:
16590 *
16591 * bignumber, boolean, complex, index, matrix, number, unit
16592 *
16593 * @param {* | Array | Matrix | null} [value] A value to convert to a string
16594 * @return {string | Array | Matrix} The created string
16595 */
16596 var string = typed(string_name, {
16597 '': function _() {
16598 return '';
16599 },
16600 number: utils_number["h" /* format */],
16601 "null": function _null(x) {
16602 return 'null';
16603 },
16604 "boolean": function boolean(x) {
16605 return x + '';
16606 },
16607 string: function string(x) {
16608 return x;
16609 },
16610 'Array | Matrix': function ArrayMatrix(x) {
16611 return deepMap(x, string);
16612 },
16613 any: function any(x) {
16614 return String(x);
16615 }
16616 });
16617 return string;
16618});
16619// CONCATENATED MODULE: ./src/type/boolean.js
16620
16621
16622var boolean_name = 'boolean';
16623var boolean_dependencies = ['typed'];
16624var createBoolean =
16625/* #__PURE__ */
16626Object(factory["a" /* factory */])(boolean_name, boolean_dependencies, function (_ref) {
16627 var typed = _ref.typed;
16628
16629 /**
16630 * Create a boolean or convert a string or number to a boolean.
16631 * In case of a number, `true` is returned for non-zero numbers, and `false` in
16632 * case of zero.
16633 * Strings can be `'true'` or `'false'`, or can contain a number.
16634 * When value is a matrix, all elements will be converted to boolean.
16635 *
16636 * Syntax:
16637 *
16638 * math.boolean(x)
16639 *
16640 * Examples:
16641 *
16642 * math.boolean(0) // returns false
16643 * math.boolean(1) // returns true
16644 * math.boolean(-3) // returns true
16645 * math.boolean('true') // returns true
16646 * math.boolean('false') // returns false
16647 * math.boolean([1, 0, 1, 1]) // returns [true, false, true, true]
16648 *
16649 * See also:
16650 *
16651 * bignumber, complex, index, matrix, string, unit
16652 *
16653 * @param {string | number | boolean | Array | Matrix | null} value A value of any type
16654 * @return {boolean | Array | Matrix} The boolean value
16655 */
16656 var bool = typed(boolean_name, {
16657 '': function _() {
16658 return false;
16659 },
16660 "boolean": function boolean(x) {
16661 return x;
16662 },
16663 number: function number(x) {
16664 return !!x;
16665 },
16666 "null": function _null(x) {
16667 return false;
16668 },
16669 BigNumber: function BigNumber(x) {
16670 return !x.isZero();
16671 },
16672 string: function string(x) {
16673 // try case insensitive
16674 var lcase = x.toLowerCase();
16675
16676 if (lcase === 'true') {
16677 return true;
16678 } else if (lcase === 'false') {
16679 return false;
16680 } // test whether value is a valid number
16681
16682
16683 var num = Number(x);
16684
16685 if (x !== '' && !isNaN(num)) {
16686 return !!num;
16687 }
16688
16689 throw new Error('Cannot convert "' + x + '" to a boolean');
16690 },
16691 'Array | Matrix': function ArrayMatrix(x) {
16692 return deepMap(x, bool);
16693 }
16694 });
16695 return bool;
16696});
16697// CONCATENATED MODULE: ./src/type/bignumber/function/bignumber.js
16698
16699
16700var bignumber_name = 'bignumber';
16701var bignumber_dependencies = ['typed', 'BigNumber'];
16702var createBignumber =
16703/* #__PURE__ */
16704Object(factory["a" /* factory */])(bignumber_name, bignumber_dependencies, function (_ref) {
16705 var typed = _ref.typed,
16706 BigNumber = _ref.BigNumber;
16707
16708 /**
16709 * Create a BigNumber, which can store numbers with arbitrary precision.
16710 * When a matrix is provided, all elements will be converted to BigNumber.
16711 *
16712 * Syntax:
16713 *
16714 * math.bignumber(x)
16715 *
16716 * Examples:
16717 *
16718 * 0.1 + 0.2 // returns number 0.30000000000000004
16719 * math.bignumber(0.1) + math.bignumber(0.2) // returns BigNumber 0.3
16720 *
16721 *
16722 * 7.2e500 // returns number Infinity
16723 * math.bignumber('7.2e500') // returns BigNumber 7.2e500
16724 *
16725 * See also:
16726 *
16727 * boolean, complex, index, matrix, string, unit
16728 *
16729 * @param {number | string | Fraction | BigNumber | Array | Matrix | boolean | null} [value] Value for the big number,
16730 * 0 by default.
16731 * @returns {BigNumber} The created bignumber
16732 */
16733 var bignumber = typed('bignumber', {
16734 '': function _() {
16735 return new BigNumber(0);
16736 },
16737 number: function number(x) {
16738 // convert to string to prevent errors in case of >15 digits
16739 return new BigNumber(x + '');
16740 },
16741 string: function string(x) {
16742 return new BigNumber(x);
16743 },
16744 BigNumber: function BigNumber(x) {
16745 // we assume a BigNumber is immutable
16746 return x;
16747 },
16748 Fraction: function Fraction(x) {
16749 return new BigNumber(x.n).div(x.d).times(x.s);
16750 },
16751 "null": function _null(x) {
16752 return new BigNumber(0);
16753 },
16754 'Array | Matrix': function ArrayMatrix(x) {
16755 return deepMap(x, bignumber);
16756 }
16757 });
16758 return bignumber;
16759});
16760// CONCATENATED MODULE: ./src/type/complex/function/complex.js
16761
16762
16763var complex_name = 'complex';
16764var complex_dependencies = ['typed', 'Complex'];
16765var createComplex =
16766/* #__PURE__ */
16767Object(factory["a" /* factory */])(complex_name, complex_dependencies, function (_ref) {
16768 var typed = _ref.typed,
16769 Complex = _ref.Complex;
16770
16771 /**
16772 * Create a complex value or convert a value to a complex value.
16773 *
16774 * Syntax:
16775 *
16776 * math.complex() // creates a complex value with zero
16777 * // as real and imaginary part.
16778 * math.complex(re : number, im : string) // creates a complex value with provided
16779 * // values for real and imaginary part.
16780 * math.complex(re : number) // creates a complex value with provided
16781 * // real value and zero imaginary part.
16782 * math.complex(complex : Complex) // clones the provided complex value.
16783 * math.complex(arg : string) // parses a string into a complex value.
16784 * math.complex(array : Array) // converts the elements of the array
16785 * // or matrix element wise into a
16786 * // complex value.
16787 * math.complex({re: number, im: number}) // creates a complex value with provided
16788 * // values for real an imaginary part.
16789 * math.complex({r: number, phi: number}) // creates a complex value with provided
16790 * // polar coordinates
16791 *
16792 * Examples:
16793 *
16794 * const a = math.complex(3, -4) // a = Complex 3 - 4i
16795 * a.re = 5 // a = Complex 5 - 4i
16796 * const i = a.im // Number -4
16797 * const b = math.complex('2 + 6i') // Complex 2 + 6i
16798 * const c = math.complex() // Complex 0 + 0i
16799 * const d = math.add(a, b) // Complex 5 + 2i
16800 *
16801 * See also:
16802 *
16803 * bignumber, boolean, index, matrix, number, string, unit
16804 *
16805 * @param {* | Array | Matrix} [args]
16806 * Arguments specifying the real and imaginary part of the complex number
16807 * @return {Complex | Array | Matrix} Returns a complex value
16808 */
16809 var complex = typed('complex', {
16810 '': function _() {
16811 return Complex.ZERO;
16812 },
16813 number: function number(x) {
16814 return new Complex(x, 0);
16815 },
16816 'number, number': function numberNumber(re, im) {
16817 return new Complex(re, im);
16818 },
16819 // TODO: this signature should be redundant
16820 'BigNumber, BigNumber': function BigNumberBigNumber(re, im) {
16821 return new Complex(re.toNumber(), im.toNumber());
16822 },
16823 Fraction: function Fraction(x) {
16824 return new Complex(x.valueOf(), 0);
16825 },
16826 Complex: function Complex(x) {
16827 return x.clone();
16828 },
16829 string: function string(x) {
16830 return Complex(x); // for example '2 + 3i'
16831 },
16832 "null": function _null(x) {
16833 return Complex(0);
16834 },
16835 Object: function Object(x) {
16836 if ('re' in x && 'im' in x) {
16837 return new Complex(x.re, x.im);
16838 }
16839
16840 if ('r' in x && 'phi' in x || 'abs' in x && 'arg' in x) {
16841 return new Complex(x);
16842 }
16843
16844 throw new Error('Expected object with properties (re and im) or (r and phi) or (abs and arg)');
16845 },
16846 'Array | Matrix': function ArrayMatrix(x) {
16847 return deepMap(x, complex);
16848 }
16849 });
16850 return complex;
16851});
16852// CONCATENATED MODULE: ./src/type/fraction/function/fraction.js
16853
16854
16855var fraction_name = 'fraction';
16856var fraction_dependencies = ['typed', 'Fraction'];
16857var createFraction =
16858/* #__PURE__ */
16859Object(factory["a" /* factory */])(fraction_name, fraction_dependencies, function (_ref) {
16860 var typed = _ref.typed,
16861 Fraction = _ref.Fraction;
16862
16863 /**
16864 * Create a fraction convert a value to a fraction.
16865 *
16866 * Syntax:
16867 * math.fraction(numerator, denominator)
16868 * math.fraction({n: numerator, d: denominator})
16869 * math.fraction(matrix: Array | Matrix) Turn all matrix entries
16870 * into fractions
16871 *
16872 * Examples:
16873 *
16874 * math.fraction(1, 3)
16875 * math.fraction('2/3')
16876 * math.fraction({n: 2, d: 3})
16877 * math.fraction([0.2, 0.25, 1.25])
16878 *
16879 * See also:
16880 *
16881 * bignumber, number, string, unit
16882 *
16883 * @param {number | string | Fraction | BigNumber | Array | Matrix} [args]
16884 * Arguments specifying the numerator and denominator of
16885 * the fraction
16886 * @return {Fraction | Array | Matrix} Returns a fraction
16887 */
16888 var fraction = typed('fraction', {
16889 number: function number(x) {
16890 if (!isFinite(x) || isNaN(x)) {
16891 throw new Error(x + ' cannot be represented as a fraction');
16892 }
16893
16894 return new Fraction(x);
16895 },
16896 string: function string(x) {
16897 return new Fraction(x);
16898 },
16899 'number, number': function numberNumber(numerator, denominator) {
16900 return new Fraction(numerator, denominator);
16901 },
16902 "null": function _null(x) {
16903 return new Fraction(0);
16904 },
16905 BigNumber: function BigNumber(x) {
16906 return new Fraction(x.toString());
16907 },
16908 Fraction: function Fraction(x) {
16909 return x; // fractions are immutable
16910 },
16911 Object: function Object(x) {
16912 return new Fraction(x);
16913 },
16914 'Array | Matrix': function ArrayMatrix(x) {
16915 return deepMap(x, fraction);
16916 }
16917 });
16918 return fraction;
16919});
16920// CONCATENATED MODULE: ./src/type/matrix/function/matrix.js
16921
16922var matrix_name = 'matrix';
16923var matrix_dependencies = ['typed', 'Matrix', 'DenseMatrix', 'SparseMatrix'];
16924var createMatrix =
16925/* #__PURE__ */
16926Object(factory["a" /* factory */])(matrix_name, matrix_dependencies, function (_ref) {
16927 var typed = _ref.typed,
16928 Matrix = _ref.Matrix,
16929 DenseMatrix = _ref.DenseMatrix,
16930 SparseMatrix = _ref.SparseMatrix;
16931
16932 /**
16933 * Create a Matrix. The function creates a new `math.Matrix` object from
16934 * an `Array`. A Matrix has utility functions to manipulate the data in the
16935 * matrix, like getting the size and getting or setting values in the matrix.
16936 * Supported storage formats are 'dense' and 'sparse'.
16937 *
16938 * Syntax:
16939 *
16940 * math.matrix() // creates an empty matrix using default storage format (dense).
16941 * math.matrix(data) // creates a matrix with initial data using default storage format (dense).
16942 * math.matrix('dense') // creates an empty matrix using the given storage format.
16943 * math.matrix(data, 'dense') // creates a matrix with initial data using the given storage format.
16944 * math.matrix(data, 'sparse') // creates a sparse matrix with initial data.
16945 * math.matrix(data, 'sparse', 'number') // creates a sparse matrix with initial data, number data type.
16946 *
16947 * Examples:
16948 *
16949 * let m = math.matrix([[1, 2], [3, 4]])
16950 * m.size() // Array [2, 2]
16951 * m.resize([3, 2], 5)
16952 * m.valueOf() // Array [[1, 2], [3, 4], [5, 5]]
16953 * m.get([1, 0]) // number 3
16954 *
16955 * See also:
16956 *
16957 * bignumber, boolean, complex, index, number, string, unit, sparse
16958 *
16959 * @param {Array | Matrix} [data] A multi dimensional array
16960 * @param {string} [format] The Matrix storage format
16961 *
16962 * @return {Matrix} The created matrix
16963 */
16964 return typed(matrix_name, {
16965 '': function _() {
16966 return _create([]);
16967 },
16968 string: function string(format) {
16969 return _create([], format);
16970 },
16971 'string, string': function stringString(format, datatype) {
16972 return _create([], format, datatype);
16973 },
16974 Array: function Array(data) {
16975 return _create(data);
16976 },
16977 Matrix: function Matrix(data) {
16978 return _create(data, data.storage());
16979 },
16980 'Array | Matrix, string': _create,
16981 'Array | Matrix, string, string': _create
16982 });
16983 /**
16984 * Create a new Matrix with given storage format
16985 * @param {Array} data
16986 * @param {string} [format]
16987 * @param {string} [datatype]
16988 * @returns {Matrix} Returns a new Matrix
16989 * @private
16990 */
16991
16992 function _create(data, format, datatype) {
16993 // get storage format constructor
16994 if (format === 'dense' || format === 'default' || format === undefined) {
16995 return new DenseMatrix(data, datatype);
16996 }
16997
16998 if (format === 'sparse') {
16999 return new SparseMatrix(data, datatype);
17000 }
17001
17002 throw new TypeError('Unknown matrix type ' + JSON.stringify(format) + '.');
17003 }
17004});
17005// CONCATENATED MODULE: ./src/type/unit/function/splitUnit.js
17006
17007var splitUnit_name = 'splitUnit';
17008var splitUnit_dependencies = ['typed'];
17009var createSplitUnit =
17010/* #__PURE__ */
17011Object(factory["a" /* factory */])(splitUnit_name, splitUnit_dependencies, function (_ref) {
17012 var typed = _ref.typed;
17013
17014 /**
17015 * Split a unit in an array of units whose sum is equal to the original unit.
17016 *
17017 * Syntax:
17018 *
17019 * splitUnit(unit: Unit, parts: Array.<Unit>)
17020 *
17021 * Example:
17022 *
17023 * math.splitUnit(new Unit(1, 'm'), ['feet', 'inch'])
17024 * // [ 3 feet, 3.3700787401575 inch ]
17025 *
17026 * See also:
17027 *
17028 * unit
17029 *
17030 * @param {Array} [parts] An array of strings or valueless units.
17031 * @return {Array} An array of units.
17032 */
17033 return typed(splitUnit_name, {
17034 'Unit, Array': function UnitArray(unit, parts) {
17035 return unit.splitUnit(parts);
17036 }
17037 });
17038});
17039// CONCATENATED MODULE: ./src/plain/number/arithmetic.js
17040
17041var arithmetic_n1 = 'number';
17042var arithmetic_n2 = 'number, number';
17043function absNumber(a) {
17044 return Math.abs(a);
17045}
17046absNumber.signature = arithmetic_n1;
17047function addNumber(a, b) {
17048 return a + b;
17049}
17050addNumber.signature = arithmetic_n2;
17051function subtractNumber(a, b) {
17052 return a - b;
17053}
17054subtractNumber.signature = arithmetic_n2;
17055function multiplyNumber(a, b) {
17056 return a * b;
17057}
17058multiplyNumber.signature = arithmetic_n2;
17059function divideNumber(a, b) {
17060 return a / b;
17061}
17062divideNumber.signature = arithmetic_n2;
17063function unaryMinusNumber(x) {
17064 return -x;
17065}
17066unaryMinusNumber.signature = arithmetic_n1;
17067function unaryPlusNumber(x) {
17068 return x;
17069}
17070unaryPlusNumber.signature = arithmetic_n1;
17071function cbrtNumber(x) {
17072 return Object(utils_number["d" /* cbrt */])(x);
17073}
17074cbrtNumber.signature = arithmetic_n1;
17075function ceilNumber(x) {
17076 return Math.ceil(x);
17077}
17078ceilNumber.signature = arithmetic_n1;
17079function cubeNumber(x) {
17080 return x * x * x;
17081}
17082cubeNumber.signature = arithmetic_n1;
17083function expNumber(x) {
17084 return Math.exp(x);
17085}
17086expNumber.signature = arithmetic_n1;
17087function expm1Number(x) {
17088 return Object(utils_number["g" /* expm1 */])(x);
17089}
17090expm1Number.signature = arithmetic_n1;
17091function fixNumber(x) {
17092 return x > 0 ? Math.floor(x) : Math.ceil(x);
17093}
17094fixNumber.signature = arithmetic_n1;
17095function floorNumber(x) {
17096 return Math.floor(x);
17097}
17098floorNumber.signature = arithmetic_n1;
17099/**
17100 * Calculate gcd for numbers
17101 * @param {number} a
17102 * @param {number} b
17103 * @returns {number} Returns the greatest common denominator of a and b
17104 */
17105
17106function gcdNumber(a, b) {
17107 if (!Object(utils_number["i" /* isInteger */])(a) || !Object(utils_number["i" /* isInteger */])(b)) {
17108 throw new Error('Parameters in function gcd must be integer numbers');
17109 } // https://en.wikipedia.org/wiki/Euclidean_algorithm
17110
17111
17112 var r;
17113
17114 while (b !== 0) {
17115 r = a % b;
17116 a = b;
17117 b = r;
17118 }
17119
17120 return a < 0 ? -a : a;
17121}
17122gcdNumber.signature = arithmetic_n2;
17123/**
17124 * Calculate lcm for two numbers
17125 * @param {number} a
17126 * @param {number} b
17127 * @returns {number} Returns the least common multiple of a and b
17128 */
17129
17130function lcmNumber(a, b) {
17131 if (!Object(utils_number["i" /* isInteger */])(a) || !Object(utils_number["i" /* isInteger */])(b)) {
17132 throw new Error('Parameters in function lcm must be integer numbers');
17133 }
17134
17135 if (a === 0 || b === 0) {
17136 return 0;
17137 } // https://en.wikipedia.org/wiki/Euclidean_algorithm
17138 // evaluate lcm here inline to reduce overhead
17139
17140
17141 var t;
17142 var prod = a * b;
17143
17144 while (b !== 0) {
17145 t = b;
17146 b = a % t;
17147 a = t;
17148 }
17149
17150 return Math.abs(prod / a);
17151}
17152lcmNumber.signature = arithmetic_n2;
17153/**
17154 * Calculate the logarithm of a value.
17155 * @param {number} x
17156 * @return {number}
17157 */
17158
17159function logNumber(x) {
17160 return Math.log(x);
17161}
17162logNumber.signature = arithmetic_n1;
17163/**
17164 * Calculate the 10-base logarithm of a number
17165 * @param {number} x
17166 * @return {number}
17167 */
17168
17169function log10Number(x) {
17170 return Object(utils_number["j" /* log10 */])(x);
17171}
17172log10Number.signature = arithmetic_n1;
17173/**
17174 * Calculate the 2-base logarithm of a number
17175 * @param {number} x
17176 * @return {number}
17177 */
17178
17179function log2Number(x) {
17180 return Object(utils_number["l" /* log2 */])(x);
17181}
17182log2Number.signature = arithmetic_n1;
17183/**
17184 * Calculate the natural logarithm of a `number+1`
17185 * @param {number} x
17186 * @returns {number}
17187 */
17188
17189function log1pNumber(x) {
17190 return Object(utils_number["k" /* log1p */])(x);
17191}
17192log1pNumber.signature = arithmetic_n1;
17193/**
17194 * Calculate the modulus of two numbers
17195 * @param {number} x
17196 * @param {number} y
17197 * @returns {number} res
17198 * @private
17199 */
17200
17201function modNumber(x, y) {
17202 if (y > 0) {
17203 // We don't use JavaScript's % operator here as this doesn't work
17204 // correctly for x < 0 and x === 0
17205 // see https://en.wikipedia.org/wiki/Modulo_operation
17206 return x - y * Math.floor(x / y);
17207 } else if (y === 0) {
17208 return x;
17209 } else {
17210 // y < 0
17211 // TODO: implement mod for a negative divisor
17212 throw new Error('Cannot calculate mod for a negative divisor');
17213 }
17214}
17215modNumber.signature = arithmetic_n2;
17216/**
17217 * Calculate the nth root of a, solve x^root == a
17218 * http://rosettacode.org/wiki/Nth_root#JavaScript
17219 * @param {number} a
17220 * @param {number} root
17221 * @private
17222 */
17223
17224function nthRootNumber(a, root) {
17225 var inv = root < 0;
17226
17227 if (inv) {
17228 root = -root;
17229 }
17230
17231 if (root === 0) {
17232 throw new Error('Root must be non-zero');
17233 }
17234
17235 if (a < 0 && Math.abs(root) % 2 !== 1) {
17236 throw new Error('Root must be odd when a is negative.');
17237 } // edge cases zero and infinity
17238
17239
17240 if (a === 0) {
17241 return inv ? Infinity : 0;
17242 }
17243
17244 if (!isFinite(a)) {
17245 return inv ? 0 : a;
17246 }
17247
17248 var x = Math.pow(Math.abs(a), 1 / root); // If a < 0, we require that root is an odd integer,
17249 // so (-1) ^ (1/root) = -1
17250
17251 x = a < 0 ? -x : x;
17252 return inv ? 1 / x : x; // Very nice algorithm, but fails with nthRoot(-2, 3).
17253 // Newton's method has some well-known problems at times:
17254 // https://en.wikipedia.org/wiki/Newton%27s_method#Failure_analysis
17255
17256 /*
17257 let x = 1 // Initial guess
17258 let xPrev = 1
17259 let i = 0
17260 const iMax = 10000
17261 do {
17262 const delta = (a / Math.pow(x, root - 1) - x) / root
17263 xPrev = x
17264 x = x + delta
17265 i++
17266 }
17267 while (xPrev !== x && i < iMax)
17268 if (xPrev !== x) {
17269 throw new Error('Function nthRoot failed to converge')
17270 }
17271 return inv ? 1 / x : x
17272 */
17273}
17274nthRootNumber.signature = arithmetic_n2;
17275function signNumber(x) {
17276 return Object(utils_number["n" /* sign */])(x);
17277}
17278signNumber.signature = arithmetic_n1;
17279function sqrtNumber(x) {
17280 return Math.sqrt(x);
17281}
17282sqrtNumber.signature = arithmetic_n1;
17283function squareNumber(x) {
17284 return x * x;
17285}
17286squareNumber.signature = arithmetic_n1;
17287/**
17288 * Calculate xgcd for two numbers
17289 * @param {number} a
17290 * @param {number} b
17291 * @return {number} result
17292 * @private
17293 */
17294
17295function xgcdNumber(a, b) {
17296 // source: https://en.wikipedia.org/wiki/Extended_Euclidean_algorithm
17297 var t; // used to swap two variables
17298
17299 var q; // quotient
17300
17301 var r; // remainder
17302
17303 var x = 0;
17304 var lastx = 1;
17305 var y = 1;
17306 var lasty = 0;
17307
17308 if (!Object(utils_number["i" /* isInteger */])(a) || !Object(utils_number["i" /* isInteger */])(b)) {
17309 throw new Error('Parameters in function xgcd must be integer numbers');
17310 }
17311
17312 while (b) {
17313 q = Math.floor(a / b);
17314 r = a - q * b;
17315 t = x;
17316 x = lastx - q * x;
17317 lastx = t;
17318 t = y;
17319 y = lasty - q * y;
17320 lasty = t;
17321 a = b;
17322 b = r;
17323 }
17324
17325 var res;
17326
17327 if (a < 0) {
17328 res = [-a, -lastx, -lasty];
17329 } else {
17330 res = [a, a ? lastx : 0, lasty];
17331 }
17332
17333 return res;
17334}
17335xgcdNumber.signature = arithmetic_n2;
17336/**
17337 * Calculates the power of x to y, x^y, for two numbers.
17338 * @param {number} x
17339 * @param {number} y
17340 * @return {number} res
17341 */
17342
17343function powNumber(x, y) {
17344 // x^Infinity === 0 if -1 < x < 1
17345 // A real number 0 is returned instead of complex(0)
17346 if (x * x < 1 && y === Infinity || x * x > 1 && y === -Infinity) {
17347 return 0;
17348 }
17349
17350 return Math.pow(x, y);
17351}
17352powNumber.signature = arithmetic_n2;
17353/**
17354 * round a number to the given number of decimals, or to zero if decimals is
17355 * not provided
17356 * @param {number} value
17357 * @param {number} decimals number of decimals, between 0 and 15 (0 by default)
17358 * @return {number} roundedValue
17359 */
17360
17361function roundNumber(value) {
17362 var decimals = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
17363 return parseFloat(Object(utils_number["q" /* toFixed */])(value, decimals));
17364}
17365roundNumber.signature = arithmetic_n2;
17366/**
17367 * Calculate the norm of a number, the absolute value.
17368 * @param {number} x
17369 * @return {number}
17370 */
17371
17372function normNumber(x) {
17373 return Math.abs(x);
17374}
17375normNumber.signature = arithmetic_n1;
17376// CONCATENATED MODULE: ./src/function/arithmetic/unaryMinus.js
17377
17378
17379
17380var unaryMinus_name = 'unaryMinus';
17381var unaryMinus_dependencies = ['typed'];
17382var createUnaryMinus =
17383/* #__PURE__ */
17384Object(factory["a" /* factory */])(unaryMinus_name, unaryMinus_dependencies, function (_ref) {
17385 var typed = _ref.typed;
17386
17387 /**
17388 * Inverse the sign of a value, apply a unary minus operation.
17389 *
17390 * For matrices, the function is evaluated element wise. Boolean values and
17391 * strings will be converted to a number. For complex numbers, both real and
17392 * complex value are inverted.
17393 *
17394 * Syntax:
17395 *
17396 * math.unaryMinus(x)
17397 *
17398 * Examples:
17399 *
17400 * math.unaryMinus(3.5) // returns -3.5
17401 * math.unaryMinus(-4.2) // returns 4.2
17402 *
17403 * See also:
17404 *
17405 * add, subtract, unaryPlus
17406 *
17407 * @param {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} x Number to be inverted.
17408 * @return {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} Returns the value with inverted sign.
17409 */
17410 var unaryMinus = typed(unaryMinus_name, {
17411 number: unaryMinusNumber,
17412 Complex: function Complex(x) {
17413 return x.neg();
17414 },
17415 BigNumber: function BigNumber(x) {
17416 return x.neg();
17417 },
17418 Fraction: function Fraction(x) {
17419 return x.neg();
17420 },
17421 Unit: function Unit(x) {
17422 var res = x.clone();
17423 res.value = unaryMinus(x.value);
17424 return res;
17425 },
17426 'Array | Matrix': function ArrayMatrix(x) {
17427 // deep map collection, skip zeros since unaryMinus(0) = 0
17428 return deepMap(x, unaryMinus, true);
17429 } // TODO: add support for string
17430
17431 });
17432 return unaryMinus;
17433});
17434// CONCATENATED MODULE: ./src/function/arithmetic/unaryPlus.js
17435
17436
17437
17438var unaryPlus_name = 'unaryPlus';
17439var unaryPlus_dependencies = ['typed', 'config', 'BigNumber'];
17440var createUnaryPlus =
17441/* #__PURE__ */
17442Object(factory["a" /* factory */])(unaryPlus_name, unaryPlus_dependencies, function (_ref) {
17443 var typed = _ref.typed,
17444 config = _ref.config,
17445 BigNumber = _ref.BigNumber;
17446
17447 /**
17448 * Unary plus operation.
17449 * Boolean values and strings will be converted to a number, numeric values will be returned as is.
17450 *
17451 * For matrices, the function is evaluated element wise.
17452 *
17453 * Syntax:
17454 *
17455 * math.unaryPlus(x)
17456 *
17457 * Examples:
17458 *
17459 * math.unaryPlus(3.5) // returns 3.5
17460 * math.unaryPlus(1) // returns 1
17461 *
17462 * See also:
17463 *
17464 * unaryMinus, add, subtract
17465 *
17466 * @param {number | BigNumber | Fraction | string | Complex | Unit | Array | Matrix} x
17467 * Input value
17468 * @return {number | BigNumber | Fraction | Complex | Unit | Array | Matrix}
17469 * Returns the input value when numeric, converts to a number when input is non-numeric.
17470 */
17471 var unaryPlus = typed(unaryPlus_name, {
17472 number: unaryPlusNumber,
17473 Complex: function Complex(x) {
17474 return x; // complex numbers are immutable
17475 },
17476 BigNumber: function BigNumber(x) {
17477 return x; // bignumbers are immutable
17478 },
17479 Fraction: function Fraction(x) {
17480 return x; // fractions are immutable
17481 },
17482 Unit: function Unit(x) {
17483 return x.clone();
17484 },
17485 'Array | Matrix': function ArrayMatrix(x) {
17486 // deep map collection, skip zeros since unaryPlus(0) = 0
17487 return deepMap(x, unaryPlus, true);
17488 },
17489 'boolean | string': function booleanString(x) {
17490 // convert to a number or bignumber
17491 return config.number === 'BigNumber' ? new BigNumber(+x) : +x;
17492 }
17493 });
17494 return unaryPlus;
17495});
17496// CONCATENATED MODULE: ./src/function/arithmetic/abs.js
17497
17498
17499
17500var abs_name = 'abs';
17501var abs_dependencies = ['typed'];
17502var createAbs =
17503/* #__PURE__ */
17504Object(factory["a" /* factory */])(abs_name, abs_dependencies, function (_ref) {
17505 var typed = _ref.typed;
17506
17507 /**
17508 * Calculate the absolute value of a number. For matrices, the function is
17509 * evaluated element wise.
17510 *
17511 * Syntax:
17512 *
17513 * math.abs(x)
17514 *
17515 * Examples:
17516 *
17517 * math.abs(3.5) // returns number 3.5
17518 * math.abs(-4.2) // returns number 4.2
17519 *
17520 * math.abs([3, -5, -1, 0, 2]) // returns Array [3, 5, 1, 0, 2]
17521 *
17522 * See also:
17523 *
17524 * sign
17525 *
17526 * @param {number | BigNumber | Fraction | Complex | Array | Matrix | Unit} x
17527 * A number or matrix for which to get the absolute value
17528 * @return {number | BigNumber | Fraction | Complex | Array | Matrix | Unit}
17529 * Absolute value of `x`
17530 */
17531 var abs = typed(abs_name, {
17532 number: absNumber,
17533 Complex: function Complex(x) {
17534 return x.abs();
17535 },
17536 BigNumber: function BigNumber(x) {
17537 return x.abs();
17538 },
17539 Fraction: function Fraction(x) {
17540 return x.abs();
17541 },
17542 'Array | Matrix': function ArrayMatrix(x) {
17543 // deep map collection, skip zeros since abs(0) = 0
17544 return deepMap(x, abs, true);
17545 },
17546 Unit: function Unit(x) {
17547 return x.abs();
17548 }
17549 });
17550 return abs;
17551});
17552// CONCATENATED MODULE: ./src/function/matrix/apply.js
17553
17554
17555
17556
17557var apply_name = 'apply';
17558var apply_dependencies = ['typed', 'isInteger'];
17559var createApply =
17560/* #__PURE__ */
17561Object(factory["a" /* factory */])(apply_name, apply_dependencies, function (_ref) {
17562 var typed = _ref.typed,
17563 isInteger = _ref.isInteger;
17564
17565 /**
17566 * Apply a function that maps an array to a scalar
17567 * along a given axis of a matrix or array.
17568 * Returns a new matrix or array with one less dimension than the input.
17569 *
17570 * Syntax:
17571 *
17572 * math.apply(A, dim, callback)
17573 *
17574 * Where:
17575 *
17576 * - `dim: number` is a zero-based dimension over which to concatenate the matrices.
17577 *
17578 * Examples:
17579 *
17580 * const A = [[1, 2], [3, 4]]
17581 * const sum = math.sum
17582 *
17583 * math.apply(A, 0, sum) // returns [4, 6]
17584 * math.apply(A, 1, sum) // returns [3, 7]
17585 *
17586 * See also:
17587 *
17588 * map, filter, forEach
17589 *
17590 * @param {Array | Matrix} array The input Matrix
17591 * @param {number} dim The dimension along which the callback is applied
17592 * @param {Function} callback The callback function that is applied. This Function
17593 * should take an array or 1-d matrix as an input and
17594 * return a number.
17595 * @return {Array | Matrix} res The residual matrix with the function applied over some dimension.
17596 */
17597 var apply = typed(apply_name, {
17598 'Array | Matrix, number | BigNumber, function': function ArrayMatrixNumberBigNumberFunction(mat, dim, callback) {
17599 if (!isInteger(dim)) {
17600 throw new TypeError('Integer number expected for dimension');
17601 }
17602
17603 var size = Array.isArray(mat) ? Object(utils_array["a" /* arraySize */])(mat) : mat.size();
17604
17605 if (dim < 0 || dim >= size.length) {
17606 throw new IndexError["a" /* IndexError */](dim, size.length);
17607 }
17608
17609 if (Object(is["v" /* isMatrix */])(mat)) {
17610 return mat.create(_apply(mat.valueOf(), dim, callback));
17611 } else {
17612 return _apply(mat, dim, callback);
17613 }
17614 }
17615 });
17616 return apply;
17617});
17618/**
17619 * Recursively reduce a matrix
17620 * @param {Array} mat
17621 * @param {number} dim
17622 * @param {Function} callback
17623 * @returns {Array} ret
17624 * @private
17625 */
17626
17627function _apply(mat, dim, callback) {
17628 var i, ret, tran;
17629
17630 if (dim <= 0) {
17631 if (!Array.isArray(mat[0])) {
17632 return callback(mat);
17633 } else {
17634 tran = apply_switch(mat);
17635 ret = [];
17636
17637 for (i = 0; i < tran.length; i++) {
17638 ret[i] = _apply(tran[i], dim - 1, callback);
17639 }
17640
17641 return ret;
17642 }
17643 } else {
17644 ret = [];
17645
17646 for (i = 0; i < mat.length; i++) {
17647 ret[i] = _apply(mat[i], dim - 1, callback);
17648 }
17649
17650 return ret;
17651 }
17652}
17653/**
17654 * Transpose a matrix
17655 * @param {Array} mat
17656 * @returns {Array} ret
17657 * @private
17658 */
17659
17660
17661function apply_switch(mat) {
17662 var I = mat.length;
17663 var J = mat[0].length;
17664 var i, j;
17665 var ret = [];
17666
17667 for (j = 0; j < J; j++) {
17668 var tmp = [];
17669
17670 for (i = 0; i < I; i++) {
17671 tmp.push(mat[i][j]);
17672 }
17673
17674 ret.push(tmp);
17675 }
17676
17677 return ret;
17678}
17679// CONCATENATED MODULE: ./src/function/arithmetic/addScalar.js
17680
17681
17682var addScalar_name = 'addScalar';
17683var addScalar_dependencies = ['typed'];
17684var createAddScalar =
17685/* #__PURE__ */
17686Object(factory["a" /* factory */])(addScalar_name, addScalar_dependencies, function (_ref) {
17687 var typed = _ref.typed;
17688
17689 /**
17690 * Add two scalar values, `x + y`.
17691 * This function is meant for internal use: it is used by the public function
17692 * `add`
17693 *
17694 * This function does not support collections (Array or Matrix).
17695 *
17696 * @param {number | BigNumber | Fraction | Complex | Unit} x First value to add
17697 * @param {number | BigNumber | Fraction | Complex} y Second value to add
17698 * @return {number | BigNumber | Fraction | Complex | Unit} Sum of `x` and `y`
17699 * @private
17700 */
17701 var addScalar = typed(addScalar_name, {
17702 'number, number': addNumber,
17703 'Complex, Complex': function ComplexComplex(x, y) {
17704 return x.add(y);
17705 },
17706 'BigNumber, BigNumber': function BigNumberBigNumber(x, y) {
17707 return x.plus(y);
17708 },
17709 'Fraction, Fraction': function FractionFraction(x, y) {
17710 return x.add(y);
17711 },
17712 'Unit, Unit': function UnitUnit(x, y) {
17713 if (x.value === null || x.value === undefined) throw new Error('Parameter x contains a unit with undefined value');
17714 if (y.value === null || y.value === undefined) throw new Error('Parameter y contains a unit with undefined value');
17715 if (!x.equalBase(y)) throw new Error('Units do not match');
17716 var res = x.clone();
17717 res.value = addScalar(res.value, y.value);
17718 res.fixPrefix = false;
17719 return res;
17720 }
17721 });
17722 return addScalar;
17723});
17724// CONCATENATED MODULE: ./src/function/arithmetic/cbrt.js
17725
17726
17727
17728
17729var cbrt_name = 'cbrt';
17730var cbrt_dependencies = ['config', 'typed', 'isNegative', 'unaryMinus', 'matrix', 'Complex', 'BigNumber', 'Fraction'];
17731var createCbrt =
17732/* #__PURE__ */
17733Object(factory["a" /* factory */])(cbrt_name, cbrt_dependencies, function (_ref) {
17734 var config = _ref.config,
17735 typed = _ref.typed,
17736 isNegative = _ref.isNegative,
17737 unaryMinus = _ref.unaryMinus,
17738 matrix = _ref.matrix,
17739 Complex = _ref.Complex,
17740 BigNumber = _ref.BigNumber,
17741 Fraction = _ref.Fraction;
17742
17743 /**
17744 * Calculate the cubic root of a value.
17745 *
17746 * For matrices, the function is evaluated element wise.
17747 *
17748 * Syntax:
17749 *
17750 * math.cbrt(x)
17751 * math.cbrt(x, allRoots)
17752 *
17753 * Examples:
17754 *
17755 * math.cbrt(27) // returns 3
17756 * math.cube(3) // returns 27
17757 * math.cbrt(-64) // returns -4
17758 * math.cbrt(math.unit('27 m^3')) // returns Unit 3 m
17759 * math.cbrt([27, 64, 125]) // returns [3, 4, 5]
17760 *
17761 * const x = math.complex('8i')
17762 * math.cbrt(x) // returns Complex 1.7320508075689 + i
17763 * math.cbrt(x, true) // returns Matrix [
17764 * // 1.7320508075689 + i
17765 * // -1.7320508075689 + i
17766 * // -2i
17767 * // ]
17768 *
17769 * See also:
17770 *
17771 * square, sqrt, cube
17772 *
17773 * @param {number | BigNumber | Complex | Unit | Array | Matrix} x
17774 * Value for which to calculate the cubic root.
17775 * @param {boolean} [allRoots] Optional, false by default. Only applicable
17776 * when `x` is a number or complex number. If true, all complex
17777 * roots are returned, if false (default) the principal root is
17778 * returned.
17779 * @return {number | BigNumber | Complex | Unit | Array | Matrix}
17780 * Returns the cubic root of `x`
17781 */
17782 var cbrt = typed(cbrt_name, {
17783 number: cbrtNumber,
17784 // note: signature 'number, boolean' is also supported,
17785 // created by typed as it knows how to convert number to Complex
17786 Complex: _cbrtComplex,
17787 'Complex, boolean': _cbrtComplex,
17788 BigNumber: function BigNumber(x) {
17789 return x.cbrt();
17790 },
17791 Unit: _cbrtUnit,
17792 'Array | Matrix': function ArrayMatrix(x) {
17793 // deep map collection, skip zeros since cbrt(0) = 0
17794 return deepMap(x, cbrt, true);
17795 }
17796 });
17797 /**
17798 * Calculate the cubic root for a complex number
17799 * @param {Complex} x
17800 * @param {boolean} [allRoots] If true, the function will return an array
17801 * with all three roots. If false or undefined,
17802 * the principal root is returned.
17803 * @returns {Complex | Array.<Complex> | Matrix.<Complex>} Returns the cubic root(s) of x
17804 * @private
17805 */
17806
17807 function _cbrtComplex(x, allRoots) {
17808 // https://www.wikiwand.com/en/Cube_root#/Complex_numbers
17809 var arg3 = x.arg() / 3;
17810 var abs = x.abs(); // principal root:
17811
17812 var principal = new Complex(cbrtNumber(abs), 0).mul(new Complex(0, arg3).exp());
17813
17814 if (allRoots) {
17815 var all = [principal, new Complex(cbrtNumber(abs), 0).mul(new Complex(0, arg3 + Math.PI * 2 / 3).exp()), new Complex(cbrtNumber(abs), 0).mul(new Complex(0, arg3 - Math.PI * 2 / 3).exp())];
17816 return config.matrix === 'Array' ? all : matrix(all);
17817 } else {
17818 return principal;
17819 }
17820 }
17821 /**
17822 * Calculate the cubic root for a Unit
17823 * @param {Unit} x
17824 * @return {Unit} Returns the cubic root of x
17825 * @private
17826 */
17827
17828
17829 function _cbrtUnit(x) {
17830 if (x.value && Object(is["j" /* isComplex */])(x.value)) {
17831 var result = x.clone();
17832 result.value = 1.0;
17833 result = result.pow(1.0 / 3); // Compute the units
17834
17835 result.value = _cbrtComplex(x.value); // Compute the value
17836
17837 return result;
17838 } else {
17839 var negate = isNegative(x.value);
17840
17841 if (negate) {
17842 x.value = unaryMinus(x.value);
17843 } // TODO: create a helper function for this
17844
17845
17846 var third;
17847
17848 if (Object(is["e" /* isBigNumber */])(x.value)) {
17849 third = new BigNumber(1).div(3);
17850 } else if (Object(is["o" /* isFraction */])(x.value)) {
17851 third = new Fraction(1, 3);
17852 } else {
17853 third = 1 / 3;
17854 }
17855
17856 var _result = x.pow(third);
17857
17858 if (negate) {
17859 _result.value = unaryMinus(_result.value);
17860 }
17861
17862 return _result;
17863 }
17864 }
17865
17866 return cbrt;
17867});
17868// CONCATENATED MODULE: ./src/function/arithmetic/ceil.js
17869
17870
17871
17872
17873
17874var ceil_name = 'ceil';
17875var ceil_dependencies = ['typed', 'config', 'round'];
17876var createCeil =
17877/* #__PURE__ */
17878Object(factory["a" /* factory */])(ceil_name, ceil_dependencies, function (_ref) {
17879 var typed = _ref.typed,
17880 config = _ref.config,
17881 round = _ref.round;
17882
17883 /**
17884 * Round a value towards plus infinity
17885 * If `x` is complex, both real and imaginary part are rounded towards plus infinity.
17886 * For matrices, the function is evaluated element wise.
17887 *
17888 * Syntax:
17889 *
17890 * math.ceil(x)
17891 *
17892 * Examples:
17893 *
17894 * math.ceil(3.2) // returns number 4
17895 * math.ceil(3.8) // returns number 4
17896 * math.ceil(-4.2) // returns number -4
17897 * math.ceil(-4.7) // returns number -4
17898 *
17899 * const c = math.complex(3.2, -2.7)
17900 * math.ceil(c) // returns Complex 4 - 2i
17901 *
17902 * math.ceil([3.2, 3.8, -4.7]) // returns Array [4, 4, -4]
17903 *
17904 * See also:
17905 *
17906 * floor, fix, round
17907 *
17908 * @param {number | BigNumber | Fraction | Complex | Array | Matrix} x Number to be rounded
17909 * @return {number | BigNumber | Fraction | Complex | Array | Matrix} Rounded value
17910 */
17911 var ceil = typed('ceil', {
17912 number: function number(x) {
17913 if (Object(utils_number["m" /* nearlyEqual */])(x, round(x), config.epsilon)) {
17914 return round(x);
17915 } else {
17916 return ceilNumber(x);
17917 }
17918 },
17919 Complex: function Complex(x) {
17920 return x.ceil();
17921 },
17922 BigNumber: function BigNumber(x) {
17923 if (nearlyEqual(x, round(x), config.epsilon)) {
17924 return round(x);
17925 } else {
17926 return x.ceil();
17927 }
17928 },
17929 Fraction: function Fraction(x) {
17930 return x.ceil();
17931 },
17932 'Array | Matrix': function ArrayMatrix(x) {
17933 // deep map collection, skip zeros since ceil(0) = 0
17934 return deepMap(x, ceil, true);
17935 }
17936 });
17937 return ceil;
17938});
17939// CONCATENATED MODULE: ./src/function/arithmetic/cube.js
17940
17941
17942
17943var cube_name = 'cube';
17944var cube_dependencies = ['typed'];
17945var createCube =
17946/* #__PURE__ */
17947Object(factory["a" /* factory */])(cube_name, cube_dependencies, function (_ref) {
17948 var typed = _ref.typed;
17949
17950 /**
17951 * Compute the cube of a value, `x * x * x`.
17952 * For matrices, the function is evaluated element wise.
17953 *
17954 * Syntax:
17955 *
17956 * math.cube(x)
17957 *
17958 * Examples:
17959 *
17960 * math.cube(2) // returns number 8
17961 * math.pow(2, 3) // returns number 8
17962 * math.cube(4) // returns number 64
17963 * 4 * 4 * 4 // returns number 64
17964 *
17965 * math.cube([1, 2, 3, 4]) // returns Array [1, 8, 27, 64]
17966 *
17967 * See also:
17968 *
17969 * multiply, square, pow, cbrt
17970 *
17971 * @param {number | BigNumber | Fraction | Complex | Array | Matrix | Unit} x Number for which to calculate the cube
17972 * @return {number | BigNumber | Fraction | Complex | Array | Matrix | Unit} Cube of x
17973 */
17974 var cube = typed(cube_name, {
17975 number: cubeNumber,
17976 Complex: function Complex(x) {
17977 return x.mul(x).mul(x); // Is faster than pow(x, 3)
17978 },
17979 BigNumber: function BigNumber(x) {
17980 return x.times(x).times(x);
17981 },
17982 Fraction: function Fraction(x) {
17983 return x.pow(3); // Is faster than mul()mul()mul()
17984 },
17985 'Array | Matrix': function ArrayMatrix(x) {
17986 // deep map collection, skip zeros since cube(0) = 0
17987 return deepMap(x, cube, true);
17988 },
17989 Unit: function Unit(x) {
17990 return x.pow(3);
17991 }
17992 });
17993 return cube;
17994});
17995// CONCATENATED MODULE: ./src/function/arithmetic/exp.js
17996
17997
17998
17999var exp_name = 'exp';
18000var exp_dependencies = ['typed'];
18001var createExp =
18002/* #__PURE__ */
18003Object(factory["a" /* factory */])(exp_name, exp_dependencies, function (_ref) {
18004 var typed = _ref.typed;
18005
18006 /**
18007 * Calculate the exponent of a value.
18008 * For matrices, the function is evaluated element wise.
18009 *
18010 * Syntax:
18011 *
18012 * math.exp(x)
18013 *
18014 * Examples:
18015 *
18016 * math.exp(2) // returns number 7.3890560989306495
18017 * math.pow(math.e, 2) // returns number 7.3890560989306495
18018 * math.log(math.exp(2)) // returns number 2
18019 *
18020 * math.exp([1, 2, 3])
18021 * // returns Array [
18022 * // 2.718281828459045,
18023 * // 7.3890560989306495,
18024 * // 20.085536923187668
18025 * // ]
18026 *
18027 * See also:
18028 *
18029 * expm1, log, pow
18030 *
18031 * @param {number | BigNumber | Complex | Array | Matrix} x A number or matrix to exponentiate
18032 * @return {number | BigNumber | Complex | Array | Matrix} Exponent of `x`
18033 */
18034 var exp = typed(exp_name, {
18035 number: expNumber,
18036 Complex: function Complex(x) {
18037 return x.exp();
18038 },
18039 BigNumber: function BigNumber(x) {
18040 return x.exp();
18041 },
18042 'Array | Matrix': function ArrayMatrix(x) {
18043 // TODO: exp(sparse) should return a dense matrix since exp(0)==1
18044 return deepMap(x, exp);
18045 }
18046 });
18047 return exp;
18048});
18049// CONCATENATED MODULE: ./src/function/arithmetic/expm1.js
18050
18051
18052
18053var expm1_name = 'expm1';
18054var expm1_dependencies = ['typed', 'Complex'];
18055var createExpm1 =
18056/* #__PURE__ */
18057Object(factory["a" /* factory */])(expm1_name, expm1_dependencies, function (_ref) {
18058 var typed = _ref.typed,
18059 _Complex = _ref.Complex;
18060
18061 /**
18062 * Calculate the value of subtracting 1 from the exponential value.
18063 * For matrices, the function is evaluated element wise.
18064 *
18065 * Syntax:
18066 *
18067 * math.expm1(x)
18068 *
18069 * Examples:
18070 *
18071 * math.expm1(2) // returns number 6.38905609893065
18072 * math.pow(math.e, 2) - 1 // returns number 6.3890560989306495
18073 * math.log(math.expm1(2) + 1) // returns number 2
18074 *
18075 * math.expm1([1, 2, 3])
18076 * // returns Array [
18077 * // 1.718281828459045,
18078 * // 6.3890560989306495,
18079 * // 19.085536923187668
18080 * // ]
18081 *
18082 * See also:
18083 *
18084 * exp, log, pow
18085 *
18086 * @param {number | BigNumber | Complex | Array | Matrix} x A number or matrix to apply expm1
18087 * @return {number | BigNumber | Complex | Array | Matrix} Exponent of `x`
18088 */
18089 var expm1 = typed(expm1_name, {
18090 number: expm1Number,
18091 Complex: function Complex(x) {
18092 var r = Math.exp(x.re);
18093 return new _Complex(r * Math.cos(x.im) - 1, r * Math.sin(x.im));
18094 },
18095 BigNumber: function BigNumber(x) {
18096 return x.exp().minus(1);
18097 },
18098 'Array | Matrix': function ArrayMatrix(x) {
18099 return deepMap(x, expm1);
18100 }
18101 });
18102 return expm1;
18103});
18104// CONCATENATED MODULE: ./src/function/arithmetic/fix.js
18105
18106
18107var fix_name = 'fix';
18108var fix_dependencies = ['typed', 'Complex', 'ceil', 'floor'];
18109var createFix =
18110/* #__PURE__ */
18111Object(factory["a" /* factory */])(fix_name, fix_dependencies, function (_ref) {
18112 var typed = _ref.typed,
18113 _Complex = _ref.Complex,
18114 ceil = _ref.ceil,
18115 floor = _ref.floor;
18116
18117 /**
18118 * Round a value towards zero.
18119 * For matrices, the function is evaluated element wise.
18120 *
18121 * Syntax:
18122 *
18123 * math.fix(x)
18124 *
18125 * Examples:
18126 *
18127 * math.fix(3.2) // returns number 3
18128 * math.fix(3.8) // returns number 3
18129 * math.fix(-4.2) // returns number -4
18130 * math.fix(-4.7) // returns number -4
18131 *
18132 * const c = math.complex(3.2, -2.7)
18133 * math.fix(c) // returns Complex 3 - 2i
18134 *
18135 * math.fix([3.2, 3.8, -4.7]) // returns Array [3, 3, -4]
18136 *
18137 * See also:
18138 *
18139 * ceil, floor, round
18140 *
18141 * @param {number | BigNumber | Fraction | Complex | Array | Matrix} x Number to be rounded
18142 * @return {number | BigNumber | Fraction | Complex | Array | Matrix} Rounded value
18143 */
18144 var fix = typed('fix', {
18145 number: function number(x) {
18146 return x > 0 ? floor(x) : ceil(x);
18147 },
18148 Complex: function Complex(x) {
18149 return new _Complex(x.re > 0 ? Math.floor(x.re) : Math.ceil(x.re), x.im > 0 ? Math.floor(x.im) : Math.ceil(x.im));
18150 },
18151 BigNumber: function BigNumber(x) {
18152 return x.isNegative() ? ceil(x) : floor(x);
18153 },
18154 Fraction: function Fraction(x) {
18155 return x.s < 0 ? x.ceil() : x.floor();
18156 },
18157 'Array | Matrix': function ArrayMatrix(x) {
18158 // deep map collection, skip zeros since fix(0) = 0
18159 return deepMap(x, fix, true);
18160 }
18161 });
18162 return fix;
18163});
18164// CONCATENATED MODULE: ./src/function/arithmetic/floor.js
18165
18166
18167
18168
18169var floor_name = 'floor';
18170var floor_dependencies = ['typed', 'config', 'round'];
18171var createFloor =
18172/* #__PURE__ */
18173Object(factory["a" /* factory */])(floor_name, floor_dependencies, function (_ref) {
18174 var typed = _ref.typed,
18175 config = _ref.config,
18176 round = _ref.round;
18177
18178 /**
18179 * Round a value towards minus infinity.
18180 * For matrices, the function is evaluated element wise.
18181 *
18182 * Syntax:
18183 *
18184 * math.floor(x)
18185 *
18186 * Examples:
18187 *
18188 * math.floor(3.2) // returns number 3
18189 * math.floor(3.8) // returns number 3
18190 * math.floor(-4.2) // returns number -5
18191 * math.floor(-4.7) // returns number -5
18192 *
18193 * const c = math.complex(3.2, -2.7)
18194 * math.floor(c) // returns Complex 3 - 3i
18195 *
18196 * math.floor([3.2, 3.8, -4.7]) // returns Array [3, 3, -5]
18197 *
18198 * See also:
18199 *
18200 * ceil, fix, round
18201 *
18202 * @param {number | BigNumber | Fraction | Complex | Array | Matrix} x Number to be rounded
18203 * @return {number | BigNumber | Fraction | Complex | Array | Matrix} Rounded value
18204 */
18205 var floor = typed('floor', {
18206 number: function number(x) {
18207 if (Object(utils_number["m" /* nearlyEqual */])(x, round(x), config.epsilon)) {
18208 return round(x);
18209 } else {
18210 return Math.floor(x);
18211 }
18212 },
18213 Complex: function Complex(x) {
18214 return x.floor();
18215 },
18216 BigNumber: function BigNumber(x) {
18217 if (nearlyEqual(x, round(x), config.epsilon)) {
18218 return round(x);
18219 } else {
18220 return x.floor();
18221 }
18222 },
18223 Fraction: function Fraction(x) {
18224 return x.floor();
18225 },
18226 'Array | Matrix': function ArrayMatrix(x) {
18227 // deep map collection, skip zeros since floor(0) = 0
18228 return deepMap(x, floor, true);
18229 }
18230 });
18231 return floor;
18232});
18233// CONCATENATED MODULE: ./src/type/matrix/utils/algorithm01.js
18234
18235
18236var algorithm01_name = 'algorithm01';
18237var algorithm01_dependencies = ['typed'];
18238var createAlgorithm01 =
18239/* #__PURE__ */
18240Object(factory["a" /* factory */])(algorithm01_name, algorithm01_dependencies, function (_ref) {
18241 var typed = _ref.typed;
18242
18243 /**
18244 * Iterates over SparseMatrix nonzero items and invokes the callback function f(Dij, Sij).
18245 * Callback function invoked NNZ times (number of nonzero items in SparseMatrix).
18246 *
18247 *
18248 * ┌ f(Dij, Sij) ; S(i,j) !== 0
18249 * C(i,j) = ┤
18250 * └ Dij ; otherwise
18251 *
18252 *
18253 * @param {Matrix} denseMatrix The DenseMatrix instance (D)
18254 * @param {Matrix} sparseMatrix The SparseMatrix instance (S)
18255 * @param {Function} callback The f(Dij,Sij) operation to invoke, where Dij = DenseMatrix(i,j) and Sij = SparseMatrix(i,j)
18256 * @param {boolean} inverse A true value indicates callback should be invoked f(Sij,Dij)
18257 *
18258 * @return {Matrix} DenseMatrix (C)
18259 *
18260 * see https://github.com/josdejong/mathjs/pull/346#issuecomment-97477571
18261 */
18262 return function algorithm1(denseMatrix, sparseMatrix, callback, inverse) {
18263 // dense matrix arrays
18264 var adata = denseMatrix._data;
18265 var asize = denseMatrix._size;
18266 var adt = denseMatrix._datatype; // sparse matrix arrays
18267
18268 var bvalues = sparseMatrix._values;
18269 var bindex = sparseMatrix._index;
18270 var bptr = sparseMatrix._ptr;
18271 var bsize = sparseMatrix._size;
18272 var bdt = sparseMatrix._datatype; // validate dimensions
18273
18274 if (asize.length !== bsize.length) {
18275 throw new DimensionError["a" /* DimensionError */](asize.length, bsize.length);
18276 } // check rows & columns
18277
18278
18279 if (asize[0] !== bsize[0] || asize[1] !== bsize[1]) {
18280 throw new RangeError('Dimension mismatch. Matrix A (' + asize + ') must match Matrix B (' + bsize + ')');
18281 } // sparse matrix cannot be a Pattern matrix
18282
18283
18284 if (!bvalues) {
18285 throw new Error('Cannot perform operation on Dense Matrix and Pattern Sparse Matrix');
18286 } // rows & columns
18287
18288
18289 var rows = asize[0];
18290 var columns = asize[1]; // process data types
18291
18292 var dt = typeof adt === 'string' && adt === bdt ? adt : undefined; // callback function
18293
18294 var cf = dt ? typed.find(callback, [dt, dt]) : callback; // vars
18295
18296 var i, j; // result (DenseMatrix)
18297
18298 var cdata = []; // initialize c
18299
18300 for (i = 0; i < rows; i++) {
18301 cdata[i] = [];
18302 } // workspace
18303
18304
18305 var x = []; // marks indicating we have a value in x for a given column
18306
18307 var w = []; // loop columns in b
18308
18309 for (j = 0; j < columns; j++) {
18310 // column mark
18311 var mark = j + 1; // values in column j
18312
18313 for (var k0 = bptr[j], k1 = bptr[j + 1], k = k0; k < k1; k++) {
18314 // row
18315 i = bindex[k]; // update workspace
18316
18317 x[i] = inverse ? cf(bvalues[k], adata[i][j]) : cf(adata[i][j], bvalues[k]); // mark i as updated
18318
18319 w[i] = mark;
18320 } // loop rows
18321
18322
18323 for (i = 0; i < rows; i++) {
18324 // check row is in workspace
18325 if (w[i] === mark) {
18326 // c[i][j] was already calculated
18327 cdata[i][j] = x[i];
18328 } else {
18329 // item does not exist in S
18330 cdata[i][j] = adata[i][j];
18331 }
18332 }
18333 } // return dense matrix
18334
18335
18336 return denseMatrix.createDenseMatrix({
18337 data: cdata,
18338 size: [rows, columns],
18339 datatype: dt
18340 });
18341 };
18342});
18343// CONCATENATED MODULE: ./src/type/matrix/utils/algorithm04.js
18344
18345
18346var algorithm04_name = 'algorithm04';
18347var algorithm04_dependencies = ['typed', 'equalScalar'];
18348var createAlgorithm04 =
18349/* #__PURE__ */
18350Object(factory["a" /* factory */])(algorithm04_name, algorithm04_dependencies, function (_ref) {
18351 var typed = _ref.typed,
18352 equalScalar = _ref.equalScalar;
18353
18354 /**
18355 * Iterates over SparseMatrix A and SparseMatrix B nonzero items and invokes the callback function f(Aij, Bij).
18356 * Callback function invoked MAX(NNZA, NNZB) times
18357 *
18358 *
18359 * ┌ f(Aij, Bij) ; A(i,j) !== 0 && B(i,j) !== 0
18360 * C(i,j) = ┤ A(i,j) ; A(i,j) !== 0
18361 * └ B(i,j) ; B(i,j) !== 0
18362 *
18363 *
18364 * @param {Matrix} a The SparseMatrix instance (A)
18365 * @param {Matrix} b The SparseMatrix instance (B)
18366 * @param {Function} callback The f(Aij,Bij) operation to invoke
18367 *
18368 * @return {Matrix} SparseMatrix (C)
18369 *
18370 * see https://github.com/josdejong/mathjs/pull/346#issuecomment-97620294
18371 */
18372 return function algorithm04(a, b, callback) {
18373 // sparse matrix arrays
18374 var avalues = a._values;
18375 var aindex = a._index;
18376 var aptr = a._ptr;
18377 var asize = a._size;
18378 var adt = a._datatype; // sparse matrix arrays
18379
18380 var bvalues = b._values;
18381 var bindex = b._index;
18382 var bptr = b._ptr;
18383 var bsize = b._size;
18384 var bdt = b._datatype; // validate dimensions
18385
18386 if (asize.length !== bsize.length) {
18387 throw new DimensionError["a" /* DimensionError */](asize.length, bsize.length);
18388 } // check rows & columns
18389
18390
18391 if (asize[0] !== bsize[0] || asize[1] !== bsize[1]) {
18392 throw new RangeError('Dimension mismatch. Matrix A (' + asize + ') must match Matrix B (' + bsize + ')');
18393 } // rows & columns
18394
18395
18396 var rows = asize[0];
18397 var columns = asize[1]; // datatype
18398
18399 var dt; // equal signature to use
18400
18401 var eq = equalScalar; // zero value
18402
18403 var zero = 0; // callback signature to use
18404
18405 var cf = callback; // process data types
18406
18407 if (typeof adt === 'string' && adt === bdt) {
18408 // datatype
18409 dt = adt; // find signature that matches (dt, dt)
18410
18411 eq = typed.find(equalScalar, [dt, dt]); // convert 0 to the same datatype
18412
18413 zero = typed.convert(0, dt); // callback
18414
18415 cf = typed.find(callback, [dt, dt]);
18416 } // result arrays
18417
18418
18419 var cvalues = avalues && bvalues ? [] : undefined;
18420 var cindex = [];
18421 var cptr = []; // matrix
18422
18423 var c = a.createSparseMatrix({
18424 values: cvalues,
18425 index: cindex,
18426 ptr: cptr,
18427 size: [rows, columns],
18428 datatype: dt
18429 }); // workspace
18430
18431 var xa = avalues && bvalues ? [] : undefined;
18432 var xb = avalues && bvalues ? [] : undefined; // marks indicating we have a value in x for a given column
18433
18434 var wa = [];
18435 var wb = []; // vars
18436
18437 var i, j, k, k0, k1; // loop columns
18438
18439 for (j = 0; j < columns; j++) {
18440 // update cptr
18441 cptr[j] = cindex.length; // columns mark
18442
18443 var mark = j + 1; // loop A(:,j)
18444
18445 for (k0 = aptr[j], k1 = aptr[j + 1], k = k0; k < k1; k++) {
18446 // row
18447 i = aindex[k]; // update c
18448
18449 cindex.push(i); // update workspace
18450
18451 wa[i] = mark; // check we need to process values
18452
18453 if (xa) {
18454 xa[i] = avalues[k];
18455 }
18456 } // loop B(:,j)
18457
18458
18459 for (k0 = bptr[j], k1 = bptr[j + 1], k = k0; k < k1; k++) {
18460 // row
18461 i = bindex[k]; // check row exists in A
18462
18463 if (wa[i] === mark) {
18464 // update record in xa @ i
18465 if (xa) {
18466 // invoke callback
18467 var v = cf(xa[i], bvalues[k]); // check for zero
18468
18469 if (!eq(v, zero)) {
18470 // update workspace
18471 xa[i] = v;
18472 } else {
18473 // remove mark (index will be removed later)
18474 wa[i] = null;
18475 }
18476 }
18477 } else {
18478 // update c
18479 cindex.push(i); // update workspace
18480
18481 wb[i] = mark; // check we need to process values
18482
18483 if (xb) {
18484 xb[i] = bvalues[k];
18485 }
18486 }
18487 } // check we need to process values (non pattern matrix)
18488
18489
18490 if (xa && xb) {
18491 // initialize first index in j
18492 k = cptr[j]; // loop index in j
18493
18494 while (k < cindex.length) {
18495 // row
18496 i = cindex[k]; // check workspace has value @ i
18497
18498 if (wa[i] === mark) {
18499 // push value (Aij != 0 || (Aij != 0 && Bij != 0))
18500 cvalues[k] = xa[i]; // increment pointer
18501
18502 k++;
18503 } else if (wb[i] === mark) {
18504 // push value (bij != 0)
18505 cvalues[k] = xb[i]; // increment pointer
18506
18507 k++;
18508 } else {
18509 // remove index @ k
18510 cindex.splice(k, 1);
18511 }
18512 }
18513 }
18514 } // update cptr
18515
18516
18517 cptr[columns] = cindex.length; // return sparse matrix
18518
18519 return c;
18520 };
18521});
18522// CONCATENATED MODULE: ./src/type/matrix/utils/algorithm10.js
18523
18524var algorithm10_name = 'algorithm10';
18525var algorithm10_dependencies = ['typed', 'DenseMatrix'];
18526var createAlgorithm10 =
18527/* #__PURE__ */
18528Object(factory["a" /* factory */])(algorithm10_name, algorithm10_dependencies, function (_ref) {
18529 var typed = _ref.typed,
18530 DenseMatrix = _ref.DenseMatrix;
18531
18532 /**
18533 * Iterates over SparseMatrix S nonzero items and invokes the callback function f(Sij, b).
18534 * Callback function invoked NZ times (number of nonzero items in S).
18535 *
18536 *
18537 * ┌ f(Sij, b) ; S(i,j) !== 0
18538 * C(i,j) = ┤
18539 * └ b ; otherwise
18540 *
18541 *
18542 * @param {Matrix} s The SparseMatrix instance (S)
18543 * @param {Scalar} b The Scalar value
18544 * @param {Function} callback The f(Aij,b) operation to invoke
18545 * @param {boolean} inverse A true value indicates callback should be invoked f(b,Sij)
18546 *
18547 * @return {Matrix} DenseMatrix (C)
18548 *
18549 * https://github.com/josdejong/mathjs/pull/346#issuecomment-97626813
18550 */
18551 return function algorithm10(s, b, callback, inverse) {
18552 // sparse matrix arrays
18553 var avalues = s._values;
18554 var aindex = s._index;
18555 var aptr = s._ptr;
18556 var asize = s._size;
18557 var adt = s._datatype; // sparse matrix cannot be a Pattern matrix
18558
18559 if (!avalues) {
18560 throw new Error('Cannot perform operation on Pattern Sparse Matrix and Scalar value');
18561 } // rows & columns
18562
18563
18564 var rows = asize[0];
18565 var columns = asize[1]; // datatype
18566
18567 var dt; // callback signature to use
18568
18569 var cf = callback; // process data types
18570
18571 if (typeof adt === 'string') {
18572 // datatype
18573 dt = adt; // convert b to the same datatype
18574
18575 b = typed.convert(b, dt); // callback
18576
18577 cf = typed.find(callback, [dt, dt]);
18578 } // result arrays
18579
18580
18581 var cdata = []; // matrix
18582
18583 var c = new DenseMatrix({
18584 data: cdata,
18585 size: [rows, columns],
18586 datatype: dt
18587 }); // workspaces
18588
18589 var x = []; // marks indicating we have a value in x for a given column
18590
18591 var w = []; // loop columns
18592
18593 for (var j = 0; j < columns; j++) {
18594 // columns mark
18595 var mark = j + 1; // values in j
18596
18597 for (var k0 = aptr[j], k1 = aptr[j + 1], k = k0; k < k1; k++) {
18598 // row
18599 var r = aindex[k]; // update workspace
18600
18601 x[r] = avalues[k];
18602 w[r] = mark;
18603 } // loop rows
18604
18605
18606 for (var i = 0; i < rows; i++) {
18607 // initialize C on first column
18608 if (j === 0) {
18609 // create row array
18610 cdata[i] = [];
18611 } // check sparse matrix has a value @ i,j
18612
18613
18614 if (w[i] === mark) {
18615 // invoke callback, update C
18616 cdata[i][j] = inverse ? cf(b, x[i]) : cf(x[i], b);
18617 } else {
18618 // dense matrix value @ i, j
18619 cdata[i][j] = b;
18620 }
18621 }
18622 } // return sparse matrix
18623
18624
18625 return c;
18626 };
18627});
18628// CONCATENATED MODULE: ./src/type/matrix/utils/algorithm13.js
18629
18630
18631var algorithm13_name = 'algorithm13';
18632var algorithm13_dependencies = ['typed'];
18633var createAlgorithm13 =
18634/* #__PURE__ */
18635Object(factory["a" /* factory */])(algorithm13_name, algorithm13_dependencies, function (_ref) {
18636 var typed = _ref.typed;
18637
18638 /**
18639 * Iterates over DenseMatrix items and invokes the callback function f(Aij..z, Bij..z).
18640 * Callback function invoked MxN times.
18641 *
18642 * C(i,j,...z) = f(Aij..z, Bij..z)
18643 *
18644 * @param {Matrix} a The DenseMatrix instance (A)
18645 * @param {Matrix} b The DenseMatrix instance (B)
18646 * @param {Function} callback The f(Aij..z,Bij..z) operation to invoke
18647 *
18648 * @return {Matrix} DenseMatrix (C)
18649 *
18650 * https://github.com/josdejong/mathjs/pull/346#issuecomment-97658658
18651 */
18652 return function algorithm13(a, b, callback) {
18653 // a arrays
18654 var adata = a._data;
18655 var asize = a._size;
18656 var adt = a._datatype; // b arrays
18657
18658 var bdata = b._data;
18659 var bsize = b._size;
18660 var bdt = b._datatype; // c arrays
18661
18662 var csize = []; // validate dimensions
18663
18664 if (asize.length !== bsize.length) {
18665 throw new DimensionError["a" /* DimensionError */](asize.length, bsize.length);
18666 } // validate each one of the dimension sizes
18667
18668
18669 for (var s = 0; s < asize.length; s++) {
18670 // must match
18671 if (asize[s] !== bsize[s]) {
18672 throw new RangeError('Dimension mismatch. Matrix A (' + asize + ') must match Matrix B (' + bsize + ')');
18673 } // update dimension in c
18674
18675
18676 csize[s] = asize[s];
18677 } // datatype
18678
18679
18680 var dt; // callback signature to use
18681
18682 var cf = callback; // process data types
18683
18684 if (typeof adt === 'string' && adt === bdt) {
18685 // datatype
18686 dt = adt; // callback
18687
18688 cf = typed.find(callback, [dt, dt]);
18689 } // populate cdata, iterate through dimensions
18690
18691
18692 var cdata = csize.length > 0 ? _iterate(cf, 0, csize, csize[0], adata, bdata) : []; // c matrix
18693
18694 return a.createDenseMatrix({
18695 data: cdata,
18696 size: csize,
18697 datatype: dt
18698 });
18699 }; // recursive function
18700
18701 function _iterate(f, level, s, n, av, bv) {
18702 // initialize array for this level
18703 var cv = []; // check we reach the last level
18704
18705 if (level === s.length - 1) {
18706 // loop arrays in last level
18707 for (var i = 0; i < n; i++) {
18708 // invoke callback and store value
18709 cv[i] = f(av[i], bv[i]);
18710 }
18711 } else {
18712 // iterate current level
18713 for (var j = 0; j < n; j++) {
18714 // iterate next level
18715 cv[j] = _iterate(f, level + 1, s, s[level + 1], av[j], bv[j]);
18716 }
18717 }
18718
18719 return cv;
18720 }
18721});
18722// CONCATENATED MODULE: ./src/type/matrix/utils/algorithm14.js
18723
18724
18725var algorithm14_name = 'algorithm14';
18726var algorithm14_dependencies = ['typed'];
18727var createAlgorithm14 =
18728/* #__PURE__ */
18729Object(factory["a" /* factory */])(algorithm14_name, algorithm14_dependencies, function (_ref) {
18730 var typed = _ref.typed;
18731
18732 /**
18733 * Iterates over DenseMatrix items and invokes the callback function f(Aij..z, b).
18734 * Callback function invoked MxN times.
18735 *
18736 * C(i,j,...z) = f(Aij..z, b)
18737 *
18738 * @param {Matrix} a The DenseMatrix instance (A)
18739 * @param {Scalar} b The Scalar value
18740 * @param {Function} callback The f(Aij..z,b) operation to invoke
18741 * @param {boolean} inverse A true value indicates callback should be invoked f(b,Aij..z)
18742 *
18743 * @return {Matrix} DenseMatrix (C)
18744 *
18745 * https://github.com/josdejong/mathjs/pull/346#issuecomment-97659042
18746 */
18747 return function algorithm14(a, b, callback, inverse) {
18748 // a arrays
18749 var adata = a._data;
18750 var asize = a._size;
18751 var adt = a._datatype; // datatype
18752
18753 var dt; // callback signature to use
18754
18755 var cf = callback; // process data types
18756
18757 if (typeof adt === 'string') {
18758 // datatype
18759 dt = adt; // convert b to the same datatype
18760
18761 b = typed.convert(b, dt); // callback
18762
18763 cf = typed.find(callback, [dt, dt]);
18764 } // populate cdata, iterate through dimensions
18765
18766
18767 var cdata = asize.length > 0 ? _iterate(cf, 0, asize, asize[0], adata, b, inverse) : []; // c matrix
18768
18769 return a.createDenseMatrix({
18770 data: cdata,
18771 size: Object(utils_object["a" /* clone */])(asize),
18772 datatype: dt
18773 });
18774 }; // recursive function
18775
18776 function _iterate(f, level, s, n, av, bv, inverse) {
18777 // initialize array for this level
18778 var cv = []; // check we reach the last level
18779
18780 if (level === s.length - 1) {
18781 // loop arrays in last level
18782 for (var i = 0; i < n; i++) {
18783 // invoke callback and store value
18784 cv[i] = inverse ? f(bv, av[i]) : f(av[i], bv);
18785 }
18786 } else {
18787 // iterate current level
18788 for (var j = 0; j < n; j++) {
18789 // iterate next level
18790 cv[j] = _iterate(f, level + 1, s, s[level + 1], av[j], bv, inverse);
18791 }
18792 }
18793
18794 return cv;
18795 }
18796});
18797// CONCATENATED MODULE: ./src/function/arithmetic/gcd.js
18798
18799
18800
18801
18802
18803
18804
18805var gcd_name = 'gcd';
18806var gcd_dependencies = ['typed', 'matrix', 'equalScalar', 'BigNumber', 'DenseMatrix'];
18807var createGcd =
18808/* #__PURE__ */
18809Object(factory["a" /* factory */])(gcd_name, gcd_dependencies, function (_ref) {
18810 var typed = _ref.typed,
18811 matrix = _ref.matrix,
18812 equalScalar = _ref.equalScalar,
18813 BigNumber = _ref.BigNumber,
18814 DenseMatrix = _ref.DenseMatrix;
18815 var algorithm01 = createAlgorithm01({
18816 typed: typed
18817 });
18818 var algorithm04 = createAlgorithm04({
18819 typed: typed,
18820 equalScalar: equalScalar
18821 });
18822 var algorithm10 = createAlgorithm10({
18823 typed: typed,
18824 DenseMatrix: DenseMatrix
18825 });
18826 var algorithm13 = createAlgorithm13({
18827 typed: typed
18828 });
18829 var algorithm14 = createAlgorithm14({
18830 typed: typed
18831 });
18832 /**
18833 * Calculate the greatest common divisor for two or more values or arrays.
18834 *
18835 * For matrices, the function is evaluated element wise.
18836 *
18837 * Syntax:
18838 *
18839 * math.gcd(a, b)
18840 * math.gcd(a, b, c, ...)
18841 *
18842 * Examples:
18843 *
18844 * math.gcd(8, 12) // returns 4
18845 * math.gcd(-4, 6) // returns 2
18846 * math.gcd(25, 15, -10) // returns 5
18847 *
18848 * math.gcd([8, -4], [12, 6]) // returns [4, 2]
18849 *
18850 * See also:
18851 *
18852 * lcm, xgcd
18853 *
18854 * @param {... number | BigNumber | Fraction | Array | Matrix} args Two or more integer numbers
18855 * @return {number | BigNumber | Fraction | Array | Matrix} The greatest common divisor
18856 */
18857
18858 var gcd = typed(gcd_name, {
18859 'number, number': gcdNumber,
18860 'BigNumber, BigNumber': _gcdBigNumber,
18861 'Fraction, Fraction': function FractionFraction(x, y) {
18862 return x.gcd(y);
18863 },
18864 'SparseMatrix, SparseMatrix': function SparseMatrixSparseMatrix(x, y) {
18865 return algorithm04(x, y, gcd);
18866 },
18867 'SparseMatrix, DenseMatrix': function SparseMatrixDenseMatrix(x, y) {
18868 return algorithm01(y, x, gcd, true);
18869 },
18870 'DenseMatrix, SparseMatrix': function DenseMatrixSparseMatrix(x, y) {
18871 return algorithm01(x, y, gcd, false);
18872 },
18873 'DenseMatrix, DenseMatrix': function DenseMatrixDenseMatrix(x, y) {
18874 return algorithm13(x, y, gcd);
18875 },
18876 'Array, Array': function ArrayArray(x, y) {
18877 // use matrix implementation
18878 return gcd(matrix(x), matrix(y)).valueOf();
18879 },
18880 'Array, Matrix': function ArrayMatrix(x, y) {
18881 // use matrix implementation
18882 return gcd(matrix(x), y);
18883 },
18884 'Matrix, Array': function MatrixArray(x, y) {
18885 // use matrix implementation
18886 return gcd(x, matrix(y));
18887 },
18888 'SparseMatrix, number | BigNumber': function SparseMatrixNumberBigNumber(x, y) {
18889 return algorithm10(x, y, gcd, false);
18890 },
18891 'DenseMatrix, number | BigNumber': function DenseMatrixNumberBigNumber(x, y) {
18892 return algorithm14(x, y, gcd, false);
18893 },
18894 'number | BigNumber, SparseMatrix': function numberBigNumberSparseMatrix(x, y) {
18895 return algorithm10(y, x, gcd, true);
18896 },
18897 'number | BigNumber, DenseMatrix': function numberBigNumberDenseMatrix(x, y) {
18898 return algorithm14(y, x, gcd, true);
18899 },
18900 'Array, number | BigNumber': function ArrayNumberBigNumber(x, y) {
18901 // use matrix implementation
18902 return algorithm14(matrix(x), y, gcd, false).valueOf();
18903 },
18904 'number | BigNumber, Array': function numberBigNumberArray(x, y) {
18905 // use matrix implementation
18906 return algorithm14(matrix(y), x, gcd, true).valueOf();
18907 },
18908 // TODO: need a smarter notation here
18909 'Array | Matrix | number | BigNumber, Array | Matrix | number | BigNumber, ...Array | Matrix | number | BigNumber': function ArrayMatrixNumberBigNumberArrayMatrixNumberBigNumberArrayMatrixNumberBigNumber(a, b, args) {
18910 var res = gcd(a, b);
18911
18912 for (var i = 0; i < args.length; i++) {
18913 res = gcd(res, args[i]);
18914 }
18915
18916 return res;
18917 }
18918 });
18919 return gcd;
18920 /**
18921 * Calculate gcd for BigNumbers
18922 * @param {BigNumber} a
18923 * @param {BigNumber} b
18924 * @returns {BigNumber} Returns greatest common denominator of a and b
18925 * @private
18926 */
18927
18928 function _gcdBigNumber(a, b) {
18929 if (!a.isInt() || !b.isInt()) {
18930 throw new Error('Parameters in function gcd must be integer numbers');
18931 } // https://en.wikipedia.org/wiki/Euclidean_algorithm
18932
18933
18934 var zero = new BigNumber(0);
18935
18936 while (!b.isZero()) {
18937 var r = a.mod(b);
18938 a = b;
18939 b = r;
18940 }
18941
18942 return a.lt(zero) ? a.neg() : a;
18943 }
18944});
18945// CONCATENATED MODULE: ./src/type/matrix/utils/algorithm02.js
18946
18947
18948var algorithm02_name = 'algorithm02';
18949var algorithm02_dependencies = ['typed', 'equalScalar'];
18950var createAlgorithm02 =
18951/* #__PURE__ */
18952Object(factory["a" /* factory */])(algorithm02_name, algorithm02_dependencies, function (_ref) {
18953 var typed = _ref.typed,
18954 equalScalar = _ref.equalScalar;
18955
18956 /**
18957 * Iterates over SparseMatrix nonzero items and invokes the callback function f(Dij, Sij).
18958 * Callback function invoked NNZ times (number of nonzero items in SparseMatrix).
18959 *
18960 *
18961 * ┌ f(Dij, Sij) ; S(i,j) !== 0
18962 * C(i,j) = ┤
18963 * └ 0 ; otherwise
18964 *
18965 *
18966 * @param {Matrix} denseMatrix The DenseMatrix instance (D)
18967 * @param {Matrix} sparseMatrix The SparseMatrix instance (S)
18968 * @param {Function} callback The f(Dij,Sij) operation to invoke, where Dij = DenseMatrix(i,j) and Sij = SparseMatrix(i,j)
18969 * @param {boolean} inverse A true value indicates callback should be invoked f(Sij,Dij)
18970 *
18971 * @return {Matrix} SparseMatrix (C)
18972 *
18973 * see https://github.com/josdejong/mathjs/pull/346#issuecomment-97477571
18974 */
18975 return function algorithm02(denseMatrix, sparseMatrix, callback, inverse) {
18976 // dense matrix arrays
18977 var adata = denseMatrix._data;
18978 var asize = denseMatrix._size;
18979 var adt = denseMatrix._datatype; // sparse matrix arrays
18980
18981 var bvalues = sparseMatrix._values;
18982 var bindex = sparseMatrix._index;
18983 var bptr = sparseMatrix._ptr;
18984 var bsize = sparseMatrix._size;
18985 var bdt = sparseMatrix._datatype; // validate dimensions
18986
18987 if (asize.length !== bsize.length) {
18988 throw new DimensionError["a" /* DimensionError */](asize.length, bsize.length);
18989 } // check rows & columns
18990
18991
18992 if (asize[0] !== bsize[0] || asize[1] !== bsize[1]) {
18993 throw new RangeError('Dimension mismatch. Matrix A (' + asize + ') must match Matrix B (' + bsize + ')');
18994 } // sparse matrix cannot be a Pattern matrix
18995
18996
18997 if (!bvalues) {
18998 throw new Error('Cannot perform operation on Dense Matrix and Pattern Sparse Matrix');
18999 } // rows & columns
19000
19001
19002 var rows = asize[0];
19003 var columns = asize[1]; // datatype
19004
19005 var dt; // equal signature to use
19006
19007 var eq = equalScalar; // zero value
19008
19009 var zero = 0; // callback signature to use
19010
19011 var cf = callback; // process data types
19012
19013 if (typeof adt === 'string' && adt === bdt) {
19014 // datatype
19015 dt = adt; // find signature that matches (dt, dt)
19016
19017 eq = typed.find(equalScalar, [dt, dt]); // convert 0 to the same datatype
19018
19019 zero = typed.convert(0, dt); // callback
19020
19021 cf = typed.find(callback, [dt, dt]);
19022 } // result (SparseMatrix)
19023
19024
19025 var cvalues = [];
19026 var cindex = [];
19027 var cptr = []; // loop columns in b
19028
19029 for (var j = 0; j < columns; j++) {
19030 // update cptr
19031 cptr[j] = cindex.length; // values in column j
19032
19033 for (var k0 = bptr[j], k1 = bptr[j + 1], k = k0; k < k1; k++) {
19034 // row
19035 var i = bindex[k]; // update C(i,j)
19036
19037 var cij = inverse ? cf(bvalues[k], adata[i][j]) : cf(adata[i][j], bvalues[k]); // check for nonzero
19038
19039 if (!eq(cij, zero)) {
19040 // push i & v
19041 cindex.push(i);
19042 cvalues.push(cij);
19043 }
19044 }
19045 } // update cptr
19046
19047
19048 cptr[columns] = cindex.length; // return sparse matrix
19049
19050 return sparseMatrix.createSparseMatrix({
19051 values: cvalues,
19052 index: cindex,
19053 ptr: cptr,
19054 size: [rows, columns],
19055 datatype: dt
19056 });
19057 };
19058});
19059// CONCATENATED MODULE: ./src/type/matrix/utils/algorithm06.js
19060
19061
19062
19063var algorithm06_name = 'algorithm06';
19064var algorithm06_dependencies = ['typed', 'equalScalar'];
19065var createAlgorithm06 =
19066/* #__PURE__ */
19067Object(factory["a" /* factory */])(algorithm06_name, algorithm06_dependencies, function (_ref) {
19068 var typed = _ref.typed,
19069 equalScalar = _ref.equalScalar;
19070
19071 /**
19072 * Iterates over SparseMatrix A and SparseMatrix B nonzero items and invokes the callback function f(Aij, Bij).
19073 * Callback function invoked (Anz U Bnz) times, where Anz and Bnz are the nonzero elements in both matrices.
19074 *
19075 *
19076 * ┌ f(Aij, Bij) ; A(i,j) !== 0 && B(i,j) !== 0
19077 * C(i,j) = ┤
19078 * └ 0 ; otherwise
19079 *
19080 *
19081 * @param {Matrix} a The SparseMatrix instance (A)
19082 * @param {Matrix} b The SparseMatrix instance (B)
19083 * @param {Function} callback The f(Aij,Bij) operation to invoke
19084 *
19085 * @return {Matrix} SparseMatrix (C)
19086 *
19087 * see https://github.com/josdejong/mathjs/pull/346#issuecomment-97620294
19088 */
19089 return function algorithm06(a, b, callback) {
19090 // sparse matrix arrays
19091 var avalues = a._values;
19092 var asize = a._size;
19093 var adt = a._datatype; // sparse matrix arrays
19094
19095 var bvalues = b._values;
19096 var bsize = b._size;
19097 var bdt = b._datatype; // validate dimensions
19098
19099 if (asize.length !== bsize.length) {
19100 throw new DimensionError["a" /* DimensionError */](asize.length, bsize.length);
19101 } // check rows & columns
19102
19103
19104 if (asize[0] !== bsize[0] || asize[1] !== bsize[1]) {
19105 throw new RangeError('Dimension mismatch. Matrix A (' + asize + ') must match Matrix B (' + bsize + ')');
19106 } // rows & columns
19107
19108
19109 var rows = asize[0];
19110 var columns = asize[1]; // datatype
19111
19112 var dt; // equal signature to use
19113
19114 var eq = equalScalar; // zero value
19115
19116 var zero = 0; // callback signature to use
19117
19118 var cf = callback; // process data types
19119
19120 if (typeof adt === 'string' && adt === bdt) {
19121 // datatype
19122 dt = adt; // find signature that matches (dt, dt)
19123
19124 eq = typed.find(equalScalar, [dt, dt]); // convert 0 to the same datatype
19125
19126 zero = typed.convert(0, dt); // callback
19127
19128 cf = typed.find(callback, [dt, dt]);
19129 } // result arrays
19130
19131
19132 var cvalues = avalues && bvalues ? [] : undefined;
19133 var cindex = [];
19134 var cptr = []; // matrix
19135
19136 var c = a.createSparseMatrix({
19137 values: cvalues,
19138 index: cindex,
19139 ptr: cptr,
19140 size: [rows, columns],
19141 datatype: dt
19142 }); // workspaces
19143
19144 var x = cvalues ? [] : undefined; // marks indicating we have a value in x for a given column
19145
19146 var w = []; // marks indicating value in a given row has been updated
19147
19148 var u = []; // loop columns
19149
19150 for (var j = 0; j < columns; j++) {
19151 // update cptr
19152 cptr[j] = cindex.length; // columns mark
19153
19154 var mark = j + 1; // scatter the values of A(:,j) into workspace
19155
19156 scatter(a, j, w, x, u, mark, c, cf); // scatter the values of B(:,j) into workspace
19157
19158 scatter(b, j, w, x, u, mark, c, cf); // check we need to process values (non pattern matrix)
19159
19160 if (x) {
19161 // initialize first index in j
19162 var k = cptr[j]; // loop index in j
19163
19164 while (k < cindex.length) {
19165 // row
19166 var i = cindex[k]; // check function was invoked on current row (Aij !=0 && Bij != 0)
19167
19168 if (u[i] === mark) {
19169 // value @ i
19170 var v = x[i]; // check for zero value
19171
19172 if (!eq(v, zero)) {
19173 // push value
19174 cvalues.push(v); // increment pointer
19175
19176 k++;
19177 } else {
19178 // remove value @ i, do not increment pointer
19179 cindex.splice(k, 1);
19180 }
19181 } else {
19182 // remove value @ i, do not increment pointer
19183 cindex.splice(k, 1);
19184 }
19185 }
19186 } else {
19187 // initialize first index in j
19188 var p = cptr[j]; // loop index in j
19189
19190 while (p < cindex.length) {
19191 // row
19192 var r = cindex[p]; // check function was invoked on current row (Aij !=0 && Bij != 0)
19193
19194 if (u[r] !== mark) {
19195 // remove value @ i, do not increment pointer
19196 cindex.splice(p, 1);
19197 } else {
19198 // increment pointer
19199 p++;
19200 }
19201 }
19202 }
19203 } // update cptr
19204
19205
19206 cptr[columns] = cindex.length; // return sparse matrix
19207
19208 return c;
19209 };
19210});
19211// CONCATENATED MODULE: ./src/type/matrix/utils/algorithm11.js
19212
19213var algorithm11_name = 'algorithm11';
19214var algorithm11_dependencies = ['typed', 'equalScalar'];
19215var createAlgorithm11 =
19216/* #__PURE__ */
19217Object(factory["a" /* factory */])(algorithm11_name, algorithm11_dependencies, function (_ref) {
19218 var typed = _ref.typed,
19219 equalScalar = _ref.equalScalar;
19220
19221 /**
19222 * Iterates over SparseMatrix S nonzero items and invokes the callback function f(Sij, b).
19223 * Callback function invoked NZ times (number of nonzero items in S).
19224 *
19225 *
19226 * ┌ f(Sij, b) ; S(i,j) !== 0
19227 * C(i,j) = ┤
19228 * └ 0 ; otherwise
19229 *
19230 *
19231 * @param {Matrix} s The SparseMatrix instance (S)
19232 * @param {Scalar} b The Scalar value
19233 * @param {Function} callback The f(Aij,b) operation to invoke
19234 * @param {boolean} inverse A true value indicates callback should be invoked f(b,Sij)
19235 *
19236 * @return {Matrix} SparseMatrix (C)
19237 *
19238 * https://github.com/josdejong/mathjs/pull/346#issuecomment-97626813
19239 */
19240 return function algorithm11(s, b, callback, inverse) {
19241 // sparse matrix arrays
19242 var avalues = s._values;
19243 var aindex = s._index;
19244 var aptr = s._ptr;
19245 var asize = s._size;
19246 var adt = s._datatype; // sparse matrix cannot be a Pattern matrix
19247
19248 if (!avalues) {
19249 throw new Error('Cannot perform operation on Pattern Sparse Matrix and Scalar value');
19250 } // rows & columns
19251
19252
19253 var rows = asize[0];
19254 var columns = asize[1]; // datatype
19255
19256 var dt; // equal signature to use
19257
19258 var eq = equalScalar; // zero value
19259
19260 var zero = 0; // callback signature to use
19261
19262 var cf = callback; // process data types
19263
19264 if (typeof adt === 'string') {
19265 // datatype
19266 dt = adt; // find signature that matches (dt, dt)
19267
19268 eq = typed.find(equalScalar, [dt, dt]); // convert 0 to the same datatype
19269
19270 zero = typed.convert(0, dt); // convert b to the same datatype
19271
19272 b = typed.convert(b, dt); // callback
19273
19274 cf = typed.find(callback, [dt, dt]);
19275 } // result arrays
19276
19277
19278 var cvalues = [];
19279 var cindex = [];
19280 var cptr = []; // matrix
19281
19282 var c = s.createSparseMatrix({
19283 values: cvalues,
19284 index: cindex,
19285 ptr: cptr,
19286 size: [rows, columns],
19287 datatype: dt
19288 }); // loop columns
19289
19290 for (var j = 0; j < columns; j++) {
19291 // initialize ptr
19292 cptr[j] = cindex.length; // values in j
19293
19294 for (var k0 = aptr[j], k1 = aptr[j + 1], k = k0; k < k1; k++) {
19295 // row
19296 var i = aindex[k]; // invoke callback
19297
19298 var v = inverse ? cf(b, avalues[k]) : cf(avalues[k], b); // check value is zero
19299
19300 if (!eq(v, zero)) {
19301 // push index & value
19302 cindex.push(i);
19303 cvalues.push(v);
19304 }
19305 }
19306 } // update ptr
19307
19308
19309 cptr[columns] = cindex.length; // return sparse matrix
19310
19311 return c;
19312 };
19313});
19314// CONCATENATED MODULE: ./src/function/arithmetic/lcm.js
19315
19316
19317
19318
19319
19320
19321
19322var lcm_name = 'lcm';
19323var lcm_dependencies = ['typed', 'matrix', 'equalScalar'];
19324var createLcm =
19325/* #__PURE__ */
19326Object(factory["a" /* factory */])(lcm_name, lcm_dependencies, function (_ref) {
19327 var typed = _ref.typed,
19328 matrix = _ref.matrix,
19329 equalScalar = _ref.equalScalar;
19330 var algorithm02 = createAlgorithm02({
19331 typed: typed,
19332 equalScalar: equalScalar
19333 });
19334 var algorithm06 = createAlgorithm06({
19335 typed: typed,
19336 equalScalar: equalScalar
19337 });
19338 var algorithm11 = createAlgorithm11({
19339 typed: typed,
19340 equalScalar: equalScalar
19341 });
19342 var algorithm13 = createAlgorithm13({
19343 typed: typed
19344 });
19345 var algorithm14 = createAlgorithm14({
19346 typed: typed
19347 });
19348 /**
19349 * Calculate the least common multiple for two or more values or arrays.
19350 *
19351 * lcm is defined as:
19352 *
19353 * lcm(a, b) = abs(a * b) / gcd(a, b)
19354 *
19355 * For matrices, the function is evaluated element wise.
19356 *
19357 * Syntax:
19358 *
19359 * math.lcm(a, b)
19360 * math.lcm(a, b, c, ...)
19361 *
19362 * Examples:
19363 *
19364 * math.lcm(4, 6) // returns 12
19365 * math.lcm(6, 21) // returns 42
19366 * math.lcm(6, 21, 5) // returns 210
19367 *
19368 * math.lcm([4, 6], [6, 21]) // returns [12, 42]
19369 *
19370 * See also:
19371 *
19372 * gcd, xgcd
19373 *
19374 * @param {... number | BigNumber | Array | Matrix} args Two or more integer numbers
19375 * @return {number | BigNumber | Array | Matrix} The least common multiple
19376 */
19377
19378 var lcm = typed(lcm_name, {
19379 'number, number': lcmNumber,
19380 'BigNumber, BigNumber': _lcmBigNumber,
19381 'Fraction, Fraction': function FractionFraction(x, y) {
19382 return x.lcm(y);
19383 },
19384 'SparseMatrix, SparseMatrix': function SparseMatrixSparseMatrix(x, y) {
19385 return algorithm06(x, y, lcm);
19386 },
19387 'SparseMatrix, DenseMatrix': function SparseMatrixDenseMatrix(x, y) {
19388 return algorithm02(y, x, lcm, true);
19389 },
19390 'DenseMatrix, SparseMatrix': function DenseMatrixSparseMatrix(x, y) {
19391 return algorithm02(x, y, lcm, false);
19392 },
19393 'DenseMatrix, DenseMatrix': function DenseMatrixDenseMatrix(x, y) {
19394 return algorithm13(x, y, lcm);
19395 },
19396 'Array, Array': function ArrayArray(x, y) {
19397 // use matrix implementation
19398 return lcm(matrix(x), matrix(y)).valueOf();
19399 },
19400 'Array, Matrix': function ArrayMatrix(x, y) {
19401 // use matrix implementation
19402 return lcm(matrix(x), y);
19403 },
19404 'Matrix, Array': function MatrixArray(x, y) {
19405 // use matrix implementation
19406 return lcm(x, matrix(y));
19407 },
19408 'SparseMatrix, number | BigNumber': function SparseMatrixNumberBigNumber(x, y) {
19409 return algorithm11(x, y, lcm, false);
19410 },
19411 'DenseMatrix, number | BigNumber': function DenseMatrixNumberBigNumber(x, y) {
19412 return algorithm14(x, y, lcm, false);
19413 },
19414 'number | BigNumber, SparseMatrix': function numberBigNumberSparseMatrix(x, y) {
19415 return algorithm11(y, x, lcm, true);
19416 },
19417 'number | BigNumber, DenseMatrix': function numberBigNumberDenseMatrix(x, y) {
19418 return algorithm14(y, x, lcm, true);
19419 },
19420 'Array, number | BigNumber': function ArrayNumberBigNumber(x, y) {
19421 // use matrix implementation
19422 return algorithm14(matrix(x), y, lcm, false).valueOf();
19423 },
19424 'number | BigNumber, Array': function numberBigNumberArray(x, y) {
19425 // use matrix implementation
19426 return algorithm14(matrix(y), x, lcm, true).valueOf();
19427 },
19428 // TODO: need a smarter notation here
19429 'Array | Matrix | number | BigNumber, Array | Matrix | number | BigNumber, ...Array | Matrix | number | BigNumber': function ArrayMatrixNumberBigNumberArrayMatrixNumberBigNumberArrayMatrixNumberBigNumber(a, b, args) {
19430 var res = lcm(a, b);
19431
19432 for (var i = 0; i < args.length; i++) {
19433 res = lcm(res, args[i]);
19434 }
19435
19436 return res;
19437 }
19438 });
19439 return lcm;
19440 /**
19441 * Calculate lcm for two BigNumbers
19442 * @param {BigNumber} a
19443 * @param {BigNumber} b
19444 * @returns {BigNumber} Returns the least common multiple of a and b
19445 * @private
19446 */
19447
19448 function _lcmBigNumber(a, b) {
19449 if (!a.isInt() || !b.isInt()) {
19450 throw new Error('Parameters in function lcm must be integer numbers');
19451 }
19452
19453 if (a.isZero()) {
19454 return a;
19455 }
19456
19457 if (b.isZero()) {
19458 return b;
19459 } // https://en.wikipedia.org/wiki/Euclidean_algorithm
19460 // evaluate lcm here inline to reduce overhead
19461
19462
19463 var prod = a.times(b);
19464
19465 while (!b.isZero()) {
19466 var t = b;
19467 b = a.mod(t);
19468 a = t;
19469 }
19470
19471 return prod.div(a).abs();
19472 }
19473});
19474// CONCATENATED MODULE: ./src/function/arithmetic/log10.js
19475
19476
19477
19478var log10_name = 'log10';
19479var log10_dependencies = ['typed', 'config', 'Complex'];
19480var createLog10 =
19481/* #__PURE__ */
19482Object(factory["a" /* factory */])(log10_name, log10_dependencies, function (_ref) {
19483 var typed = _ref.typed,
19484 config = _ref.config,
19485 _Complex = _ref.Complex;
19486
19487 /**
19488 * Calculate the 10-base logarithm of a value. This is the same as calculating `log(x, 10)`.
19489 *
19490 * For matrices, the function is evaluated element wise.
19491 *
19492 * Syntax:
19493 *
19494 * math.log10(x)
19495 *
19496 * Examples:
19497 *
19498 * math.log10(0.00001) // returns -5
19499 * math.log10(10000) // returns 4
19500 * math.log(10000) / math.log(10) // returns 4
19501 * math.pow(10, 4) // returns 10000
19502 *
19503 * See also:
19504 *
19505 * exp, log, log1p, log2
19506 *
19507 * @param {number | BigNumber | Complex | Array | Matrix} x
19508 * Value for which to calculate the logarithm.
19509 * @return {number | BigNumber | Complex | Array | Matrix}
19510 * Returns the 10-base logarithm of `x`
19511 */
19512 var log10 = typed(log10_name, {
19513 number: function number(x) {
19514 if (x >= 0 || config.predictable) {
19515 return log10Number(x);
19516 } else {
19517 // negative value -> complex value computation
19518 return new _Complex(x, 0).log().div(Math.LN10);
19519 }
19520 },
19521 Complex: function Complex(x) {
19522 return new _Complex(x).log().div(Math.LN10);
19523 },
19524 BigNumber: function BigNumber(x) {
19525 if (!x.isNegative() || config.predictable) {
19526 return x.log();
19527 } else {
19528 // downgrade to number, return Complex valued result
19529 return new _Complex(x.toNumber(), 0).log().div(Math.LN10);
19530 }
19531 },
19532 'Array | Matrix': function ArrayMatrix(x) {
19533 return deepMap(x, log10);
19534 }
19535 });
19536 return log10;
19537});
19538// CONCATENATED MODULE: ./src/function/arithmetic/log2.js
19539
19540
19541
19542var log2_name = 'log2';
19543var log2_dependencies = ['typed', 'config', 'Complex'];
19544var createLog2 =
19545/* #__PURE__ */
19546Object(factory["a" /* factory */])(log2_name, log2_dependencies, function (_ref) {
19547 var typed = _ref.typed,
19548 config = _ref.config,
19549 Complex = _ref.Complex;
19550
19551 /**
19552 * Calculate the 2-base of a value. This is the same as calculating `log(x, 2)`.
19553 *
19554 * For matrices, the function is evaluated element wise.
19555 *
19556 * Syntax:
19557 *
19558 * math.log2(x)
19559 *
19560 * Examples:
19561 *
19562 * math.log2(0.03125) // returns -5
19563 * math.log2(16) // returns 4
19564 * math.log2(16) / math.log2(2) // returns 4
19565 * math.pow(2, 4) // returns 16
19566 *
19567 * See also:
19568 *
19569 * exp, log, log1p, log10
19570 *
19571 * @param {number | BigNumber | Complex | Array | Matrix} x
19572 * Value for which to calculate the logarithm.
19573 * @return {number | BigNumber | Complex | Array | Matrix}
19574 * Returns the 2-base logarithm of `x`
19575 */
19576 var log2 = typed(log2_name, {
19577 number: function number(x) {
19578 if (x >= 0 || config.predictable) {
19579 return log2Number(x);
19580 } else {
19581 // negative value -> complex value computation
19582 return _log2Complex(new Complex(x, 0));
19583 }
19584 },
19585 Complex: _log2Complex,
19586 BigNumber: function BigNumber(x) {
19587 if (!x.isNegative() || config.predictable) {
19588 return x.log(2);
19589 } else {
19590 // downgrade to number, return Complex valued result
19591 return _log2Complex(new Complex(x.toNumber(), 0));
19592 }
19593 },
19594 'Array | Matrix': function ArrayMatrix(x) {
19595 return deepMap(x, log2);
19596 }
19597 });
19598 /**
19599 * Calculate log2 for a complex value
19600 * @param {Complex} x
19601 * @returns {Complex}
19602 * @private
19603 */
19604
19605 function _log2Complex(x) {
19606 var newX = Math.sqrt(x.re * x.re + x.im * x.im);
19607 return new Complex(Math.log2 ? Math.log2(newX) : Math.log(newX) / Math.LN2, Math.atan2(x.im, x.re) / Math.LN2);
19608 }
19609
19610 return log2;
19611});
19612// CONCATENATED MODULE: ./src/type/matrix/utils/algorithm03.js
19613
19614
19615var algorithm03_name = 'algorithm03';
19616var algorithm03_dependencies = ['typed'];
19617var createAlgorithm03 =
19618/* #__PURE__ */
19619Object(factory["a" /* factory */])(algorithm03_name, algorithm03_dependencies, function (_ref) {
19620 var typed = _ref.typed;
19621
19622 /**
19623 * Iterates over SparseMatrix items and invokes the callback function f(Dij, Sij).
19624 * Callback function invoked M*N times.
19625 *
19626 *
19627 * ┌ f(Dij, Sij) ; S(i,j) !== 0
19628 * C(i,j) = ┤
19629 * └ f(Dij, 0) ; otherwise
19630 *
19631 *
19632 * @param {Matrix} denseMatrix The DenseMatrix instance (D)
19633 * @param {Matrix} sparseMatrix The SparseMatrix instance (C)
19634 * @param {Function} callback The f(Dij,Sij) operation to invoke, where Dij = DenseMatrix(i,j) and Sij = SparseMatrix(i,j)
19635 * @param {boolean} inverse A true value indicates callback should be invoked f(Sij,Dij)
19636 *
19637 * @return {Matrix} DenseMatrix (C)
19638 *
19639 * see https://github.com/josdejong/mathjs/pull/346#issuecomment-97477571
19640 */
19641 return function algorithm03(denseMatrix, sparseMatrix, callback, inverse) {
19642 // dense matrix arrays
19643 var adata = denseMatrix._data;
19644 var asize = denseMatrix._size;
19645 var adt = denseMatrix._datatype; // sparse matrix arrays
19646
19647 var bvalues = sparseMatrix._values;
19648 var bindex = sparseMatrix._index;
19649 var bptr = sparseMatrix._ptr;
19650 var bsize = sparseMatrix._size;
19651 var bdt = sparseMatrix._datatype; // validate dimensions
19652
19653 if (asize.length !== bsize.length) {
19654 throw new DimensionError["a" /* DimensionError */](asize.length, bsize.length);
19655 } // check rows & columns
19656
19657
19658 if (asize[0] !== bsize[0] || asize[1] !== bsize[1]) {
19659 throw new RangeError('Dimension mismatch. Matrix A (' + asize + ') must match Matrix B (' + bsize + ')');
19660 } // sparse matrix cannot be a Pattern matrix
19661
19662
19663 if (!bvalues) {
19664 throw new Error('Cannot perform operation on Dense Matrix and Pattern Sparse Matrix');
19665 } // rows & columns
19666
19667
19668 var rows = asize[0];
19669 var columns = asize[1]; // datatype
19670
19671 var dt; // zero value
19672
19673 var zero = 0; // callback signature to use
19674
19675 var cf = callback; // process data types
19676
19677 if (typeof adt === 'string' && adt === bdt) {
19678 // datatype
19679 dt = adt; // convert 0 to the same datatype
19680
19681 zero = typed.convert(0, dt); // callback
19682
19683 cf = typed.find(callback, [dt, dt]);
19684 } // result (DenseMatrix)
19685
19686
19687 var cdata = []; // initialize dense matrix
19688
19689 for (var z = 0; z < rows; z++) {
19690 // initialize row
19691 cdata[z] = [];
19692 } // workspace
19693
19694
19695 var x = []; // marks indicating we have a value in x for a given column
19696
19697 var w = []; // loop columns in b
19698
19699 for (var j = 0; j < columns; j++) {
19700 // column mark
19701 var mark = j + 1; // values in column j
19702
19703 for (var k0 = bptr[j], k1 = bptr[j + 1], k = k0; k < k1; k++) {
19704 // row
19705 var i = bindex[k]; // update workspace
19706
19707 x[i] = inverse ? cf(bvalues[k], adata[i][j]) : cf(adata[i][j], bvalues[k]);
19708 w[i] = mark;
19709 } // process workspace
19710
19711
19712 for (var y = 0; y < rows; y++) {
19713 // check we have a calculated value for current row
19714 if (w[y] === mark) {
19715 // use calculated value
19716 cdata[y][j] = x[y];
19717 } else {
19718 // calculate value
19719 cdata[y][j] = inverse ? cf(zero, adata[y][j]) : cf(adata[y][j], zero);
19720 }
19721 }
19722 } // return dense matrix
19723
19724
19725 return denseMatrix.createDenseMatrix({
19726 data: cdata,
19727 size: [rows, columns],
19728 datatype: dt
19729 });
19730 };
19731});
19732// CONCATENATED MODULE: ./src/type/matrix/utils/algorithm05.js
19733
19734
19735var algorithm05_name = 'algorithm05';
19736var algorithm05_dependencies = ['typed', 'equalScalar'];
19737var createAlgorithm05 =
19738/* #__PURE__ */
19739Object(factory["a" /* factory */])(algorithm05_name, algorithm05_dependencies, function (_ref) {
19740 var typed = _ref.typed,
19741 equalScalar = _ref.equalScalar;
19742
19743 /**
19744 * Iterates over SparseMatrix A and SparseMatrix B nonzero items and invokes the callback function f(Aij, Bij).
19745 * Callback function invoked MAX(NNZA, NNZB) times
19746 *
19747 *
19748 * ┌ f(Aij, Bij) ; A(i,j) !== 0 || B(i,j) !== 0
19749 * C(i,j) = ┤
19750 * └ 0 ; otherwise
19751 *
19752 *
19753 * @param {Matrix} a The SparseMatrix instance (A)
19754 * @param {Matrix} b The SparseMatrix instance (B)
19755 * @param {Function} callback The f(Aij,Bij) operation to invoke
19756 *
19757 * @return {Matrix} SparseMatrix (C)
19758 *
19759 * see https://github.com/josdejong/mathjs/pull/346#issuecomment-97620294
19760 */
19761 return function algorithm05(a, b, callback) {
19762 // sparse matrix arrays
19763 var avalues = a._values;
19764 var aindex = a._index;
19765 var aptr = a._ptr;
19766 var asize = a._size;
19767 var adt = a._datatype; // sparse matrix arrays
19768
19769 var bvalues = b._values;
19770 var bindex = b._index;
19771 var bptr = b._ptr;
19772 var bsize = b._size;
19773 var bdt = b._datatype; // validate dimensions
19774
19775 if (asize.length !== bsize.length) {
19776 throw new DimensionError["a" /* DimensionError */](asize.length, bsize.length);
19777 } // check rows & columns
19778
19779
19780 if (asize[0] !== bsize[0] || asize[1] !== bsize[1]) {
19781 throw new RangeError('Dimension mismatch. Matrix A (' + asize + ') must match Matrix B (' + bsize + ')');
19782 } // rows & columns
19783
19784
19785 var rows = asize[0];
19786 var columns = asize[1]; // datatype
19787
19788 var dt; // equal signature to use
19789
19790 var eq = equalScalar; // zero value
19791
19792 var zero = 0; // callback signature to use
19793
19794 var cf = callback; // process data types
19795
19796 if (typeof adt === 'string' && adt === bdt) {
19797 // datatype
19798 dt = adt; // find signature that matches (dt, dt)
19799
19800 eq = typed.find(equalScalar, [dt, dt]); // convert 0 to the same datatype
19801
19802 zero = typed.convert(0, dt); // callback
19803
19804 cf = typed.find(callback, [dt, dt]);
19805 } // result arrays
19806
19807
19808 var cvalues = avalues && bvalues ? [] : undefined;
19809 var cindex = [];
19810 var cptr = []; // matrix
19811
19812 var c = a.createSparseMatrix({
19813 values: cvalues,
19814 index: cindex,
19815 ptr: cptr,
19816 size: [rows, columns],
19817 datatype: dt
19818 }); // workspaces
19819
19820 var xa = cvalues ? [] : undefined;
19821 var xb = cvalues ? [] : undefined; // marks indicating we have a value in x for a given column
19822
19823 var wa = [];
19824 var wb = []; // vars
19825
19826 var i, j, k, k1; // loop columns
19827
19828 for (j = 0; j < columns; j++) {
19829 // update cptr
19830 cptr[j] = cindex.length; // columns mark
19831
19832 var mark = j + 1; // loop values A(:,j)
19833
19834 for (k = aptr[j], k1 = aptr[j + 1]; k < k1; k++) {
19835 // row
19836 i = aindex[k]; // push index
19837
19838 cindex.push(i); // update workspace
19839
19840 wa[i] = mark; // check we need to process values
19841
19842 if (xa) {
19843 xa[i] = avalues[k];
19844 }
19845 } // loop values B(:,j)
19846
19847
19848 for (k = bptr[j], k1 = bptr[j + 1]; k < k1; k++) {
19849 // row
19850 i = bindex[k]; // check row existed in A
19851
19852 if (wa[i] !== mark) {
19853 // push index
19854 cindex.push(i);
19855 } // update workspace
19856
19857
19858 wb[i] = mark; // check we need to process values
19859
19860 if (xb) {
19861 xb[i] = bvalues[k];
19862 }
19863 } // check we need to process values (non pattern matrix)
19864
19865
19866 if (cvalues) {
19867 // initialize first index in j
19868 k = cptr[j]; // loop index in j
19869
19870 while (k < cindex.length) {
19871 // row
19872 i = cindex[k]; // marks
19873
19874 var wai = wa[i];
19875 var wbi = wb[i]; // check Aij or Bij are nonzero
19876
19877 if (wai === mark || wbi === mark) {
19878 // matrix values @ i,j
19879 var va = wai === mark ? xa[i] : zero;
19880 var vb = wbi === mark ? xb[i] : zero; // Cij
19881
19882 var vc = cf(va, vb); // check for zero
19883
19884 if (!eq(vc, zero)) {
19885 // push value
19886 cvalues.push(vc); // increment pointer
19887
19888 k++;
19889 } else {
19890 // remove value @ i, do not increment pointer
19891 cindex.splice(k, 1);
19892 }
19893 }
19894 }
19895 }
19896 } // update cptr
19897
19898
19899 cptr[columns] = cindex.length; // return sparse matrix
19900
19901 return c;
19902 };
19903});
19904// CONCATENATED MODULE: ./src/type/matrix/utils/algorithm12.js
19905
19906var algorithm12_name = 'algorithm12';
19907var algorithm12_dependencies = ['typed', 'DenseMatrix'];
19908var createAlgorithm12 =
19909/* #__PURE__ */
19910Object(factory["a" /* factory */])(algorithm12_name, algorithm12_dependencies, function (_ref) {
19911 var typed = _ref.typed,
19912 DenseMatrix = _ref.DenseMatrix;
19913
19914 /**
19915 * Iterates over SparseMatrix S nonzero items and invokes the callback function f(Sij, b).
19916 * Callback function invoked MxN times.
19917 *
19918 *
19919 * ┌ f(Sij, b) ; S(i,j) !== 0
19920 * C(i,j) = ┤
19921 * └ f(0, b) ; otherwise
19922 *
19923 *
19924 * @param {Matrix} s The SparseMatrix instance (S)
19925 * @param {Scalar} b The Scalar value
19926 * @param {Function} callback The f(Aij,b) operation to invoke
19927 * @param {boolean} inverse A true value indicates callback should be invoked f(b,Sij)
19928 *
19929 * @return {Matrix} DenseMatrix (C)
19930 *
19931 * https://github.com/josdejong/mathjs/pull/346#issuecomment-97626813
19932 */
19933 return function algorithm12(s, b, callback, inverse) {
19934 // sparse matrix arrays
19935 var avalues = s._values;
19936 var aindex = s._index;
19937 var aptr = s._ptr;
19938 var asize = s._size;
19939 var adt = s._datatype; // sparse matrix cannot be a Pattern matrix
19940
19941 if (!avalues) {
19942 throw new Error('Cannot perform operation on Pattern Sparse Matrix and Scalar value');
19943 } // rows & columns
19944
19945
19946 var rows = asize[0];
19947 var columns = asize[1]; // datatype
19948
19949 var dt; // callback signature to use
19950
19951 var cf = callback; // process data types
19952
19953 if (typeof adt === 'string') {
19954 // datatype
19955 dt = adt; // convert b to the same datatype
19956
19957 b = typed.convert(b, dt); // callback
19958
19959 cf = typed.find(callback, [dt, dt]);
19960 } // result arrays
19961
19962
19963 var cdata = []; // matrix
19964
19965 var c = new DenseMatrix({
19966 data: cdata,
19967 size: [rows, columns],
19968 datatype: dt
19969 }); // workspaces
19970
19971 var x = []; // marks indicating we have a value in x for a given column
19972
19973 var w = []; // loop columns
19974
19975 for (var j = 0; j < columns; j++) {
19976 // columns mark
19977 var mark = j + 1; // values in j
19978
19979 for (var k0 = aptr[j], k1 = aptr[j + 1], k = k0; k < k1; k++) {
19980 // row
19981 var r = aindex[k]; // update workspace
19982
19983 x[r] = avalues[k];
19984 w[r] = mark;
19985 } // loop rows
19986
19987
19988 for (var i = 0; i < rows; i++) {
19989 // initialize C on first column
19990 if (j === 0) {
19991 // create row array
19992 cdata[i] = [];
19993 } // check sparse matrix has a value @ i,j
19994
19995
19996 if (w[i] === mark) {
19997 // invoke callback, update C
19998 cdata[i][j] = inverse ? cf(b, x[i]) : cf(x[i], b);
19999 } else {
20000 // dense matrix value @ i, j
20001 cdata[i][j] = inverse ? cf(b, 0) : cf(0, b);
20002 }
20003 }
20004 } // return sparse matrix
20005
20006
20007 return c;
20008 };
20009});
20010// CONCATENATED MODULE: ./src/function/arithmetic/mod.js
20011
20012
20013
20014
20015
20016
20017
20018
20019
20020var mod_name = 'mod';
20021var mod_dependencies = ['typed', 'matrix', 'equalScalar', 'DenseMatrix'];
20022var createMod =
20023/* #__PURE__ */
20024Object(factory["a" /* factory */])(mod_name, mod_dependencies, function (_ref) {
20025 var typed = _ref.typed,
20026 matrix = _ref.matrix,
20027 equalScalar = _ref.equalScalar,
20028 DenseMatrix = _ref.DenseMatrix;
20029 var algorithm02 = createAlgorithm02({
20030 typed: typed,
20031 equalScalar: equalScalar
20032 });
20033 var algorithm03 = createAlgorithm03({
20034 typed: typed
20035 });
20036 var algorithm05 = createAlgorithm05({
20037 typed: typed,
20038 equalScalar: equalScalar
20039 });
20040 var algorithm11 = createAlgorithm11({
20041 typed: typed,
20042 equalScalar: equalScalar
20043 });
20044 var algorithm12 = createAlgorithm12({
20045 typed: typed,
20046 DenseMatrix: DenseMatrix
20047 });
20048 var algorithm13 = createAlgorithm13({
20049 typed: typed
20050 });
20051 var algorithm14 = createAlgorithm14({
20052 typed: typed
20053 });
20054 /**
20055 * Calculates the modulus, the remainder of an integer division.
20056 *
20057 * For matrices, the function is evaluated element wise.
20058 *
20059 * The modulus is defined as:
20060 *
20061 * x - y * floor(x / y)
20062 *
20063 * See https://en.wikipedia.org/wiki/Modulo_operation.
20064 *
20065 * Syntax:
20066 *
20067 * math.mod(x, y)
20068 *
20069 * Examples:
20070 *
20071 * math.mod(8, 3) // returns 2
20072 * math.mod(11, 2) // returns 1
20073 *
20074 * function isOdd(x) {
20075 * return math.mod(x, 2) != 0
20076 * }
20077 *
20078 * isOdd(2) // returns false
20079 * isOdd(3) // returns true
20080 *
20081 * See also:
20082 *
20083 * divide
20084 *
20085 * @param {number | BigNumber | Fraction | Array | Matrix} x Dividend
20086 * @param {number | BigNumber | Fraction | Array | Matrix} y Divisor
20087 * @return {number | BigNumber | Fraction | Array | Matrix} Returns the remainder of `x` divided by `y`.
20088 */
20089
20090 var mod = typed(mod_name, {
20091 'number, number': modNumber,
20092 'BigNumber, BigNumber': function BigNumberBigNumber(x, y) {
20093 return y.isZero() ? x : x.mod(y);
20094 },
20095 'Fraction, Fraction': function FractionFraction(x, y) {
20096 return x.mod(y);
20097 },
20098 'SparseMatrix, SparseMatrix': function SparseMatrixSparseMatrix(x, y) {
20099 return algorithm05(x, y, mod, false);
20100 },
20101 'SparseMatrix, DenseMatrix': function SparseMatrixDenseMatrix(x, y) {
20102 return algorithm02(y, x, mod, true);
20103 },
20104 'DenseMatrix, SparseMatrix': function DenseMatrixSparseMatrix(x, y) {
20105 return algorithm03(x, y, mod, false);
20106 },
20107 'DenseMatrix, DenseMatrix': function DenseMatrixDenseMatrix(x, y) {
20108 return algorithm13(x, y, mod);
20109 },
20110 'Array, Array': function ArrayArray(x, y) {
20111 // use matrix implementation
20112 return mod(matrix(x), matrix(y)).valueOf();
20113 },
20114 'Array, Matrix': function ArrayMatrix(x, y) {
20115 // use matrix implementation
20116 return mod(matrix(x), y);
20117 },
20118 'Matrix, Array': function MatrixArray(x, y) {
20119 // use matrix implementation
20120 return mod(x, matrix(y));
20121 },
20122 'SparseMatrix, any': function SparseMatrixAny(x, y) {
20123 return algorithm11(x, y, mod, false);
20124 },
20125 'DenseMatrix, any': function DenseMatrixAny(x, y) {
20126 return algorithm14(x, y, mod, false);
20127 },
20128 'any, SparseMatrix': function anySparseMatrix(x, y) {
20129 return algorithm12(y, x, mod, true);
20130 },
20131 'any, DenseMatrix': function anyDenseMatrix(x, y) {
20132 return algorithm14(y, x, mod, true);
20133 },
20134 'Array, any': function ArrayAny(x, y) {
20135 // use matrix implementation
20136 return algorithm14(matrix(x), y, mod, false).valueOf();
20137 },
20138 'any, Array': function anyArray(x, y) {
20139 // use matrix implementation
20140 return algorithm14(matrix(y), x, mod, true).valueOf();
20141 }
20142 });
20143 return mod;
20144});
20145// CONCATENATED MODULE: ./src/function/arithmetic/multiplyScalar.js
20146
20147
20148var multiplyScalar_name = 'multiplyScalar';
20149var multiplyScalar_dependencies = ['typed'];
20150var createMultiplyScalar =
20151/* #__PURE__ */
20152Object(factory["a" /* factory */])(multiplyScalar_name, multiplyScalar_dependencies, function (_ref) {
20153 var typed = _ref.typed;
20154
20155 /**
20156 * Multiply two scalar values, `x * y`.
20157 * This function is meant for internal use: it is used by the public function
20158 * `multiply`
20159 *
20160 * This function does not support collections (Array or Matrix).
20161 *
20162 * @param {number | BigNumber | Fraction | Complex | Unit} x First value to multiply
20163 * @param {number | BigNumber | Fraction | Complex} y Second value to multiply
20164 * @return {number | BigNumber | Fraction | Complex | Unit} Multiplication of `x` and `y`
20165 * @private
20166 */
20167 var multiplyScalar = typed('multiplyScalar', {
20168 'number, number': multiplyNumber,
20169 'Complex, Complex': function ComplexComplex(x, y) {
20170 return x.mul(y);
20171 },
20172 'BigNumber, BigNumber': function BigNumberBigNumber(x, y) {
20173 return x.times(y);
20174 },
20175 'Fraction, Fraction': function FractionFraction(x, y) {
20176 return x.mul(y);
20177 },
20178 'number | Fraction | BigNumber | Complex, Unit': function numberFractionBigNumberComplexUnit(x, y) {
20179 var res = y.clone();
20180 res.value = res.value === null ? res._normalize(x) : multiplyScalar(res.value, x);
20181 return res;
20182 },
20183 'Unit, number | Fraction | BigNumber | Complex': function UnitNumberFractionBigNumberComplex(x, y) {
20184 var res = x.clone();
20185 res.value = res.value === null ? res._normalize(y) : multiplyScalar(res.value, y);
20186 return res;
20187 },
20188 'Unit, Unit': function UnitUnit(x, y) {
20189 return x.multiply(y);
20190 }
20191 });
20192 return multiplyScalar;
20193});
20194// CONCATENATED MODULE: ./src/function/arithmetic/multiply.js
20195
20196
20197
20198
20199
20200
20201var multiply_name = 'multiply';
20202var multiply_dependencies = ['typed', 'matrix', 'addScalar', 'multiplyScalar', 'equalScalar'];
20203var createMultiply =
20204/* #__PURE__ */
20205Object(factory["a" /* factory */])(multiply_name, multiply_dependencies, function (_ref) {
20206 var typed = _ref.typed,
20207 matrix = _ref.matrix,
20208 addScalar = _ref.addScalar,
20209 multiplyScalar = _ref.multiplyScalar,
20210 equalScalar = _ref.equalScalar;
20211 var algorithm11 = createAlgorithm11({
20212 typed: typed,
20213 equalScalar: equalScalar
20214 });
20215 var algorithm14 = createAlgorithm14({
20216 typed: typed
20217 });
20218 /**
20219 * Multiply two or more values, `x * y`.
20220 * For matrices, the matrix product is calculated.
20221 *
20222 * Syntax:
20223 *
20224 * math.multiply(x, y)
20225 * math.multiply(x, y, z, ...)
20226 *
20227 * Examples:
20228 *
20229 * math.multiply(4, 5.2) // returns number 20.8
20230 * math.multiply(2, 3, 4) // returns number 24
20231 *
20232 * const a = math.complex(2, 3)
20233 * const b = math.complex(4, 1)
20234 * math.multiply(a, b) // returns Complex 5 + 14i
20235 *
20236 * const c = [[1, 2], [4, 3]]
20237 * const d = [[1, 2, 3], [3, -4, 7]]
20238 * math.multiply(c, d) // returns Array [[7, -6, 17], [13, -4, 33]]
20239 *
20240 * const e = math.unit('2.1 km')
20241 * math.multiply(3, e) // returns Unit 6.3 km
20242 *
20243 * See also:
20244 *
20245 * divide, prod, cross, dot
20246 *
20247 * @param {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} x First value to multiply
20248 * @param {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} y Second value to multiply
20249 * @return {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} Multiplication of `x` and `y`
20250 */
20251
20252 var multiply = typed(multiply_name, Object(utils_object["e" /* extend */])({
20253 // we extend the signatures of multiplyScalar with signatures dealing with matrices
20254 'Array, Array': function ArrayArray(x, y) {
20255 // check dimensions
20256 _validateMatrixDimensions(Object(utils_array["a" /* arraySize */])(x), Object(utils_array["a" /* arraySize */])(y)); // use dense matrix implementation
20257
20258
20259 var m = multiply(matrix(x), matrix(y)); // return array or scalar
20260
20261 return Object(is["v" /* isMatrix */])(m) ? m.valueOf() : m;
20262 },
20263 'Matrix, Matrix': function MatrixMatrix(x, y) {
20264 // dimensions
20265 var xsize = x.size();
20266 var ysize = y.size(); // check dimensions
20267
20268 _validateMatrixDimensions(xsize, ysize); // process dimensions
20269
20270
20271 if (xsize.length === 1) {
20272 // process y dimensions
20273 if (ysize.length === 1) {
20274 // Vector * Vector
20275 return _multiplyVectorVector(x, y, xsize[0]);
20276 } // Vector * Matrix
20277
20278
20279 return _multiplyVectorMatrix(x, y);
20280 } // process y dimensions
20281
20282
20283 if (ysize.length === 1) {
20284 // Matrix * Vector
20285 return _multiplyMatrixVector(x, y);
20286 } // Matrix * Matrix
20287
20288
20289 return _multiplyMatrixMatrix(x, y);
20290 },
20291 'Matrix, Array': function MatrixArray(x, y) {
20292 // use Matrix * Matrix implementation
20293 return multiply(x, matrix(y));
20294 },
20295 'Array, Matrix': function ArrayMatrix(x, y) {
20296 // use Matrix * Matrix implementation
20297 return multiply(matrix(x, y.storage()), y);
20298 },
20299 'SparseMatrix, any': function SparseMatrixAny(x, y) {
20300 return algorithm11(x, y, multiplyScalar, false);
20301 },
20302 'DenseMatrix, any': function DenseMatrixAny(x, y) {
20303 return algorithm14(x, y, multiplyScalar, false);
20304 },
20305 'any, SparseMatrix': function anySparseMatrix(x, y) {
20306 return algorithm11(y, x, multiplyScalar, true);
20307 },
20308 'any, DenseMatrix': function anyDenseMatrix(x, y) {
20309 return algorithm14(y, x, multiplyScalar, true);
20310 },
20311 'Array, any': function ArrayAny(x, y) {
20312 // use matrix implementation
20313 return algorithm14(matrix(x), y, multiplyScalar, false).valueOf();
20314 },
20315 'any, Array': function anyArray(x, y) {
20316 // use matrix implementation
20317 return algorithm14(matrix(y), x, multiplyScalar, true).valueOf();
20318 },
20319 'any, any': multiplyScalar,
20320 'any, any, ...any': function anyAnyAny(x, y, rest) {
20321 var result = multiply(x, y);
20322
20323 for (var i = 0; i < rest.length; i++) {
20324 result = multiply(result, rest[i]);
20325 }
20326
20327 return result;
20328 }
20329 }, multiplyScalar.signatures));
20330
20331 function _validateMatrixDimensions(size1, size2) {
20332 // check left operand dimensions
20333 switch (size1.length) {
20334 case 1:
20335 // check size2
20336 switch (size2.length) {
20337 case 1:
20338 // Vector x Vector
20339 if (size1[0] !== size2[0]) {
20340 // throw error
20341 throw new RangeError('Dimension mismatch in multiplication. Vectors must have the same length');
20342 }
20343
20344 break;
20345
20346 case 2:
20347 // Vector x Matrix
20348 if (size1[0] !== size2[0]) {
20349 // throw error
20350 throw new RangeError('Dimension mismatch in multiplication. Vector length (' + size1[0] + ') must match Matrix rows (' + size2[0] + ')');
20351 }
20352
20353 break;
20354
20355 default:
20356 throw new Error('Can only multiply a 1 or 2 dimensional matrix (Matrix B has ' + size2.length + ' dimensions)');
20357 }
20358
20359 break;
20360
20361 case 2:
20362 // check size2
20363 switch (size2.length) {
20364 case 1:
20365 // Matrix x Vector
20366 if (size1[1] !== size2[0]) {
20367 // throw error
20368 throw new RangeError('Dimension mismatch in multiplication. Matrix columns (' + size1[1] + ') must match Vector length (' + size2[0] + ')');
20369 }
20370
20371 break;
20372
20373 case 2:
20374 // Matrix x Matrix
20375 if (size1[1] !== size2[0]) {
20376 // throw error
20377 throw new RangeError('Dimension mismatch in multiplication. Matrix A columns (' + size1[1] + ') must match Matrix B rows (' + size2[0] + ')');
20378 }
20379
20380 break;
20381
20382 default:
20383 throw new Error('Can only multiply a 1 or 2 dimensional matrix (Matrix B has ' + size2.length + ' dimensions)');
20384 }
20385
20386 break;
20387
20388 default:
20389 throw new Error('Can only multiply a 1 or 2 dimensional matrix (Matrix A has ' + size1.length + ' dimensions)');
20390 }
20391 }
20392 /**
20393 * C = A * B
20394 *
20395 * @param {Matrix} a Dense Vector (N)
20396 * @param {Matrix} b Dense Vector (N)
20397 *
20398 * @return {number} Scalar value
20399 */
20400
20401
20402 function _multiplyVectorVector(a, b, n) {
20403 // check empty vector
20404 if (n === 0) {
20405 throw new Error('Cannot multiply two empty vectors');
20406 } // a dense
20407
20408
20409 var adata = a._data;
20410 var adt = a._datatype; // b dense
20411
20412 var bdata = b._data;
20413 var bdt = b._datatype; // datatype
20414
20415 var dt; // addScalar signature to use
20416
20417 var af = addScalar; // multiplyScalar signature to use
20418
20419 var mf = multiplyScalar; // process data types
20420
20421 if (adt && bdt && adt === bdt && typeof adt === 'string') {
20422 // datatype
20423 dt = adt; // find signatures that matches (dt, dt)
20424
20425 af = typed.find(addScalar, [dt, dt]);
20426 mf = typed.find(multiplyScalar, [dt, dt]);
20427 } // result (do not initialize it with zero)
20428
20429
20430 var c = mf(adata[0], bdata[0]); // loop data
20431
20432 for (var i = 1; i < n; i++) {
20433 // multiply and accumulate
20434 c = af(c, mf(adata[i], bdata[i]));
20435 }
20436
20437 return c;
20438 }
20439 /**
20440 * C = A * B
20441 *
20442 * @param {Matrix} a Dense Vector (M)
20443 * @param {Matrix} b Matrix (MxN)
20444 *
20445 * @return {Matrix} Dense Vector (N)
20446 */
20447
20448
20449 function _multiplyVectorMatrix(a, b) {
20450 // process storage
20451 if (b.storage() !== 'dense') {
20452 throw new Error('Support for SparseMatrix not implemented');
20453 }
20454
20455 return _multiplyVectorDenseMatrix(a, b);
20456 }
20457 /**
20458 * C = A * B
20459 *
20460 * @param {Matrix} a Dense Vector (M)
20461 * @param {Matrix} b Dense Matrix (MxN)
20462 *
20463 * @return {Matrix} Dense Vector (N)
20464 */
20465
20466
20467 function _multiplyVectorDenseMatrix(a, b) {
20468 // a dense
20469 var adata = a._data;
20470 var asize = a._size;
20471 var adt = a._datatype; // b dense
20472
20473 var bdata = b._data;
20474 var bsize = b._size;
20475 var bdt = b._datatype; // rows & columns
20476
20477 var alength = asize[0];
20478 var bcolumns = bsize[1]; // datatype
20479
20480 var dt; // addScalar signature to use
20481
20482 var af = addScalar; // multiplyScalar signature to use
20483
20484 var mf = multiplyScalar; // process data types
20485
20486 if (adt && bdt && adt === bdt && typeof adt === 'string') {
20487 // datatype
20488 dt = adt; // find signatures that matches (dt, dt)
20489
20490 af = typed.find(addScalar, [dt, dt]);
20491 mf = typed.find(multiplyScalar, [dt, dt]);
20492 } // result
20493
20494
20495 var c = []; // loop matrix columns
20496
20497 for (var j = 0; j < bcolumns; j++) {
20498 // sum (do not initialize it with zero)
20499 var sum = mf(adata[0], bdata[0][j]); // loop vector
20500
20501 for (var i = 1; i < alength; i++) {
20502 // multiply & accumulate
20503 sum = af(sum, mf(adata[i], bdata[i][j]));
20504 }
20505
20506 c[j] = sum;
20507 } // return matrix
20508
20509
20510 return a.createDenseMatrix({
20511 data: c,
20512 size: [bcolumns],
20513 datatype: dt
20514 });
20515 }
20516 /**
20517 * C = A * B
20518 *
20519 * @param {Matrix} a Matrix (MxN)
20520 * @param {Matrix} b Dense Vector (N)
20521 *
20522 * @return {Matrix} Dense Vector (M)
20523 */
20524
20525
20526 var _multiplyMatrixVector = typed('_multiplyMatrixVector', {
20527 'DenseMatrix, any': _multiplyDenseMatrixVector,
20528 'SparseMatrix, any': _multiplySparseMatrixVector
20529 });
20530 /**
20531 * C = A * B
20532 *
20533 * @param {Matrix} a Matrix (MxN)
20534 * @param {Matrix} b Matrix (NxC)
20535 *
20536 * @return {Matrix} Matrix (MxC)
20537 */
20538
20539
20540 var _multiplyMatrixMatrix = typed('_multiplyMatrixMatrix', {
20541 'DenseMatrix, DenseMatrix': _multiplyDenseMatrixDenseMatrix,
20542 'DenseMatrix, SparseMatrix': _multiplyDenseMatrixSparseMatrix,
20543 'SparseMatrix, DenseMatrix': _multiplySparseMatrixDenseMatrix,
20544 'SparseMatrix, SparseMatrix': _multiplySparseMatrixSparseMatrix
20545 });
20546 /**
20547 * C = A * B
20548 *
20549 * @param {Matrix} a DenseMatrix (MxN)
20550 * @param {Matrix} b Dense Vector (N)
20551 *
20552 * @return {Matrix} Dense Vector (M)
20553 */
20554
20555
20556 function _multiplyDenseMatrixVector(a, b) {
20557 // a dense
20558 var adata = a._data;
20559 var asize = a._size;
20560 var adt = a._datatype; // b dense
20561
20562 var bdata = b._data;
20563 var bdt = b._datatype; // rows & columns
20564
20565 var arows = asize[0];
20566 var acolumns = asize[1]; // datatype
20567
20568 var dt; // addScalar signature to use
20569
20570 var af = addScalar; // multiplyScalar signature to use
20571
20572 var mf = multiplyScalar; // process data types
20573
20574 if (adt && bdt && adt === bdt && typeof adt === 'string') {
20575 // datatype
20576 dt = adt; // find signatures that matches (dt, dt)
20577
20578 af = typed.find(addScalar, [dt, dt]);
20579 mf = typed.find(multiplyScalar, [dt, dt]);
20580 } // result
20581
20582
20583 var c = []; // loop matrix a rows
20584
20585 for (var i = 0; i < arows; i++) {
20586 // current row
20587 var row = adata[i]; // sum (do not initialize it with zero)
20588
20589 var sum = mf(row[0], bdata[0]); // loop matrix a columns
20590
20591 for (var j = 1; j < acolumns; j++) {
20592 // multiply & accumulate
20593 sum = af(sum, mf(row[j], bdata[j]));
20594 }
20595
20596 c[i] = sum;
20597 } // return matrix
20598
20599
20600 return a.createDenseMatrix({
20601 data: c,
20602 size: [arows],
20603 datatype: dt
20604 });
20605 }
20606 /**
20607 * C = A * B
20608 *
20609 * @param {Matrix} a DenseMatrix (MxN)
20610 * @param {Matrix} b DenseMatrix (NxC)
20611 *
20612 * @return {Matrix} DenseMatrix (MxC)
20613 */
20614
20615
20616 function _multiplyDenseMatrixDenseMatrix(a, b) {
20617 // a dense
20618 var adata = a._data;
20619 var asize = a._size;
20620 var adt = a._datatype; // b dense
20621
20622 var bdata = b._data;
20623 var bsize = b._size;
20624 var bdt = b._datatype; // rows & columns
20625
20626 var arows = asize[0];
20627 var acolumns = asize[1];
20628 var bcolumns = bsize[1]; // datatype
20629
20630 var dt; // addScalar signature to use
20631
20632 var af = addScalar; // multiplyScalar signature to use
20633
20634 var mf = multiplyScalar; // process data types
20635
20636 if (adt && bdt && adt === bdt && typeof adt === 'string') {
20637 // datatype
20638 dt = adt; // find signatures that matches (dt, dt)
20639
20640 af = typed.find(addScalar, [dt, dt]);
20641 mf = typed.find(multiplyScalar, [dt, dt]);
20642 } // result
20643
20644
20645 var c = []; // loop matrix a rows
20646
20647 for (var i = 0; i < arows; i++) {
20648 // current row
20649 var row = adata[i]; // initialize row array
20650
20651 c[i] = []; // loop matrix b columns
20652
20653 for (var j = 0; j < bcolumns; j++) {
20654 // sum (avoid initializing sum to zero)
20655 var sum = mf(row[0], bdata[0][j]); // loop matrix a columns
20656
20657 for (var x = 1; x < acolumns; x++) {
20658 // multiply & accumulate
20659 sum = af(sum, mf(row[x], bdata[x][j]));
20660 }
20661
20662 c[i][j] = sum;
20663 }
20664 } // return matrix
20665
20666
20667 return a.createDenseMatrix({
20668 data: c,
20669 size: [arows, bcolumns],
20670 datatype: dt
20671 });
20672 }
20673 /**
20674 * C = A * B
20675 *
20676 * @param {Matrix} a DenseMatrix (MxN)
20677 * @param {Matrix} b SparseMatrix (NxC)
20678 *
20679 * @return {Matrix} SparseMatrix (MxC)
20680 */
20681
20682
20683 function _multiplyDenseMatrixSparseMatrix(a, b) {
20684 // a dense
20685 var adata = a._data;
20686 var asize = a._size;
20687 var adt = a._datatype; // b sparse
20688
20689 var bvalues = b._values;
20690 var bindex = b._index;
20691 var bptr = b._ptr;
20692 var bsize = b._size;
20693 var bdt = b._datatype; // validate b matrix
20694
20695 if (!bvalues) {
20696 throw new Error('Cannot multiply Dense Matrix times Pattern only Matrix');
20697 } // rows & columns
20698
20699
20700 var arows = asize[0];
20701 var bcolumns = bsize[1]; // datatype
20702
20703 var dt; // addScalar signature to use
20704
20705 var af = addScalar; // multiplyScalar signature to use
20706
20707 var mf = multiplyScalar; // equalScalar signature to use
20708
20709 var eq = equalScalar; // zero value
20710
20711 var zero = 0; // process data types
20712
20713 if (adt && bdt && adt === bdt && typeof adt === 'string') {
20714 // datatype
20715 dt = adt; // find signatures that matches (dt, dt)
20716
20717 af = typed.find(addScalar, [dt, dt]);
20718 mf = typed.find(multiplyScalar, [dt, dt]);
20719 eq = typed.find(equalScalar, [dt, dt]); // convert 0 to the same datatype
20720
20721 zero = typed.convert(0, dt);
20722 } // result
20723
20724
20725 var cvalues = [];
20726 var cindex = [];
20727 var cptr = []; // c matrix
20728
20729 var c = b.createSparseMatrix({
20730 values: cvalues,
20731 index: cindex,
20732 ptr: cptr,
20733 size: [arows, bcolumns],
20734 datatype: dt
20735 }); // loop b columns
20736
20737 for (var jb = 0; jb < bcolumns; jb++) {
20738 // update ptr
20739 cptr[jb] = cindex.length; // indeces in column jb
20740
20741 var kb0 = bptr[jb];
20742 var kb1 = bptr[jb + 1]; // do not process column jb if no data exists
20743
20744 if (kb1 > kb0) {
20745 // last row mark processed
20746 var last = 0; // loop a rows
20747
20748 for (var i = 0; i < arows; i++) {
20749 // column mark
20750 var mark = i + 1; // C[i, jb]
20751
20752 var cij = void 0; // values in b column j
20753
20754 for (var kb = kb0; kb < kb1; kb++) {
20755 // row
20756 var ib = bindex[kb]; // check value has been initialized
20757
20758 if (last !== mark) {
20759 // first value in column jb
20760 cij = mf(adata[i][ib], bvalues[kb]); // update mark
20761
20762 last = mark;
20763 } else {
20764 // accumulate value
20765 cij = af(cij, mf(adata[i][ib], bvalues[kb]));
20766 }
20767 } // check column has been processed and value != 0
20768
20769
20770 if (last === mark && !eq(cij, zero)) {
20771 // push row & value
20772 cindex.push(i);
20773 cvalues.push(cij);
20774 }
20775 }
20776 }
20777 } // update ptr
20778
20779
20780 cptr[bcolumns] = cindex.length; // return sparse matrix
20781
20782 return c;
20783 }
20784 /**
20785 * C = A * B
20786 *
20787 * @param {Matrix} a SparseMatrix (MxN)
20788 * @param {Matrix} b Dense Vector (N)
20789 *
20790 * @return {Matrix} SparseMatrix (M, 1)
20791 */
20792
20793
20794 function _multiplySparseMatrixVector(a, b) {
20795 // a sparse
20796 var avalues = a._values;
20797 var aindex = a._index;
20798 var aptr = a._ptr;
20799 var adt = a._datatype; // validate a matrix
20800
20801 if (!avalues) {
20802 throw new Error('Cannot multiply Pattern only Matrix times Dense Matrix');
20803 } // b dense
20804
20805
20806 var bdata = b._data;
20807 var bdt = b._datatype; // rows & columns
20808
20809 var arows = a._size[0];
20810 var brows = b._size[0]; // result
20811
20812 var cvalues = [];
20813 var cindex = [];
20814 var cptr = []; // datatype
20815
20816 var dt; // addScalar signature to use
20817
20818 var af = addScalar; // multiplyScalar signature to use
20819
20820 var mf = multiplyScalar; // equalScalar signature to use
20821
20822 var eq = equalScalar; // zero value
20823
20824 var zero = 0; // process data types
20825
20826 if (adt && bdt && adt === bdt && typeof adt === 'string') {
20827 // datatype
20828 dt = adt; // find signatures that matches (dt, dt)
20829
20830 af = typed.find(addScalar, [dt, dt]);
20831 mf = typed.find(multiplyScalar, [dt, dt]);
20832 eq = typed.find(equalScalar, [dt, dt]); // convert 0 to the same datatype
20833
20834 zero = typed.convert(0, dt);
20835 } // workspace
20836
20837
20838 var x = []; // vector with marks indicating a value x[i] exists in a given column
20839
20840 var w = []; // update ptr
20841
20842 cptr[0] = 0; // rows in b
20843
20844 for (var ib = 0; ib < brows; ib++) {
20845 // b[ib]
20846 var vbi = bdata[ib]; // check b[ib] != 0, avoid loops
20847
20848 if (!eq(vbi, zero)) {
20849 // A values & index in ib column
20850 for (var ka0 = aptr[ib], ka1 = aptr[ib + 1], ka = ka0; ka < ka1; ka++) {
20851 // a row
20852 var ia = aindex[ka]; // check value exists in current j
20853
20854 if (!w[ia]) {
20855 // ia is new entry in j
20856 w[ia] = true; // add i to pattern of C
20857
20858 cindex.push(ia); // x(ia) = A
20859
20860 x[ia] = mf(vbi, avalues[ka]);
20861 } else {
20862 // i exists in C already
20863 x[ia] = af(x[ia], mf(vbi, avalues[ka]));
20864 }
20865 }
20866 }
20867 } // copy values from x to column jb of c
20868
20869
20870 for (var p1 = cindex.length, p = 0; p < p1; p++) {
20871 // row
20872 var ic = cindex[p]; // copy value
20873
20874 cvalues[p] = x[ic];
20875 } // update ptr
20876
20877
20878 cptr[1] = cindex.length; // return sparse matrix
20879
20880 return a.createSparseMatrix({
20881 values: cvalues,
20882 index: cindex,
20883 ptr: cptr,
20884 size: [arows, 1],
20885 datatype: dt
20886 });
20887 }
20888 /**
20889 * C = A * B
20890 *
20891 * @param {Matrix} a SparseMatrix (MxN)
20892 * @param {Matrix} b DenseMatrix (NxC)
20893 *
20894 * @return {Matrix} SparseMatrix (MxC)
20895 */
20896
20897
20898 function _multiplySparseMatrixDenseMatrix(a, b) {
20899 // a sparse
20900 var avalues = a._values;
20901 var aindex = a._index;
20902 var aptr = a._ptr;
20903 var adt = a._datatype; // validate a matrix
20904
20905 if (!avalues) {
20906 throw new Error('Cannot multiply Pattern only Matrix times Dense Matrix');
20907 } // b dense
20908
20909
20910 var bdata = b._data;
20911 var bdt = b._datatype; // rows & columns
20912
20913 var arows = a._size[0];
20914 var brows = b._size[0];
20915 var bcolumns = b._size[1]; // datatype
20916
20917 var dt; // addScalar signature to use
20918
20919 var af = addScalar; // multiplyScalar signature to use
20920
20921 var mf = multiplyScalar; // equalScalar signature to use
20922
20923 var eq = equalScalar; // zero value
20924
20925 var zero = 0; // process data types
20926
20927 if (adt && bdt && adt === bdt && typeof adt === 'string') {
20928 // datatype
20929 dt = adt; // find signatures that matches (dt, dt)
20930
20931 af = typed.find(addScalar, [dt, dt]);
20932 mf = typed.find(multiplyScalar, [dt, dt]);
20933 eq = typed.find(equalScalar, [dt, dt]); // convert 0 to the same datatype
20934
20935 zero = typed.convert(0, dt);
20936 } // result
20937
20938
20939 var cvalues = [];
20940 var cindex = [];
20941 var cptr = []; // c matrix
20942
20943 var c = a.createSparseMatrix({
20944 values: cvalues,
20945 index: cindex,
20946 ptr: cptr,
20947 size: [arows, bcolumns],
20948 datatype: dt
20949 }); // workspace
20950
20951 var x = []; // vector with marks indicating a value x[i] exists in a given column
20952
20953 var w = []; // loop b columns
20954
20955 for (var jb = 0; jb < bcolumns; jb++) {
20956 // update ptr
20957 cptr[jb] = cindex.length; // mark in workspace for current column
20958
20959 var mark = jb + 1; // rows in jb
20960
20961 for (var ib = 0; ib < brows; ib++) {
20962 // b[ib, jb]
20963 var vbij = bdata[ib][jb]; // check b[ib, jb] != 0, avoid loops
20964
20965 if (!eq(vbij, zero)) {
20966 // A values & index in ib column
20967 for (var ka0 = aptr[ib], ka1 = aptr[ib + 1], ka = ka0; ka < ka1; ka++) {
20968 // a row
20969 var ia = aindex[ka]; // check value exists in current j
20970
20971 if (w[ia] !== mark) {
20972 // ia is new entry in j
20973 w[ia] = mark; // add i to pattern of C
20974
20975 cindex.push(ia); // x(ia) = A
20976
20977 x[ia] = mf(vbij, avalues[ka]);
20978 } else {
20979 // i exists in C already
20980 x[ia] = af(x[ia], mf(vbij, avalues[ka]));
20981 }
20982 }
20983 }
20984 } // copy values from x to column jb of c
20985
20986
20987 for (var p0 = cptr[jb], p1 = cindex.length, p = p0; p < p1; p++) {
20988 // row
20989 var ic = cindex[p]; // copy value
20990
20991 cvalues[p] = x[ic];
20992 }
20993 } // update ptr
20994
20995
20996 cptr[bcolumns] = cindex.length; // return sparse matrix
20997
20998 return c;
20999 }
21000 /**
21001 * C = A * B
21002 *
21003 * @param {Matrix} a SparseMatrix (MxN)
21004 * @param {Matrix} b SparseMatrix (NxC)
21005 *
21006 * @return {Matrix} SparseMatrix (MxC)
21007 */
21008
21009
21010 function _multiplySparseMatrixSparseMatrix(a, b) {
21011 // a sparse
21012 var avalues = a._values;
21013 var aindex = a._index;
21014 var aptr = a._ptr;
21015 var adt = a._datatype; // b sparse
21016
21017 var bvalues = b._values;
21018 var bindex = b._index;
21019 var bptr = b._ptr;
21020 var bdt = b._datatype; // rows & columns
21021
21022 var arows = a._size[0];
21023 var bcolumns = b._size[1]; // flag indicating both matrices (a & b) contain data
21024
21025 var values = avalues && bvalues; // datatype
21026
21027 var dt; // addScalar signature to use
21028
21029 var af = addScalar; // multiplyScalar signature to use
21030
21031 var mf = multiplyScalar; // process data types
21032
21033 if (adt && bdt && adt === bdt && typeof adt === 'string') {
21034 // datatype
21035 dt = adt; // find signatures that matches (dt, dt)
21036
21037 af = typed.find(addScalar, [dt, dt]);
21038 mf = typed.find(multiplyScalar, [dt, dt]);
21039 } // result
21040
21041
21042 var cvalues = values ? [] : undefined;
21043 var cindex = [];
21044 var cptr = []; // c matrix
21045
21046 var c = a.createSparseMatrix({
21047 values: cvalues,
21048 index: cindex,
21049 ptr: cptr,
21050 size: [arows, bcolumns],
21051 datatype: dt
21052 }); // workspace
21053
21054 var x = values ? [] : undefined; // vector with marks indicating a value x[i] exists in a given column
21055
21056 var w = []; // variables
21057
21058 var ka, ka0, ka1, kb, kb0, kb1, ia, ib; // loop b columns
21059
21060 for (var jb = 0; jb < bcolumns; jb++) {
21061 // update ptr
21062 cptr[jb] = cindex.length; // mark in workspace for current column
21063
21064 var mark = jb + 1; // B values & index in j
21065
21066 for (kb0 = bptr[jb], kb1 = bptr[jb + 1], kb = kb0; kb < kb1; kb++) {
21067 // b row
21068 ib = bindex[kb]; // check we need to process values
21069
21070 if (values) {
21071 // loop values in a[:,ib]
21072 for (ka0 = aptr[ib], ka1 = aptr[ib + 1], ka = ka0; ka < ka1; ka++) {
21073 // row
21074 ia = aindex[ka]; // check value exists in current j
21075
21076 if (w[ia] !== mark) {
21077 // ia is new entry in j
21078 w[ia] = mark; // add i to pattern of C
21079
21080 cindex.push(ia); // x(ia) = A
21081
21082 x[ia] = mf(bvalues[kb], avalues[ka]);
21083 } else {
21084 // i exists in C already
21085 x[ia] = af(x[ia], mf(bvalues[kb], avalues[ka]));
21086 }
21087 }
21088 } else {
21089 // loop values in a[:,ib]
21090 for (ka0 = aptr[ib], ka1 = aptr[ib + 1], ka = ka0; ka < ka1; ka++) {
21091 // row
21092 ia = aindex[ka]; // check value exists in current j
21093
21094 if (w[ia] !== mark) {
21095 // ia is new entry in j
21096 w[ia] = mark; // add i to pattern of C
21097
21098 cindex.push(ia);
21099 }
21100 }
21101 }
21102 } // check we need to process matrix values (pattern matrix)
21103
21104
21105 if (values) {
21106 // copy values from x to column jb of c
21107 for (var p0 = cptr[jb], p1 = cindex.length, p = p0; p < p1; p++) {
21108 // row
21109 var ic = cindex[p]; // copy value
21110
21111 cvalues[p] = x[ic];
21112 }
21113 }
21114 } // update ptr
21115
21116
21117 cptr[bcolumns] = cindex.length; // return sparse matrix
21118
21119 return c;
21120 }
21121
21122 return multiply;
21123});
21124// CONCATENATED MODULE: ./src/function/arithmetic/nthRoot.js
21125
21126
21127
21128
21129
21130
21131
21132
21133var nthRoot_name = 'nthRoot';
21134var nthRoot_dependencies = ['typed', 'matrix', 'equalScalar', 'BigNumber'];
21135var createNthRoot =
21136/* #__PURE__ */
21137Object(factory["a" /* factory */])(nthRoot_name, nthRoot_dependencies, function (_ref) {
21138 var typed = _ref.typed,
21139 matrix = _ref.matrix,
21140 equalScalar = _ref.equalScalar,
21141 _BigNumber = _ref.BigNumber;
21142 var algorithm01 = createAlgorithm01({
21143 typed: typed
21144 });
21145 var algorithm02 = createAlgorithm02({
21146 typed: typed,
21147 equalScalar: equalScalar
21148 });
21149 var algorithm06 = createAlgorithm06({
21150 typed: typed,
21151 equalScalar: equalScalar
21152 });
21153 var algorithm11 = createAlgorithm11({
21154 typed: typed,
21155 equalScalar: equalScalar
21156 });
21157 var algorithm13 = createAlgorithm13({
21158 typed: typed
21159 });
21160 var algorithm14 = createAlgorithm14({
21161 typed: typed
21162 });
21163 /**
21164 * Calculate the nth root of a value.
21165 * The principal nth root of a positive real number A, is the positive real
21166 * solution of the equation
21167 *
21168 * x^root = A
21169 *
21170 * For matrices, the function is evaluated element wise.
21171 *
21172 * Syntax:
21173 *
21174 * math.nthRoot(a)
21175 * math.nthRoot(a, root)
21176 *
21177 * Examples:
21178 *
21179 * math.nthRoot(9, 2) // returns 3, as 3^2 == 9
21180 * math.sqrt(9) // returns 3, as 3^2 == 9
21181 * math.nthRoot(64, 3) // returns 4, as 4^3 == 64
21182 *
21183 * See also:
21184 *
21185 * sqrt, pow
21186 *
21187 * @param {number | BigNumber | Array | Matrix | Complex} a
21188 * Value for which to calculate the nth root
21189 * @param {number | BigNumber} [root=2] The root.
21190 * @return {number | Complex | Array | Matrix} Returns the nth root of `a`
21191 */
21192
21193 var complexErr = '' + 'Complex number not supported in function nthRoot. ' + 'Use nthRoots instead.';
21194 var nthRoot = typed(nthRoot_name, {
21195 number: function number(x) {
21196 return nthRootNumber(x, 2);
21197 },
21198 'number, number': nthRootNumber,
21199 BigNumber: function BigNumber(x) {
21200 return _bigNthRoot(x, new _BigNumber(2));
21201 },
21202 Complex: function Complex(x) {
21203 throw new Error(complexErr);
21204 },
21205 'Complex, number': function ComplexNumber(x, y) {
21206 throw new Error(complexErr);
21207 },
21208 'BigNumber, BigNumber': _bigNthRoot,
21209 'Array | Matrix': function ArrayMatrix(x) {
21210 return nthRoot(x, 2);
21211 },
21212 'SparseMatrix, SparseMatrix': function SparseMatrixSparseMatrix(x, y) {
21213 // density must be one (no zeros in matrix)
21214 if (y.density() === 1) {
21215 // sparse + sparse
21216 return algorithm06(x, y, nthRoot);
21217 } else {
21218 // throw exception
21219 throw new Error('Root must be non-zero');
21220 }
21221 },
21222 'SparseMatrix, DenseMatrix': function SparseMatrixDenseMatrix(x, y) {
21223 return algorithm02(y, x, nthRoot, true);
21224 },
21225 'DenseMatrix, SparseMatrix': function DenseMatrixSparseMatrix(x, y) {
21226 // density must be one (no zeros in matrix)
21227 if (y.density() === 1) {
21228 // dense + sparse
21229 return algorithm01(x, y, nthRoot, false);
21230 } else {
21231 // throw exception
21232 throw new Error('Root must be non-zero');
21233 }
21234 },
21235 'DenseMatrix, DenseMatrix': function DenseMatrixDenseMatrix(x, y) {
21236 return algorithm13(x, y, nthRoot);
21237 },
21238 'Array, Array': function ArrayArray(x, y) {
21239 // use matrix implementation
21240 return nthRoot(matrix(x), matrix(y)).valueOf();
21241 },
21242 'Array, Matrix': function ArrayMatrix(x, y) {
21243 // use matrix implementation
21244 return nthRoot(matrix(x), y);
21245 },
21246 'Matrix, Array': function MatrixArray(x, y) {
21247 // use matrix implementation
21248 return nthRoot(x, matrix(y));
21249 },
21250 'SparseMatrix, number | BigNumber': function SparseMatrixNumberBigNumber(x, y) {
21251 return algorithm11(x, y, nthRoot, false);
21252 },
21253 'DenseMatrix, number | BigNumber': function DenseMatrixNumberBigNumber(x, y) {
21254 return algorithm14(x, y, nthRoot, false);
21255 },
21256 'number | BigNumber, SparseMatrix': function numberBigNumberSparseMatrix(x, y) {
21257 // density must be one (no zeros in matrix)
21258 if (y.density() === 1) {
21259 // sparse - scalar
21260 return algorithm11(y, x, nthRoot, true);
21261 } else {
21262 // throw exception
21263 throw new Error('Root must be non-zero');
21264 }
21265 },
21266 'number | BigNumber, DenseMatrix': function numberBigNumberDenseMatrix(x, y) {
21267 return algorithm14(y, x, nthRoot, true);
21268 },
21269 'Array, number | BigNumber': function ArrayNumberBigNumber(x, y) {
21270 // use matrix implementation
21271 return nthRoot(matrix(x), y).valueOf();
21272 },
21273 'number | BigNumber, Array': function numberBigNumberArray(x, y) {
21274 // use matrix implementation
21275 return nthRoot(x, matrix(y)).valueOf();
21276 }
21277 });
21278 return nthRoot;
21279 /**
21280 * Calculate the nth root of a for BigNumbers, solve x^root == a
21281 * https://rosettacode.org/wiki/Nth_root#JavaScript
21282 * @param {BigNumber} a
21283 * @param {BigNumber} root
21284 * @private
21285 */
21286
21287 function _bigNthRoot(a, root) {
21288 var precision = _BigNumber.precision;
21289
21290 var Big = _BigNumber.clone({
21291 precision: precision + 2
21292 });
21293
21294 var zero = new _BigNumber(0);
21295 var one = new Big(1);
21296 var inv = root.isNegative();
21297
21298 if (inv) {
21299 root = root.neg();
21300 }
21301
21302 if (root.isZero()) {
21303 throw new Error('Root must be non-zero');
21304 }
21305
21306 if (a.isNegative() && !root.abs().mod(2).equals(1)) {
21307 throw new Error('Root must be odd when a is negative.');
21308 } // edge cases zero and infinity
21309
21310
21311 if (a.isZero()) {
21312 return inv ? new Big(Infinity) : 0;
21313 }
21314
21315 if (!a.isFinite()) {
21316 return inv ? zero : a;
21317 }
21318
21319 var x = a.abs().pow(one.div(root)); // If a < 0, we require that root is an odd integer,
21320 // so (-1) ^ (1/root) = -1
21321
21322 x = a.isNeg() ? x.neg() : x;
21323 return new _BigNumber((inv ? one.div(x) : x).toPrecision(precision));
21324 }
21325});
21326var createNthRootNumber =
21327/* #__PURE__ */
21328Object(factory["a" /* factory */])(nthRoot_name, ['typed'], function (_ref2) {
21329 var typed = _ref2.typed;
21330 return typed(nthRoot_name, {
21331 number: nthRootNumber,
21332 'number, number': nthRootNumber
21333 });
21334});
21335// CONCATENATED MODULE: ./src/function/arithmetic/sign.js
21336
21337
21338
21339var sign_name = 'sign';
21340var sign_dependencies = ['typed', 'BigNumber', 'Fraction'];
21341var createSign =
21342/* #__PURE__ */
21343Object(factory["a" /* factory */])(sign_name, sign_dependencies, function (_ref) {
21344 var typed = _ref.typed,
21345 _BigNumber = _ref.BigNumber,
21346 _Fraction = _ref.Fraction;
21347
21348 /**
21349 * Compute the sign of a value. The sign of a value x is:
21350 *
21351 * - 1 when x > 0
21352 * - -1 when x < 0
21353 * - 0 when x == 0
21354 *
21355 * For matrices, the function is evaluated element wise.
21356 *
21357 * Syntax:
21358 *
21359 * math.sign(x)
21360 *
21361 * Examples:
21362 *
21363 * math.sign(3.5) // returns 1
21364 * math.sign(-4.2) // returns -1
21365 * math.sign(0) // returns 0
21366 *
21367 * math.sign([3, 5, -2, 0, 2]) // returns [1, 1, -1, 0, 1]
21368 *
21369 * See also:
21370 *
21371 * abs
21372 *
21373 * @param {number | BigNumber | Fraction | Complex | Array | Matrix | Unit} x
21374 * The number for which to determine the sign
21375 * @return {number | BigNumber | Fraction | Complex | Array | Matrix | Unit}e
21376 * The sign of `x`
21377 */
21378 var sign = typed(sign_name, {
21379 number: signNumber,
21380 Complex: function Complex(x) {
21381 return x.sign();
21382 },
21383 BigNumber: function BigNumber(x) {
21384 return new _BigNumber(x.cmp(0));
21385 },
21386 Fraction: function Fraction(x) {
21387 return new _Fraction(x.s, 1);
21388 },
21389 'Array | Matrix': function ArrayMatrix(x) {
21390 // deep map collection, skip zeros since sign(0) = 0
21391 return deepMap(x, sign, true);
21392 },
21393 Unit: function Unit(x) {
21394 return sign(x.value);
21395 }
21396 });
21397 return sign;
21398});
21399// CONCATENATED MODULE: ./src/function/arithmetic/sqrt.js
21400
21401
21402var sqrt_name = 'sqrt';
21403var sqrt_dependencies = ['config', 'typed', 'Complex'];
21404var createSqrt =
21405/* #__PURE__ */
21406Object(factory["a" /* factory */])(sqrt_name, sqrt_dependencies, function (_ref) {
21407 var config = _ref.config,
21408 typed = _ref.typed,
21409 Complex = _ref.Complex;
21410
21411 /**
21412 * Calculate the square root of a value.
21413 *
21414 * For matrices, the function is evaluated element wise.
21415 *
21416 * Syntax:
21417 *
21418 * math.sqrt(x)
21419 *
21420 * Examples:
21421 *
21422 * math.sqrt(25) // returns 5
21423 * math.square(5) // returns 25
21424 * math.sqrt(-4) // returns Complex 2i
21425 *
21426 * See also:
21427 *
21428 * square, multiply, cube, cbrt, sqrtm
21429 *
21430 * @param {number | BigNumber | Complex | Array | Matrix | Unit} x
21431 * Value for which to calculate the square root.
21432 * @return {number | BigNumber | Complex | Array | Matrix | Unit}
21433 * Returns the square root of `x`
21434 */
21435 var sqrt = typed('sqrt', {
21436 number: _sqrtNumber,
21437 Complex: function Complex(x) {
21438 return x.sqrt();
21439 },
21440 BigNumber: function BigNumber(x) {
21441 if (!x.isNegative() || config.predictable) {
21442 return x.sqrt();
21443 } else {
21444 // negative value -> downgrade to number to do complex value computation
21445 return _sqrtNumber(x.toNumber());
21446 }
21447 },
21448 'Array | Matrix': function ArrayMatrix(x) {
21449 // deep map collection, skip zeros since sqrt(0) = 0
21450 return deepMap(x, sqrt, true);
21451 },
21452 Unit: function Unit(x) {
21453 // Someday will work for complex units when they are implemented
21454 return x.pow(0.5);
21455 }
21456 });
21457 /**
21458 * Calculate sqrt for a number
21459 * @param {number} x
21460 * @returns {number | Complex} Returns the square root of x
21461 * @private
21462 */
21463
21464 function _sqrtNumber(x) {
21465 if (isNaN(x)) {
21466 return NaN;
21467 } else if (x >= 0 || config.predictable) {
21468 return Math.sqrt(x);
21469 } else {
21470 return new Complex(x, 0).sqrt();
21471 }
21472 }
21473
21474 return sqrt;
21475});
21476// CONCATENATED MODULE: ./src/function/arithmetic/square.js
21477
21478
21479
21480var square_name = 'square';
21481var square_dependencies = ['typed'];
21482var createSquare =
21483/* #__PURE__ */
21484Object(factory["a" /* factory */])(square_name, square_dependencies, function (_ref) {
21485 var typed = _ref.typed;
21486
21487 /**
21488 * Compute the square of a value, `x * x`.
21489 * For matrices, the function is evaluated element wise.
21490 *
21491 * Syntax:
21492 *
21493 * math.square(x)
21494 *
21495 * Examples:
21496 *
21497 * math.square(2) // returns number 4
21498 * math.square(3) // returns number 9
21499 * math.pow(3, 2) // returns number 9
21500 * math.multiply(3, 3) // returns number 9
21501 *
21502 * math.square([1, 2, 3, 4]) // returns Array [1, 4, 9, 16]
21503 *
21504 * See also:
21505 *
21506 * multiply, cube, sqrt, pow
21507 *
21508 * @param {number | BigNumber | Fraction | Complex | Array | Matrix | Unit} x
21509 * Number for which to calculate the square
21510 * @return {number | BigNumber | Fraction | Complex | Array | Matrix | Unit}
21511 * Squared value
21512 */
21513 var square = typed(square_name, {
21514 number: squareNumber,
21515 Complex: function Complex(x) {
21516 return x.mul(x);
21517 },
21518 BigNumber: function BigNumber(x) {
21519 return x.times(x);
21520 },
21521 Fraction: function Fraction(x) {
21522 return x.mul(x);
21523 },
21524 'Array | Matrix': function ArrayMatrix(x) {
21525 // deep map collection, skip zeros since square(0) = 0
21526 return deepMap(x, square, true);
21527 },
21528 Unit: function Unit(x) {
21529 return x.pow(2);
21530 }
21531 });
21532 return square;
21533});
21534// CONCATENATED MODULE: ./src/function/arithmetic/subtract.js
21535
21536
21537
21538
21539
21540
21541
21542
21543var subtract_name = 'subtract';
21544var subtract_dependencies = ['typed', 'matrix', 'equalScalar', 'addScalar', 'unaryMinus', 'DenseMatrix'];
21545var createSubtract =
21546/* #__PURE__ */
21547Object(factory["a" /* factory */])(subtract_name, subtract_dependencies, function (_ref) {
21548 var typed = _ref.typed,
21549 matrix = _ref.matrix,
21550 equalScalar = _ref.equalScalar,
21551 addScalar = _ref.addScalar,
21552 unaryMinus = _ref.unaryMinus,
21553 DenseMatrix = _ref.DenseMatrix;
21554 // TODO: split function subtract in two: subtract and subtractScalar
21555 var algorithm01 = createAlgorithm01({
21556 typed: typed
21557 });
21558 var algorithm03 = createAlgorithm03({
21559 typed: typed
21560 });
21561 var algorithm05 = createAlgorithm05({
21562 typed: typed,
21563 equalScalar: equalScalar
21564 });
21565 var algorithm10 = createAlgorithm10({
21566 typed: typed,
21567 DenseMatrix: DenseMatrix
21568 });
21569 var algorithm13 = createAlgorithm13({
21570 typed: typed
21571 });
21572 var algorithm14 = createAlgorithm14({
21573 typed: typed
21574 });
21575 /**
21576 * Subtract two values, `x - y`.
21577 * For matrices, the function is evaluated element wise.
21578 *
21579 * Syntax:
21580 *
21581 * math.subtract(x, y)
21582 *
21583 * Examples:
21584 *
21585 * math.subtract(5.3, 2) // returns number 3.3
21586 *
21587 * const a = math.complex(2, 3)
21588 * const b = math.complex(4, 1)
21589 * math.subtract(a, b) // returns Complex -2 + 2i
21590 *
21591 * math.subtract([5, 7, 4], 4) // returns Array [1, 3, 0]
21592 *
21593 * const c = math.unit('2.1 km')
21594 * const d = math.unit('500m')
21595 * math.subtract(c, d) // returns Unit 1.6 km
21596 *
21597 * See also:
21598 *
21599 * add
21600 *
21601 * @param {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} x
21602 * Initial value
21603 * @param {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} y
21604 * Value to subtract from `x`
21605 * @return {number | BigNumber | Fraction | Complex | Unit | Array | Matrix}
21606 * Subtraction of `x` and `y`
21607 */
21608
21609 var subtract = typed(subtract_name, {
21610 'number, number': function numberNumber(x, y) {
21611 return x - y;
21612 },
21613 'Complex, Complex': function ComplexComplex(x, y) {
21614 return x.sub(y);
21615 },
21616 'BigNumber, BigNumber': function BigNumberBigNumber(x, y) {
21617 return x.minus(y);
21618 },
21619 'Fraction, Fraction': function FractionFraction(x, y) {
21620 return x.sub(y);
21621 },
21622 'Unit, Unit': function UnitUnit(x, y) {
21623 if (x.value === null) {
21624 throw new Error('Parameter x contains a unit with undefined value');
21625 }
21626
21627 if (y.value === null) {
21628 throw new Error('Parameter y contains a unit with undefined value');
21629 }
21630
21631 if (!x.equalBase(y)) {
21632 throw new Error('Units do not match');
21633 }
21634
21635 var res = x.clone();
21636 res.value = subtract(res.value, y.value);
21637 res.fixPrefix = false;
21638 return res;
21639 },
21640 'SparseMatrix, SparseMatrix': function SparseMatrixSparseMatrix(x, y) {
21641 checkEqualDimensions(x, y);
21642 return algorithm05(x, y, subtract);
21643 },
21644 'SparseMatrix, DenseMatrix': function SparseMatrixDenseMatrix(x, y) {
21645 checkEqualDimensions(x, y);
21646 return algorithm03(y, x, subtract, true);
21647 },
21648 'DenseMatrix, SparseMatrix': function DenseMatrixSparseMatrix(x, y) {
21649 checkEqualDimensions(x, y);
21650 return algorithm01(x, y, subtract, false);
21651 },
21652 'DenseMatrix, DenseMatrix': function DenseMatrixDenseMatrix(x, y) {
21653 checkEqualDimensions(x, y);
21654 return algorithm13(x, y, subtract);
21655 },
21656 'Array, Array': function ArrayArray(x, y) {
21657 // use matrix implementation
21658 return subtract(matrix(x), matrix(y)).valueOf();
21659 },
21660 'Array, Matrix': function ArrayMatrix(x, y) {
21661 // use matrix implementation
21662 return subtract(matrix(x), y);
21663 },
21664 'Matrix, Array': function MatrixArray(x, y) {
21665 // use matrix implementation
21666 return subtract(x, matrix(y));
21667 },
21668 'SparseMatrix, any': function SparseMatrixAny(x, y) {
21669 return algorithm10(x, unaryMinus(y), addScalar);
21670 },
21671 'DenseMatrix, any': function DenseMatrixAny(x, y) {
21672 return algorithm14(x, y, subtract);
21673 },
21674 'any, SparseMatrix': function anySparseMatrix(x, y) {
21675 return algorithm10(y, x, subtract, true);
21676 },
21677 'any, DenseMatrix': function anyDenseMatrix(x, y) {
21678 return algorithm14(y, x, subtract, true);
21679 },
21680 'Array, any': function ArrayAny(x, y) {
21681 // use matrix implementation
21682 return algorithm14(matrix(x), y, subtract, false).valueOf();
21683 },
21684 'any, Array': function anyArray(x, y) {
21685 // use matrix implementation
21686 return algorithm14(matrix(y), x, subtract, true).valueOf();
21687 }
21688 });
21689 return subtract;
21690});
21691/**
21692 * Check whether matrix x and y have the same number of dimensions.
21693 * Throws a DimensionError when dimensions are not equal
21694 * @param {Matrix} x
21695 * @param {Matrix} y
21696 */
21697
21698function checkEqualDimensions(x, y) {
21699 var xsize = x.size();
21700 var ysize = y.size();
21701
21702 if (xsize.length !== ysize.length) {
21703 throw new DimensionError["a" /* DimensionError */](xsize.length, ysize.length);
21704 }
21705}
21706// CONCATENATED MODULE: ./src/function/arithmetic/xgcd.js
21707
21708
21709var xgcd_name = 'xgcd';
21710var xgcd_dependencies = ['typed', 'config', 'matrix', 'BigNumber'];
21711var createXgcd =
21712/* #__PURE__ */
21713Object(factory["a" /* factory */])(xgcd_name, xgcd_dependencies, function (_ref) {
21714 var typed = _ref.typed,
21715 config = _ref.config,
21716 matrix = _ref.matrix,
21717 BigNumber = _ref.BigNumber;
21718
21719 /**
21720 * Calculate the extended greatest common divisor for two values.
21721 * See https://en.wikipedia.org/wiki/Extended_Euclidean_algorithm.
21722 *
21723 * Syntax:
21724 *
21725 * math.xgcd(a, b)
21726 *
21727 * Examples:
21728 *
21729 * math.xgcd(8, 12) // returns [4, -1, 1]
21730 * math.gcd(8, 12) // returns 4
21731 * math.xgcd(36163, 21199) // returns [1247, -7, 12]
21732 *
21733 * See also:
21734 *
21735 * gcd, lcm
21736 *
21737 * @param {number | BigNumber} a An integer number
21738 * @param {number | BigNumber} b An integer number
21739 * @return {Array} Returns an array containing 3 integers `[div, m, n]`
21740 * where `div = gcd(a, b)` and `a*m + b*n = div`
21741 */
21742 return typed(xgcd_name, {
21743 'number, number': function numberNumber(a, b) {
21744 var res = xgcdNumber(a, b);
21745 return config.matrix === 'Array' ? res : matrix(res);
21746 },
21747 'BigNumber, BigNumber': _xgcdBigNumber // TODO: implement support for Fraction
21748
21749 });
21750 /**
21751 * Calculate xgcd for two BigNumbers
21752 * @param {BigNumber} a
21753 * @param {BigNumber} b
21754 * @return {BigNumber[]} result
21755 * @private
21756 */
21757
21758 function _xgcdBigNumber(a, b) {
21759 // source: https://en.wikipedia.org/wiki/Extended_Euclidean_algorithm
21760 var // used to swap two variables
21761 t;
21762 var // quotient
21763 q;
21764 var // remainder
21765 r;
21766 var zero = new BigNumber(0);
21767 var one = new BigNumber(1);
21768 var x = zero;
21769 var lastx = one;
21770 var y = one;
21771 var lasty = zero;
21772
21773 if (!a.isInt() || !b.isInt()) {
21774 throw new Error('Parameters in function xgcd must be integer numbers');
21775 }
21776
21777 while (!b.isZero()) {
21778 q = a.div(b).floor();
21779 r = a.mod(b);
21780 t = x;
21781 x = lastx.minus(q.times(x));
21782 lastx = t;
21783 t = y;
21784 y = lasty.minus(q.times(y));
21785 lasty = t;
21786 a = b;
21787 b = r;
21788 }
21789
21790 var res;
21791
21792 if (a.lt(zero)) {
21793 res = [a.neg(), lastx.neg(), lasty.neg()];
21794 } else {
21795 res = [a, !a.isZero() ? lastx : 0, lasty];
21796 }
21797
21798 return config.matrix === 'Array' ? res : matrix(res);
21799 }
21800});
21801// CONCATENATED MODULE: ./src/type/matrix/utils/algorithm09.js
21802
21803
21804var algorithm09_name = 'algorithm09';
21805var algorithm09_dependencies = ['typed', 'equalScalar'];
21806var createAlgorithm09 =
21807/* #__PURE__ */
21808Object(factory["a" /* factory */])(algorithm09_name, algorithm09_dependencies, function (_ref) {
21809 var typed = _ref.typed,
21810 equalScalar = _ref.equalScalar;
21811
21812 /**
21813 * Iterates over SparseMatrix A and invokes the callback function f(Aij, Bij).
21814 * Callback function invoked NZA times, number of nonzero elements in A.
21815 *
21816 *
21817 * ┌ f(Aij, Bij) ; A(i,j) !== 0
21818 * C(i,j) = ┤
21819 * └ 0 ; otherwise
21820 *
21821 *
21822 * @param {Matrix} a The SparseMatrix instance (A)
21823 * @param {Matrix} b The SparseMatrix instance (B)
21824 * @param {Function} callback The f(Aij,Bij) operation to invoke
21825 *
21826 * @return {Matrix} SparseMatrix (C)
21827 *
21828 * see https://github.com/josdejong/mathjs/pull/346#issuecomment-97620294
21829 */
21830 return function algorithm09(a, b, callback) {
21831 // sparse matrix arrays
21832 var avalues = a._values;
21833 var aindex = a._index;
21834 var aptr = a._ptr;
21835 var asize = a._size;
21836 var adt = a._datatype; // sparse matrix arrays
21837
21838 var bvalues = b._values;
21839 var bindex = b._index;
21840 var bptr = b._ptr;
21841 var bsize = b._size;
21842 var bdt = b._datatype; // validate dimensions
21843
21844 if (asize.length !== bsize.length) {
21845 throw new DimensionError["a" /* DimensionError */](asize.length, bsize.length);
21846 } // check rows & columns
21847
21848
21849 if (asize[0] !== bsize[0] || asize[1] !== bsize[1]) {
21850 throw new RangeError('Dimension mismatch. Matrix A (' + asize + ') must match Matrix B (' + bsize + ')');
21851 } // rows & columns
21852
21853
21854 var rows = asize[0];
21855 var columns = asize[1]; // datatype
21856
21857 var dt; // equal signature to use
21858
21859 var eq = equalScalar; // zero value
21860
21861 var zero = 0; // callback signature to use
21862
21863 var cf = callback; // process data types
21864
21865 if (typeof adt === 'string' && adt === bdt) {
21866 // datatype
21867 dt = adt; // find signature that matches (dt, dt)
21868
21869 eq = typed.find(equalScalar, [dt, dt]); // convert 0 to the same datatype
21870
21871 zero = typed.convert(0, dt); // callback
21872
21873 cf = typed.find(callback, [dt, dt]);
21874 } // result arrays
21875
21876
21877 var cvalues = avalues && bvalues ? [] : undefined;
21878 var cindex = [];
21879 var cptr = []; // matrix
21880
21881 var c = a.createSparseMatrix({
21882 values: cvalues,
21883 index: cindex,
21884 ptr: cptr,
21885 size: [rows, columns],
21886 datatype: dt
21887 }); // workspaces
21888
21889 var x = cvalues ? [] : undefined; // marks indicating we have a value in x for a given column
21890
21891 var w = []; // vars
21892
21893 var i, j, k, k0, k1; // loop columns
21894
21895 for (j = 0; j < columns; j++) {
21896 // update cptr
21897 cptr[j] = cindex.length; // column mark
21898
21899 var mark = j + 1; // check we need to process values
21900
21901 if (x) {
21902 // loop B(:,j)
21903 for (k0 = bptr[j], k1 = bptr[j + 1], k = k0; k < k1; k++) {
21904 // row
21905 i = bindex[k]; // update workspace
21906
21907 w[i] = mark;
21908 x[i] = bvalues[k];
21909 }
21910 } // loop A(:,j)
21911
21912
21913 for (k0 = aptr[j], k1 = aptr[j + 1], k = k0; k < k1; k++) {
21914 // row
21915 i = aindex[k]; // check we need to process values
21916
21917 if (x) {
21918 // b value @ i,j
21919 var vb = w[i] === mark ? x[i] : zero; // invoke f
21920
21921 var vc = cf(avalues[k], vb); // check zero value
21922
21923 if (!eq(vc, zero)) {
21924 // push index
21925 cindex.push(i); // push value
21926
21927 cvalues.push(vc);
21928 }
21929 } else {
21930 // push index
21931 cindex.push(i);
21932 }
21933 }
21934 } // update cptr
21935
21936
21937 cptr[columns] = cindex.length; // return sparse matrix
21938
21939 return c;
21940 };
21941});
21942// CONCATENATED MODULE: ./src/function/arithmetic/dotMultiply.js
21943
21944
21945
21946
21947
21948
21949var dotMultiply_name = 'dotMultiply';
21950var dotMultiply_dependencies = ['typed', 'matrix', 'equalScalar', 'multiplyScalar'];
21951var createDotMultiply =
21952/* #__PURE__ */
21953Object(factory["a" /* factory */])(dotMultiply_name, dotMultiply_dependencies, function (_ref) {
21954 var typed = _ref.typed,
21955 matrix = _ref.matrix,
21956 equalScalar = _ref.equalScalar,
21957 multiplyScalar = _ref.multiplyScalar;
21958 var algorithm02 = createAlgorithm02({
21959 typed: typed,
21960 equalScalar: equalScalar
21961 });
21962 var algorithm09 = createAlgorithm09({
21963 typed: typed,
21964 equalScalar: equalScalar
21965 });
21966 var algorithm11 = createAlgorithm11({
21967 typed: typed,
21968 equalScalar: equalScalar
21969 });
21970 var algorithm13 = createAlgorithm13({
21971 typed: typed
21972 });
21973 var algorithm14 = createAlgorithm14({
21974 typed: typed
21975 });
21976 /**
21977 * Multiply two matrices element wise. The function accepts both matrices and
21978 * scalar values.
21979 *
21980 * Syntax:
21981 *
21982 * math.dotMultiply(x, y)
21983 *
21984 * Examples:
21985 *
21986 * math.dotMultiply(2, 4) // returns 8
21987 *
21988 * a = [[9, 5], [6, 1]]
21989 * b = [[3, 2], [5, 2]]
21990 *
21991 * math.dotMultiply(a, b) // returns [[27, 10], [30, 2]]
21992 * math.multiply(a, b) // returns [[52, 28], [23, 14]]
21993 *
21994 * See also:
21995 *
21996 * multiply, divide, dotDivide
21997 *
21998 * @param {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} x Left hand value
21999 * @param {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} y Right hand value
22000 * @return {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} Multiplication of `x` and `y`
22001 */
22002
22003 var dotMultiply = typed(dotMultiply_name, {
22004 'any, any': multiplyScalar,
22005 'SparseMatrix, SparseMatrix': function SparseMatrixSparseMatrix(x, y) {
22006 return algorithm09(x, y, multiplyScalar, false);
22007 },
22008 'SparseMatrix, DenseMatrix': function SparseMatrixDenseMatrix(x, y) {
22009 return algorithm02(y, x, multiplyScalar, true);
22010 },
22011 'DenseMatrix, SparseMatrix': function DenseMatrixSparseMatrix(x, y) {
22012 return algorithm02(x, y, multiplyScalar, false);
22013 },
22014 'DenseMatrix, DenseMatrix': function DenseMatrixDenseMatrix(x, y) {
22015 return algorithm13(x, y, multiplyScalar);
22016 },
22017 'Array, Array': function ArrayArray(x, y) {
22018 // use matrix implementation
22019 return dotMultiply(matrix(x), matrix(y)).valueOf();
22020 },
22021 'Array, Matrix': function ArrayMatrix(x, y) {
22022 // use matrix implementation
22023 return dotMultiply(matrix(x), y);
22024 },
22025 'Matrix, Array': function MatrixArray(x, y) {
22026 // use matrix implementation
22027 return dotMultiply(x, matrix(y));
22028 },
22029 'SparseMatrix, any': function SparseMatrixAny(x, y) {
22030 return algorithm11(x, y, multiplyScalar, false);
22031 },
22032 'DenseMatrix, any': function DenseMatrixAny(x, y) {
22033 return algorithm14(x, y, multiplyScalar, false);
22034 },
22035 'any, SparseMatrix': function anySparseMatrix(x, y) {
22036 return algorithm11(y, x, multiplyScalar, true);
22037 },
22038 'any, DenseMatrix': function anyDenseMatrix(x, y) {
22039 return algorithm14(y, x, multiplyScalar, true);
22040 },
22041 'Array, any': function ArrayAny(x, y) {
22042 // use matrix implementation
22043 return algorithm14(matrix(x), y, multiplyScalar, false).valueOf();
22044 },
22045 'any, Array': function anyArray(x, y) {
22046 // use matrix implementation
22047 return algorithm14(matrix(y), x, multiplyScalar, true).valueOf();
22048 }
22049 });
22050 return dotMultiply;
22051});
22052// CONCATENATED MODULE: ./src/utils/bignumber/bitwise.js
22053/**
22054 * Bitwise and for Bignumbers
22055 *
22056 * Special Cases:
22057 * N & n = N
22058 * n & 0 = 0
22059 * n & -1 = n
22060 * n & n = n
22061 * I & I = I
22062 * -I & -I = -I
22063 * I & -I = 0
22064 * I & n = n
22065 * I & -n = I
22066 * -I & n = 0
22067 * -I & -n = -I
22068 *
22069 * @param {BigNumber} x
22070 * @param {BigNumber} y
22071 * @return {BigNumber} Result of `x` & `y`, is fully precise
22072 * @private
22073 */
22074function bitAndBigNumber(x, y) {
22075 if (x.isFinite() && !x.isInteger() || y.isFinite() && !y.isInteger()) {
22076 throw new Error('Integers expected in function bitAnd');
22077 }
22078
22079 var BigNumber = x.constructor;
22080
22081 if (x.isNaN() || y.isNaN()) {
22082 return new BigNumber(NaN);
22083 }
22084
22085 if (x.isZero() || y.eq(-1) || x.eq(y)) {
22086 return x;
22087 }
22088
22089 if (y.isZero() || x.eq(-1)) {
22090 return y;
22091 }
22092
22093 if (!x.isFinite() || !y.isFinite()) {
22094 if (!x.isFinite() && !y.isFinite()) {
22095 if (x.isNegative() === y.isNegative()) {
22096 return x;
22097 }
22098
22099 return new BigNumber(0);
22100 }
22101
22102 if (!x.isFinite()) {
22103 if (y.isNegative()) {
22104 return x;
22105 }
22106
22107 if (x.isNegative()) {
22108 return new BigNumber(0);
22109 }
22110
22111 return y;
22112 }
22113
22114 if (!y.isFinite()) {
22115 if (x.isNegative()) {
22116 return y;
22117 }
22118
22119 if (y.isNegative()) {
22120 return new BigNumber(0);
22121 }
22122
22123 return x;
22124 }
22125 }
22126
22127 return bitwise(x, y, function (a, b) {
22128 return a & b;
22129 });
22130}
22131/**
22132 * Bitwise not
22133 * @param {BigNumber} x
22134 * @return {BigNumber} Result of ~`x`, fully precise
22135 *
22136 */
22137
22138function bitNotBigNumber(x) {
22139 if (x.isFinite() && !x.isInteger()) {
22140 throw new Error('Integer expected in function bitNot');
22141 }
22142
22143 var BigNumber = x.constructor;
22144 var prevPrec = BigNumber.precision;
22145 BigNumber.config({
22146 precision: 1E9
22147 });
22148 var result = x.plus(new BigNumber(1));
22149 result.s = -result.s || null;
22150 BigNumber.config({
22151 precision: prevPrec
22152 });
22153 return result;
22154}
22155/**
22156 * Bitwise OR for BigNumbers
22157 *
22158 * Special Cases:
22159 * N | n = N
22160 * n | 0 = n
22161 * n | -1 = -1
22162 * n | n = n
22163 * I | I = I
22164 * -I | -I = -I
22165 * I | -n = -1
22166 * I | -I = -1
22167 * I | n = I
22168 * -I | n = -I
22169 * -I | -n = -n
22170 *
22171 * @param {BigNumber} x
22172 * @param {BigNumber} y
22173 * @return {BigNumber} Result of `x` | `y`, fully precise
22174 */
22175
22176function bitOrBigNumber(x, y) {
22177 if (x.isFinite() && !x.isInteger() || y.isFinite() && !y.isInteger()) {
22178 throw new Error('Integers expected in function bitOr');
22179 }
22180
22181 var BigNumber = x.constructor;
22182
22183 if (x.isNaN() || y.isNaN()) {
22184 return new BigNumber(NaN);
22185 }
22186
22187 var negOne = new BigNumber(-1);
22188
22189 if (x.isZero() || y.eq(negOne) || x.eq(y)) {
22190 return y;
22191 }
22192
22193 if (y.isZero() || x.eq(negOne)) {
22194 return x;
22195 }
22196
22197 if (!x.isFinite() || !y.isFinite()) {
22198 if (!x.isFinite() && !x.isNegative() && y.isNegative() || x.isNegative() && !y.isNegative() && !y.isFinite()) {
22199 return negOne;
22200 }
22201
22202 if (x.isNegative() && y.isNegative()) {
22203 return x.isFinite() ? x : y;
22204 }
22205
22206 return x.isFinite() ? y : x;
22207 }
22208
22209 return bitwise(x, y, function (a, b) {
22210 return a | b;
22211 });
22212}
22213/**
22214 * Applies bitwise function to numbers
22215 * @param {BigNumber} x
22216 * @param {BigNumber} y
22217 * @param {function (a, b)} func
22218 * @return {BigNumber}
22219 */
22220
22221function bitwise(x, y, func) {
22222 var BigNumber = x.constructor;
22223 var xBits, yBits;
22224 var xSign = +(x.s < 0);
22225 var ySign = +(y.s < 0);
22226
22227 if (xSign) {
22228 xBits = decCoefficientToBinaryString(bitNotBigNumber(x));
22229
22230 for (var i = 0; i < xBits.length; ++i) {
22231 xBits[i] ^= 1;
22232 }
22233 } else {
22234 xBits = decCoefficientToBinaryString(x);
22235 }
22236
22237 if (ySign) {
22238 yBits = decCoefficientToBinaryString(bitNotBigNumber(y));
22239
22240 for (var _i = 0; _i < yBits.length; ++_i) {
22241 yBits[_i] ^= 1;
22242 }
22243 } else {
22244 yBits = decCoefficientToBinaryString(y);
22245 }
22246
22247 var minBits, maxBits, minSign;
22248
22249 if (xBits.length <= yBits.length) {
22250 minBits = xBits;
22251 maxBits = yBits;
22252 minSign = xSign;
22253 } else {
22254 minBits = yBits;
22255 maxBits = xBits;
22256 minSign = ySign;
22257 }
22258
22259 var shortLen = minBits.length;
22260 var longLen = maxBits.length;
22261 var expFuncVal = func(xSign, ySign) ^ 1;
22262 var outVal = new BigNumber(expFuncVal ^ 1);
22263 var twoPower = new BigNumber(1);
22264 var two = new BigNumber(2);
22265 var prevPrec = BigNumber.precision;
22266 BigNumber.config({
22267 precision: 1E9
22268 });
22269
22270 while (shortLen > 0) {
22271 if (func(minBits[--shortLen], maxBits[--longLen]) === expFuncVal) {
22272 outVal = outVal.plus(twoPower);
22273 }
22274
22275 twoPower = twoPower.times(two);
22276 }
22277
22278 while (longLen > 0) {
22279 if (func(minSign, maxBits[--longLen]) === expFuncVal) {
22280 outVal = outVal.plus(twoPower);
22281 }
22282
22283 twoPower = twoPower.times(two);
22284 }
22285
22286 BigNumber.config({
22287 precision: prevPrec
22288 });
22289
22290 if (expFuncVal === 0) {
22291 outVal.s = -outVal.s;
22292 }
22293
22294 return outVal;
22295}
22296/* Extracted from decimal.js, and edited to specialize. */
22297
22298function decCoefficientToBinaryString(x) {
22299 // Convert to string
22300 var a = x.d; // array with digits
22301
22302 var r = a[0] + '';
22303
22304 for (var i = 1; i < a.length; ++i) {
22305 var s = a[i] + '';
22306
22307 for (var z = 7 - s.length; z--;) {
22308 s = '0' + s;
22309 }
22310
22311 r += s;
22312 }
22313
22314 var j = r.length;
22315
22316 while (r.charAt(j) === '0') {
22317 j--;
22318 }
22319
22320 var xe = x.e;
22321 var str = r.slice(0, j + 1 || 1);
22322 var strL = str.length;
22323
22324 if (xe > 0) {
22325 if (++xe > strL) {
22326 // Append zeros.
22327 xe -= strL;
22328
22329 while (xe--) {
22330 str += '0';
22331 }
22332 } else if (xe < strL) {
22333 str = str.slice(0, xe) + '.' + str.slice(xe);
22334 }
22335 } // Convert from base 10 (decimal) to base 2
22336
22337
22338 var arr = [0];
22339
22340 for (var _i2 = 0; _i2 < str.length;) {
22341 var arrL = arr.length;
22342
22343 while (arrL--) {
22344 arr[arrL] *= 10;
22345 }
22346
22347 arr[0] += parseInt(str.charAt(_i2++)); // convert to int
22348
22349 for (var _j = 0; _j < arr.length; ++_j) {
22350 if (arr[_j] > 1) {
22351 if (arr[_j + 1] === null || arr[_j + 1] === undefined) {
22352 arr[_j + 1] = 0;
22353 }
22354
22355 arr[_j + 1] += arr[_j] >> 1;
22356 arr[_j] &= 1;
22357 }
22358 }
22359 }
22360
22361 return arr.reverse();
22362}
22363/**
22364 * Bitwise XOR for BigNumbers
22365 *
22366 * Special Cases:
22367 * N ^ n = N
22368 * n ^ 0 = n
22369 * n ^ n = 0
22370 * n ^ -1 = ~n
22371 * I ^ n = I
22372 * I ^ -n = -I
22373 * I ^ -I = -1
22374 * -I ^ n = -I
22375 * -I ^ -n = I
22376 *
22377 * @param {BigNumber} x
22378 * @param {BigNumber} y
22379 * @return {BigNumber} Result of `x` ^ `y`, fully precise
22380 *
22381 */
22382
22383
22384function bitwise_bitXor(x, y) {
22385 if (x.isFinite() && !x.isInteger() || y.isFinite() && !y.isInteger()) {
22386 throw new Error('Integers expected in function bitXor');
22387 }
22388
22389 var BigNumber = x.constructor;
22390
22391 if (x.isNaN() || y.isNaN()) {
22392 return new BigNumber(NaN);
22393 }
22394
22395 if (x.isZero()) {
22396 return y;
22397 }
22398
22399 if (y.isZero()) {
22400 return x;
22401 }
22402
22403 if (x.eq(y)) {
22404 return new BigNumber(0);
22405 }
22406
22407 var negOne = new BigNumber(-1);
22408
22409 if (x.eq(negOne)) {
22410 return bitNotBigNumber(y);
22411 }
22412
22413 if (y.eq(negOne)) {
22414 return bitNotBigNumber(x);
22415 }
22416
22417 if (!x.isFinite() || !y.isFinite()) {
22418 if (!x.isFinite() && !y.isFinite()) {
22419 return negOne;
22420 }
22421
22422 return new BigNumber(x.isNegative() === y.isNegative() ? Infinity : -Infinity);
22423 }
22424
22425 return bitwise(x, y, function (a, b) {
22426 return a ^ b;
22427 });
22428}
22429/**
22430 * Bitwise left shift
22431 *
22432 * Special Cases:
22433 * n << -n = N
22434 * n << N = N
22435 * N << n = N
22436 * n << 0 = n
22437 * 0 << n = 0
22438 * I << I = N
22439 * I << n = I
22440 * n << I = I
22441 *
22442 * @param {BigNumber} x
22443 * @param {BigNumber} y
22444 * @return {BigNumber} Result of `x` << `y`
22445 *
22446 */
22447
22448function leftShiftBigNumber(x, y) {
22449 if (x.isFinite() && !x.isInteger() || y.isFinite() && !y.isInteger()) {
22450 throw new Error('Integers expected in function leftShift');
22451 }
22452
22453 var BigNumber = x.constructor;
22454
22455 if (x.isNaN() || y.isNaN() || y.isNegative() && !y.isZero()) {
22456 return new BigNumber(NaN);
22457 }
22458
22459 if (x.isZero() || y.isZero()) {
22460 return x;
22461 }
22462
22463 if (!x.isFinite() && !y.isFinite()) {
22464 return new BigNumber(NaN);
22465 } // Math.pow(2, y) is fully precise for y < 55, and fast
22466
22467
22468 if (y.lt(55)) {
22469 return x.times(Math.pow(2, y.toNumber()) + '');
22470 }
22471
22472 return x.times(new BigNumber(2).pow(y));
22473}
22474/*
22475 * Special Cases:
22476 * n >> -n = N
22477 * n >> N = N
22478 * N >> n = N
22479 * I >> I = N
22480 * n >> 0 = n
22481 * I >> n = I
22482 * -I >> n = -I
22483 * -I >> I = -I
22484 * n >> I = I
22485 * -n >> I = -1
22486 * 0 >> n = 0
22487 *
22488 * @param {BigNumber} value
22489 * @param {BigNumber} value
22490 * @return {BigNumber} Result of `x` >> `y`
22491 *
22492 */
22493
22494function rightArithShiftBigNumber(x, y) {
22495 if (x.isFinite() && !x.isInteger() || y.isFinite() && !y.isInteger()) {
22496 throw new Error('Integers expected in function rightArithShift');
22497 }
22498
22499 var BigNumber = x.constructor;
22500
22501 if (x.isNaN() || y.isNaN() || y.isNegative() && !y.isZero()) {
22502 return new BigNumber(NaN);
22503 }
22504
22505 if (x.isZero() || y.isZero()) {
22506 return x;
22507 }
22508
22509 if (!y.isFinite()) {
22510 if (x.isNegative()) {
22511 return new BigNumber(-1);
22512 }
22513
22514 if (!x.isFinite()) {
22515 return new BigNumber(NaN);
22516 }
22517
22518 return new BigNumber(0);
22519 } // Math.pow(2, y) is fully precise for y < 55, and fast
22520
22521
22522 if (y.lt(55)) {
22523 return x.div(Math.pow(2, y.toNumber()) + '').floor();
22524 }
22525
22526 return x.div(new BigNumber(2).pow(y)).floor();
22527}
22528// CONCATENATED MODULE: ./src/plain/number/bitwise.js
22529
22530var bitwise_n1 = 'number';
22531var bitwise_n2 = 'number, number';
22532function bitAndNumber(x, y) {
22533 if (!Object(utils_number["i" /* isInteger */])(x) || !Object(utils_number["i" /* isInteger */])(y)) {
22534 throw new Error('Integers expected in function bitAnd');
22535 }
22536
22537 return x & y;
22538}
22539bitAndNumber.signature = bitwise_n2;
22540function bitNotNumber(x) {
22541 if (!Object(utils_number["i" /* isInteger */])(x)) {
22542 throw new Error('Integer expected in function bitNot');
22543 }
22544
22545 return ~x;
22546}
22547bitNotNumber.signature = bitwise_n1;
22548function bitOrNumber(x, y) {
22549 if (!Object(utils_number["i" /* isInteger */])(x) || !Object(utils_number["i" /* isInteger */])(y)) {
22550 throw new Error('Integers expected in function bitOr');
22551 }
22552
22553 return x | y;
22554}
22555bitOrNumber.signature = bitwise_n2;
22556function bitXorNumber(x, y) {
22557 if (!Object(utils_number["i" /* isInteger */])(x) || !Object(utils_number["i" /* isInteger */])(y)) {
22558 throw new Error('Integers expected in function bitXor');
22559 }
22560
22561 return x ^ y;
22562}
22563bitXorNumber.signature = bitwise_n2;
22564function leftShiftNumber(x, y) {
22565 if (!Object(utils_number["i" /* isInteger */])(x) || !Object(utils_number["i" /* isInteger */])(y)) {
22566 throw new Error('Integers expected in function leftShift');
22567 }
22568
22569 return x << y;
22570}
22571leftShiftNumber.signature = bitwise_n2;
22572function rightArithShiftNumber(x, y) {
22573 if (!Object(utils_number["i" /* isInteger */])(x) || !Object(utils_number["i" /* isInteger */])(y)) {
22574 throw new Error('Integers expected in function rightArithShift');
22575 }
22576
22577 return x >> y;
22578}
22579rightArithShiftNumber.signature = bitwise_n2;
22580function rightLogShiftNumber(x, y) {
22581 if (!Object(utils_number["i" /* isInteger */])(x) || !Object(utils_number["i" /* isInteger */])(y)) {
22582 throw new Error('Integers expected in function rightLogShift');
22583 }
22584
22585 return x >>> y;
22586}
22587rightLogShiftNumber.signature = bitwise_n2;
22588// CONCATENATED MODULE: ./src/function/bitwise/bitAnd.js
22589
22590
22591
22592
22593
22594
22595
22596
22597var bitAnd_name = 'bitAnd';
22598var bitAnd_dependencies = ['typed', 'matrix', 'equalScalar'];
22599var createBitAnd =
22600/* #__PURE__ */
22601Object(factory["a" /* factory */])(bitAnd_name, bitAnd_dependencies, function (_ref) {
22602 var typed = _ref.typed,
22603 matrix = _ref.matrix,
22604 equalScalar = _ref.equalScalar;
22605 var algorithm02 = createAlgorithm02({
22606 typed: typed,
22607 equalScalar: equalScalar
22608 });
22609 var algorithm06 = createAlgorithm06({
22610 typed: typed,
22611 equalScalar: equalScalar
22612 });
22613 var algorithm11 = createAlgorithm11({
22614 typed: typed,
22615 equalScalar: equalScalar
22616 });
22617 var algorithm13 = createAlgorithm13({
22618 typed: typed
22619 });
22620 var algorithm14 = createAlgorithm14({
22621 typed: typed
22622 });
22623 /**
22624 * Bitwise AND two values, `x & y`.
22625 * For matrices, the function is evaluated element wise.
22626 *
22627 * Syntax:
22628 *
22629 * math.bitAnd(x, y)
22630 *
22631 * Examples:
22632 *
22633 * math.bitAnd(53, 131) // returns number 1
22634 *
22635 * math.bitAnd([1, 12, 31], 42) // returns Array [0, 8, 10]
22636 *
22637 * See also:
22638 *
22639 * bitNot, bitOr, bitXor, leftShift, rightArithShift, rightLogShift
22640 *
22641 * @param {number | BigNumber | Array | Matrix} x First value to and
22642 * @param {number | BigNumber | Array | Matrix} y Second value to and
22643 * @return {number | BigNumber | Array | Matrix} AND of `x` and `y`
22644 */
22645
22646 var bitAnd = typed(bitAnd_name, {
22647 'number, number': bitAndNumber,
22648 'BigNumber, BigNumber': bitAndBigNumber,
22649 'SparseMatrix, SparseMatrix': function SparseMatrixSparseMatrix(x, y) {
22650 return algorithm06(x, y, bitAnd, false);
22651 },
22652 'SparseMatrix, DenseMatrix': function SparseMatrixDenseMatrix(x, y) {
22653 return algorithm02(y, x, bitAnd, true);
22654 },
22655 'DenseMatrix, SparseMatrix': function DenseMatrixSparseMatrix(x, y) {
22656 return algorithm02(x, y, bitAnd, false);
22657 },
22658 'DenseMatrix, DenseMatrix': function DenseMatrixDenseMatrix(x, y) {
22659 return algorithm13(x, y, bitAnd);
22660 },
22661 'Array, Array': function ArrayArray(x, y) {
22662 // use matrix implementation
22663 return bitAnd(matrix(x), matrix(y)).valueOf();
22664 },
22665 'Array, Matrix': function ArrayMatrix(x, y) {
22666 // use matrix implementation
22667 return bitAnd(matrix(x), y);
22668 },
22669 'Matrix, Array': function MatrixArray(x, y) {
22670 // use matrix implementation
22671 return bitAnd(x, matrix(y));
22672 },
22673 'SparseMatrix, any': function SparseMatrixAny(x, y) {
22674 return algorithm11(x, y, bitAnd, false);
22675 },
22676 'DenseMatrix, any': function DenseMatrixAny(x, y) {
22677 return algorithm14(x, y, bitAnd, false);
22678 },
22679 'any, SparseMatrix': function anySparseMatrix(x, y) {
22680 return algorithm11(y, x, bitAnd, true);
22681 },
22682 'any, DenseMatrix': function anyDenseMatrix(x, y) {
22683 return algorithm14(y, x, bitAnd, true);
22684 },
22685 'Array, any': function ArrayAny(x, y) {
22686 // use matrix implementation
22687 return algorithm14(matrix(x), y, bitAnd, false).valueOf();
22688 },
22689 'any, Array': function anyArray(x, y) {
22690 // use matrix implementation
22691 return algorithm14(matrix(y), x, bitAnd, true).valueOf();
22692 }
22693 });
22694 return bitAnd;
22695});
22696// CONCATENATED MODULE: ./src/function/bitwise/bitNot.js
22697
22698
22699
22700
22701var bitNot_name = 'bitNot';
22702var bitNot_dependencies = ['typed'];
22703var createBitNot =
22704/* #__PURE__ */
22705Object(factory["a" /* factory */])(bitNot_name, bitNot_dependencies, function (_ref) {
22706 var typed = _ref.typed;
22707
22708 /**
22709 * Bitwise NOT value, `~x`.
22710 * For matrices, the function is evaluated element wise.
22711 * For units, the function is evaluated on the best prefix base.
22712 *
22713 * Syntax:
22714 *
22715 * math.bitNot(x)
22716 *
22717 * Examples:
22718 *
22719 * math.bitNot(1) // returns number -2
22720 *
22721 * math.bitNot([2, -3, 4]) // returns Array [-3, 2, 5]
22722 *
22723 * See also:
22724 *
22725 * bitAnd, bitOr, bitXor, leftShift, rightArithShift, rightLogShift
22726 *
22727 * @param {number | BigNumber | Array | Matrix} x Value to not
22728 * @return {number | BigNumber | Array | Matrix} NOT of `x`
22729 */
22730 var bitNot = typed(bitNot_name, {
22731 number: bitNotNumber,
22732 BigNumber: bitNotBigNumber,
22733 'Array | Matrix': function ArrayMatrix(x) {
22734 return deepMap(x, bitNot);
22735 }
22736 });
22737 return bitNot;
22738});
22739// CONCATENATED MODULE: ./src/function/bitwise/bitOr.js
22740
22741
22742
22743
22744
22745
22746
22747
22748var bitOr_name = 'bitOr';
22749var bitOr_dependencies = ['typed', 'matrix', 'equalScalar', 'DenseMatrix'];
22750var createBitOr =
22751/* #__PURE__ */
22752Object(factory["a" /* factory */])(bitOr_name, bitOr_dependencies, function (_ref) {
22753 var typed = _ref.typed,
22754 matrix = _ref.matrix,
22755 equalScalar = _ref.equalScalar,
22756 DenseMatrix = _ref.DenseMatrix;
22757 var algorithm01 = createAlgorithm01({
22758 typed: typed
22759 });
22760 var algorithm04 = createAlgorithm04({
22761 typed: typed,
22762 equalScalar: equalScalar
22763 });
22764 var algorithm10 = createAlgorithm10({
22765 typed: typed,
22766 DenseMatrix: DenseMatrix
22767 });
22768 var algorithm13 = createAlgorithm13({
22769 typed: typed
22770 });
22771 var algorithm14 = createAlgorithm14({
22772 typed: typed
22773 });
22774 /**
22775 * Bitwise OR two values, `x | y`.
22776 * For matrices, the function is evaluated element wise.
22777 * For units, the function is evaluated on the lowest print base.
22778 *
22779 * Syntax:
22780 *
22781 * math.bitOr(x, y)
22782 *
22783 * Examples:
22784 *
22785 * math.bitOr(1, 2) // returns number 3
22786 *
22787 * math.bitOr([1, 2, 3], 4) // returns Array [5, 6, 7]
22788 *
22789 * See also:
22790 *
22791 * bitAnd, bitNot, bitXor, leftShift, rightArithShift, rightLogShift
22792 *
22793 * @param {number | BigNumber | Array | Matrix} x First value to or
22794 * @param {number | BigNumber | Array | Matrix} y Second value to or
22795 * @return {number | BigNumber | Array | Matrix} OR of `x` and `y`
22796 */
22797
22798 var bitOr = typed(bitOr_name, {
22799 'number, number': bitOrNumber,
22800 'BigNumber, BigNumber': bitOrBigNumber,
22801 'SparseMatrix, SparseMatrix': function SparseMatrixSparseMatrix(x, y) {
22802 return algorithm04(x, y, bitOr);
22803 },
22804 'SparseMatrix, DenseMatrix': function SparseMatrixDenseMatrix(x, y) {
22805 return algorithm01(y, x, bitOr, true);
22806 },
22807 'DenseMatrix, SparseMatrix': function DenseMatrixSparseMatrix(x, y) {
22808 return algorithm01(x, y, bitOr, false);
22809 },
22810 'DenseMatrix, DenseMatrix': function DenseMatrixDenseMatrix(x, y) {
22811 return algorithm13(x, y, bitOr);
22812 },
22813 'Array, Array': function ArrayArray(x, y) {
22814 // use matrix implementation
22815 return bitOr(matrix(x), matrix(y)).valueOf();
22816 },
22817 'Array, Matrix': function ArrayMatrix(x, y) {
22818 // use matrix implementation
22819 return bitOr(matrix(x), y);
22820 },
22821 'Matrix, Array': function MatrixArray(x, y) {
22822 // use matrix implementation
22823 return bitOr(x, matrix(y));
22824 },
22825 'SparseMatrix, any': function SparseMatrixAny(x, y) {
22826 return algorithm10(x, y, bitOr, false);
22827 },
22828 'DenseMatrix, any': function DenseMatrixAny(x, y) {
22829 return algorithm14(x, y, bitOr, false);
22830 },
22831 'any, SparseMatrix': function anySparseMatrix(x, y) {
22832 return algorithm10(y, x, bitOr, true);
22833 },
22834 'any, DenseMatrix': function anyDenseMatrix(x, y) {
22835 return algorithm14(y, x, bitOr, true);
22836 },
22837 'Array, any': function ArrayAny(x, y) {
22838 // use matrix implementation
22839 return algorithm14(matrix(x), y, bitOr, false).valueOf();
22840 },
22841 'any, Array': function anyArray(x, y) {
22842 // use matrix implementation
22843 return algorithm14(matrix(y), x, bitOr, true).valueOf();
22844 }
22845 });
22846 return bitOr;
22847});
22848// CONCATENATED MODULE: ./src/type/matrix/utils/algorithm07.js
22849
22850
22851var algorithm07_name = 'algorithm07';
22852var algorithm07_dependencies = ['typed', 'DenseMatrix'];
22853var createAlgorithm07 =
22854/* #__PURE__ */
22855Object(factory["a" /* factory */])(algorithm07_name, algorithm07_dependencies, function (_ref) {
22856 var typed = _ref.typed,
22857 DenseMatrix = _ref.DenseMatrix;
22858
22859 /**
22860 * Iterates over SparseMatrix A and SparseMatrix B items (zero and nonzero) and invokes the callback function f(Aij, Bij).
22861 * Callback function invoked MxN times.
22862 *
22863 * C(i,j) = f(Aij, Bij)
22864 *
22865 * @param {Matrix} a The SparseMatrix instance (A)
22866 * @param {Matrix} b The SparseMatrix instance (B)
22867 * @param {Function} callback The f(Aij,Bij) operation to invoke
22868 *
22869 * @return {Matrix} DenseMatrix (C)
22870 *
22871 * see https://github.com/josdejong/mathjs/pull/346#issuecomment-97620294
22872 */
22873 return function algorithm07(a, b, callback) {
22874 // sparse matrix arrays
22875 var asize = a._size;
22876 var adt = a._datatype; // sparse matrix arrays
22877
22878 var bsize = b._size;
22879 var bdt = b._datatype; // validate dimensions
22880
22881 if (asize.length !== bsize.length) {
22882 throw new DimensionError["a" /* DimensionError */](asize.length, bsize.length);
22883 } // check rows & columns
22884
22885
22886 if (asize[0] !== bsize[0] || asize[1] !== bsize[1]) {
22887 throw new RangeError('Dimension mismatch. Matrix A (' + asize + ') must match Matrix B (' + bsize + ')');
22888 } // rows & columns
22889
22890
22891 var rows = asize[0];
22892 var columns = asize[1]; // datatype
22893
22894 var dt; // zero value
22895
22896 var zero = 0; // callback signature to use
22897
22898 var cf = callback; // process data types
22899
22900 if (typeof adt === 'string' && adt === bdt) {
22901 // datatype
22902 dt = adt; // convert 0 to the same datatype
22903
22904 zero = typed.convert(0, dt); // callback
22905
22906 cf = typed.find(callback, [dt, dt]);
22907 } // vars
22908
22909
22910 var i, j; // result arrays
22911
22912 var cdata = []; // initialize c
22913
22914 for (i = 0; i < rows; i++) {
22915 cdata[i] = [];
22916 } // matrix
22917
22918
22919 var c = new DenseMatrix({
22920 data: cdata,
22921 size: [rows, columns],
22922 datatype: dt
22923 }); // workspaces
22924
22925 var xa = [];
22926 var xb = []; // marks indicating we have a value in x for a given column
22927
22928 var wa = [];
22929 var wb = []; // loop columns
22930
22931 for (j = 0; j < columns; j++) {
22932 // columns mark
22933 var mark = j + 1; // scatter the values of A(:,j) into workspace
22934
22935 _scatter(a, j, wa, xa, mark); // scatter the values of B(:,j) into workspace
22936
22937
22938 _scatter(b, j, wb, xb, mark); // loop rows
22939
22940
22941 for (i = 0; i < rows; i++) {
22942 // matrix values @ i,j
22943 var va = wa[i] === mark ? xa[i] : zero;
22944 var vb = wb[i] === mark ? xb[i] : zero; // invoke callback
22945
22946 cdata[i][j] = cf(va, vb);
22947 }
22948 } // return sparse matrix
22949
22950
22951 return c;
22952 };
22953
22954 function _scatter(m, j, w, x, mark) {
22955 // a arrays
22956 var values = m._values;
22957 var index = m._index;
22958 var ptr = m._ptr; // loop values in column j
22959
22960 for (var k = ptr[j], k1 = ptr[j + 1]; k < k1; k++) {
22961 // row
22962 var i = index[k]; // update workspace
22963
22964 w[i] = mark;
22965 x[i] = values[k];
22966 }
22967 }
22968});
22969// CONCATENATED MODULE: ./src/function/bitwise/bitXor.js
22970
22971
22972
22973
22974
22975
22976
22977
22978var bitXor_name = 'bitXor';
22979var bitXor_dependencies = ['typed', 'matrix', 'DenseMatrix'];
22980var createBitXor =
22981/* #__PURE__ */
22982Object(factory["a" /* factory */])(bitXor_name, bitXor_dependencies, function (_ref) {
22983 var typed = _ref.typed,
22984 matrix = _ref.matrix,
22985 DenseMatrix = _ref.DenseMatrix;
22986 var algorithm03 = createAlgorithm03({
22987 typed: typed
22988 });
22989 var algorithm07 = createAlgorithm07({
22990 typed: typed,
22991 DenseMatrix: DenseMatrix
22992 });
22993 var algorithm12 = createAlgorithm12({
22994 typed: typed,
22995 DenseMatrix: DenseMatrix
22996 });
22997 var algorithm13 = createAlgorithm13({
22998 typed: typed
22999 });
23000 var algorithm14 = createAlgorithm14({
23001 typed: typed
23002 });
23003 /**
23004 * Bitwise XOR two values, `x ^ y`.
23005 * For matrices, the function is evaluated element wise.
23006 *
23007 * Syntax:
23008 *
23009 * math.bitXor(x, y)
23010 *
23011 * Examples:
23012 *
23013 * math.bitXor(1, 2) // returns number 3
23014 *
23015 * math.bitXor([2, 3, 4], 4) // returns Array [6, 7, 0]
23016 *
23017 * See also:
23018 *
23019 * bitAnd, bitNot, bitOr, leftShift, rightArithShift, rightLogShift
23020 *
23021 * @param {number | BigNumber | Array | Matrix} x First value to xor
23022 * @param {number | BigNumber | Array | Matrix} y Second value to xor
23023 * @return {number | BigNumber | Array | Matrix} XOR of `x` and `y`
23024 */
23025
23026 var bitXor = typed(bitXor_name, {
23027 'number, number': bitXorNumber,
23028 'BigNumber, BigNumber': bitwise_bitXor,
23029 'SparseMatrix, SparseMatrix': function SparseMatrixSparseMatrix(x, y) {
23030 return algorithm07(x, y, bitXor);
23031 },
23032 'SparseMatrix, DenseMatrix': function SparseMatrixDenseMatrix(x, y) {
23033 return algorithm03(y, x, bitXor, true);
23034 },
23035 'DenseMatrix, SparseMatrix': function DenseMatrixSparseMatrix(x, y) {
23036 return algorithm03(x, y, bitXor, false);
23037 },
23038 'DenseMatrix, DenseMatrix': function DenseMatrixDenseMatrix(x, y) {
23039 return algorithm13(x, y, bitXor);
23040 },
23041 'Array, Array': function ArrayArray(x, y) {
23042 // use matrix implementation
23043 return bitXor(matrix(x), matrix(y)).valueOf();
23044 },
23045 'Array, Matrix': function ArrayMatrix(x, y) {
23046 // use matrix implementation
23047 return bitXor(matrix(x), y);
23048 },
23049 'Matrix, Array': function MatrixArray(x, y) {
23050 // use matrix implementation
23051 return bitXor(x, matrix(y));
23052 },
23053 'SparseMatrix, any': function SparseMatrixAny(x, y) {
23054 return algorithm12(x, y, bitXor, false);
23055 },
23056 'DenseMatrix, any': function DenseMatrixAny(x, y) {
23057 return algorithm14(x, y, bitXor, false);
23058 },
23059 'any, SparseMatrix': function anySparseMatrix(x, y) {
23060 return algorithm12(y, x, bitXor, true);
23061 },
23062 'any, DenseMatrix': function anyDenseMatrix(x, y) {
23063 return algorithm14(y, x, bitXor, true);
23064 },
23065 'Array, any': function ArrayAny(x, y) {
23066 // use matrix implementation
23067 return algorithm14(matrix(x), y, bitXor, false).valueOf();
23068 },
23069 'any, Array': function anyArray(x, y) {
23070 // use matrix implementation
23071 return algorithm14(matrix(y), x, bitXor, true).valueOf();
23072 }
23073 });
23074 return bitXor;
23075});
23076// CONCATENATED MODULE: ./src/function/complex/arg.js
23077
23078
23079var arg_name = 'arg';
23080var arg_dependencies = ['typed'];
23081var createArg =
23082/* #__PURE__ */
23083Object(factory["a" /* factory */])(arg_name, arg_dependencies, function (_ref) {
23084 var typed = _ref.typed;
23085
23086 /**
23087 * Compute the argument of a complex value.
23088 * For a complex number `a + bi`, the argument is computed as `atan2(b, a)`.
23089 *
23090 * For matrices, the function is evaluated element wise.
23091 *
23092 * Syntax:
23093 *
23094 * math.arg(x)
23095 *
23096 * Examples:
23097 *
23098 * const a = math.complex(2, 2)
23099 * math.arg(a) / math.pi // returns number 0.25
23100 *
23101 * const b = math.complex('2 + 3i')
23102 * math.arg(b) // returns number 0.982793723247329
23103 * math.atan2(3, 2) // returns number 0.982793723247329
23104 *
23105 * See also:
23106 *
23107 * re, im, conj, abs
23108 *
23109 * @param {number | BigNumber | Complex | Array | Matrix} x
23110 * A complex number or array with complex numbers
23111 * @return {number | BigNumber | Array | Matrix} The argument of x
23112 */
23113 var arg = typed(arg_name, {
23114 number: function number(x) {
23115 return Math.atan2(0, x);
23116 },
23117 BigNumber: function BigNumber(x) {
23118 return x.constructor.atan2(0, x);
23119 },
23120 Complex: function Complex(x) {
23121 return x.arg();
23122 },
23123 // TODO: implement BigNumber support for function arg
23124 'Array | Matrix': function ArrayMatrix(x) {
23125 return deepMap(x, arg);
23126 }
23127 });
23128 return arg;
23129});
23130// CONCATENATED MODULE: ./src/function/complex/conj.js
23131
23132
23133var conj_name = 'conj';
23134var conj_dependencies = ['typed'];
23135var createConj =
23136/* #__PURE__ */
23137Object(factory["a" /* factory */])(conj_name, conj_dependencies, function (_ref) {
23138 var typed = _ref.typed;
23139
23140 /**
23141 * Compute the complex conjugate of a complex value.
23142 * If `x = a+bi`, the complex conjugate of `x` is `a - bi`.
23143 *
23144 * For matrices, the function is evaluated element wise.
23145 *
23146 * Syntax:
23147 *
23148 * math.conj(x)
23149 *
23150 * Examples:
23151 *
23152 * math.conj(math.complex('2 + 3i')) // returns Complex 2 - 3i
23153 * math.conj(math.complex('2 - 3i')) // returns Complex 2 + 3i
23154 * math.conj(math.complex('-5.2i')) // returns Complex 5.2i
23155 *
23156 * See also:
23157 *
23158 * re, im, arg, abs
23159 *
23160 * @param {number | BigNumber | Complex | Array | Matrix} x
23161 * A complex number or array with complex numbers
23162 * @return {number | BigNumber | Complex | Array | Matrix}
23163 * The complex conjugate of x
23164 */
23165 var conj = typed(conj_name, {
23166 number: function number(x) {
23167 return x;
23168 },
23169 BigNumber: function BigNumber(x) {
23170 return x;
23171 },
23172 Complex: function Complex(x) {
23173 return x.conjugate();
23174 },
23175 'Array | Matrix': function ArrayMatrix(x) {
23176 return deepMap(x, conj);
23177 }
23178 });
23179 return conj;
23180});
23181// CONCATENATED MODULE: ./src/function/complex/im.js
23182
23183
23184var im_name = 'im';
23185var im_dependencies = ['typed'];
23186var createIm =
23187/* #__PURE__ */
23188Object(factory["a" /* factory */])(im_name, im_dependencies, function (_ref) {
23189 var typed = _ref.typed;
23190
23191 /**
23192 * Get the imaginary part of a complex number.
23193 * For a complex number `a + bi`, the function returns `b`.
23194 *
23195 * For matrices, the function is evaluated element wise.
23196 *
23197 * Syntax:
23198 *
23199 * math.im(x)
23200 *
23201 * Examples:
23202 *
23203 * const a = math.complex(2, 3)
23204 * math.re(a) // returns number 2
23205 * math.im(a) // returns number 3
23206 *
23207 * math.re(math.complex('-5.2i')) // returns number -5.2
23208 * math.re(math.complex(2.4)) // returns number 0
23209 *
23210 * See also:
23211 *
23212 * re, conj, abs, arg
23213 *
23214 * @param {number | BigNumber | Complex | Array | Matrix} x
23215 * A complex number or array with complex numbers
23216 * @return {number | BigNumber | Array | Matrix} The imaginary part of x
23217 */
23218 var im = typed(im_name, {
23219 number: function number(x) {
23220 return 0;
23221 },
23222 BigNumber: function BigNumber(x) {
23223 return x.mul(0);
23224 },
23225 Complex: function Complex(x) {
23226 return x.im;
23227 },
23228 'Array | Matrix': function ArrayMatrix(x) {
23229 return deepMap(x, im);
23230 }
23231 });
23232 return im;
23233});
23234// CONCATENATED MODULE: ./src/function/complex/re.js
23235
23236
23237var re_name = 're';
23238var re_dependencies = ['typed'];
23239var createRe =
23240/* #__PURE__ */
23241Object(factory["a" /* factory */])(re_name, re_dependencies, function (_ref) {
23242 var typed = _ref.typed;
23243
23244 /**
23245 * Get the real part of a complex number.
23246 * For a complex number `a + bi`, the function returns `a`.
23247 *
23248 * For matrices, the function is evaluated element wise.
23249 *
23250 * Syntax:
23251 *
23252 * math.re(x)
23253 *
23254 * Examples:
23255 *
23256 * const a = math.complex(2, 3)
23257 * math.re(a) // returns number 2
23258 * math.im(a) // returns number 3
23259 *
23260 * math.re(math.complex('-5.2i')) // returns number 0
23261 * math.re(math.complex(2.4)) // returns number 2.4
23262 *
23263 * See also:
23264 *
23265 * im, conj, abs, arg
23266 *
23267 * @param {number | BigNumber | Complex | Array | Matrix} x
23268 * A complex number or array with complex numbers
23269 * @return {number | BigNumber | Array | Matrix} The real part of x
23270 */
23271 var re = typed(re_name, {
23272 number: function number(x) {
23273 return x;
23274 },
23275 BigNumber: function BigNumber(x) {
23276 return x;
23277 },
23278 Complex: function Complex(x) {
23279 return x.re;
23280 },
23281 'Array | Matrix': function ArrayMatrix(x) {
23282 return deepMap(x, re);
23283 }
23284 });
23285 return re;
23286});
23287// CONCATENATED MODULE: ./src/plain/number/logical.js
23288var logical_n1 = 'number';
23289var logical_n2 = 'number, number';
23290function notNumber(x) {
23291 return !x;
23292}
23293notNumber.signature = logical_n1;
23294function orNumber(x, y) {
23295 return !!(x || y);
23296}
23297orNumber.signature = logical_n2;
23298function xorNumber(x, y) {
23299 return !!x !== !!y;
23300}
23301xorNumber.signature = logical_n2;
23302function andNumber(x, y) {
23303 return !!(x && y);
23304}
23305andNumber.signature = logical_n2;
23306// CONCATENATED MODULE: ./src/function/logical/not.js
23307
23308
23309
23310var not_name = 'not';
23311var not_dependencies = ['typed'];
23312var createNot =
23313/* #__PURE__ */
23314Object(factory["a" /* factory */])(not_name, not_dependencies, function (_ref) {
23315 var typed = _ref.typed;
23316
23317 /**
23318 * Logical `not`. Flips boolean value of a given parameter.
23319 * For matrices, the function is evaluated element wise.
23320 *
23321 * Syntax:
23322 *
23323 * math.not(x)
23324 *
23325 * Examples:
23326 *
23327 * math.not(2) // returns false
23328 * math.not(0) // returns true
23329 * math.not(true) // returns false
23330 *
23331 * a = [2, -7, 0]
23332 * math.not(a) // returns [false, false, true]
23333 *
23334 * See also:
23335 *
23336 * and, or, xor
23337 *
23338 * @param {number | BigNumber | Complex | Unit | Array | Matrix} x First value to check
23339 * @return {boolean | Array | Matrix}
23340 * Returns true when input is a zero or empty value.
23341 */
23342 var not = typed(not_name, {
23343 number: notNumber,
23344 Complex: function Complex(x) {
23345 return x.re === 0 && x.im === 0;
23346 },
23347 BigNumber: function BigNumber(x) {
23348 return x.isZero() || x.isNaN();
23349 },
23350 Unit: function Unit(x) {
23351 return x.value !== null ? not(x.value) : true;
23352 },
23353 'Array | Matrix': function ArrayMatrix(x) {
23354 return deepMap(x, not);
23355 }
23356 });
23357 return not;
23358});
23359// CONCATENATED MODULE: ./src/function/logical/or.js
23360
23361
23362
23363
23364
23365
23366
23367var or_name = 'or';
23368var or_dependencies = ['typed', 'matrix', 'equalScalar', 'DenseMatrix'];
23369var createOr =
23370/* #__PURE__ */
23371Object(factory["a" /* factory */])(or_name, or_dependencies, function (_ref) {
23372 var typed = _ref.typed,
23373 matrix = _ref.matrix,
23374 equalScalar = _ref.equalScalar,
23375 DenseMatrix = _ref.DenseMatrix;
23376 var algorithm03 = createAlgorithm03({
23377 typed: typed
23378 });
23379 var algorithm05 = createAlgorithm05({
23380 typed: typed,
23381 equalScalar: equalScalar
23382 });
23383 var algorithm12 = createAlgorithm12({
23384 typed: typed,
23385 DenseMatrix: DenseMatrix
23386 });
23387 var algorithm13 = createAlgorithm13({
23388 typed: typed
23389 });
23390 var algorithm14 = createAlgorithm14({
23391 typed: typed
23392 });
23393 /**
23394 * Logical `or`. Test if at least one value is defined with a nonzero/nonempty value.
23395 * For matrices, the function is evaluated element wise.
23396 *
23397 * Syntax:
23398 *
23399 * math.or(x, y)
23400 *
23401 * Examples:
23402 *
23403 * math.or(2, 4) // returns true
23404 *
23405 * a = [2, 5, 0]
23406 * b = [0, 22, 0]
23407 * c = 0
23408 *
23409 * math.or(a, b) // returns [true, true, false]
23410 * math.or(b, c) // returns [false, true, false]
23411 *
23412 * See also:
23413 *
23414 * and, not, xor
23415 *
23416 * @param {number | BigNumber | Complex | Unit | Array | Matrix} x First value to check
23417 * @param {number | BigNumber | Complex | Unit | Array | Matrix} y Second value to check
23418 * @return {boolean | Array | Matrix}
23419 * Returns true when one of the inputs is defined with a nonzero/nonempty value.
23420 */
23421
23422 var or = typed(or_name, {
23423 'number, number': orNumber,
23424 'Complex, Complex': function ComplexComplex(x, y) {
23425 return x.re !== 0 || x.im !== 0 || y.re !== 0 || y.im !== 0;
23426 },
23427 'BigNumber, BigNumber': function BigNumberBigNumber(x, y) {
23428 return !x.isZero() && !x.isNaN() || !y.isZero() && !y.isNaN();
23429 },
23430 'Unit, Unit': function UnitUnit(x, y) {
23431 return or(x.value || 0, y.value || 0);
23432 },
23433 'SparseMatrix, SparseMatrix': function SparseMatrixSparseMatrix(x, y) {
23434 return algorithm05(x, y, or);
23435 },
23436 'SparseMatrix, DenseMatrix': function SparseMatrixDenseMatrix(x, y) {
23437 return algorithm03(y, x, or, true);
23438 },
23439 'DenseMatrix, SparseMatrix': function DenseMatrixSparseMatrix(x, y) {
23440 return algorithm03(x, y, or, false);
23441 },
23442 'DenseMatrix, DenseMatrix': function DenseMatrixDenseMatrix(x, y) {
23443 return algorithm13(x, y, or);
23444 },
23445 'Array, Array': function ArrayArray(x, y) {
23446 // use matrix implementation
23447 return or(matrix(x), matrix(y)).valueOf();
23448 },
23449 'Array, Matrix': function ArrayMatrix(x, y) {
23450 // use matrix implementation
23451 return or(matrix(x), y);
23452 },
23453 'Matrix, Array': function MatrixArray(x, y) {
23454 // use matrix implementation
23455 return or(x, matrix(y));
23456 },
23457 'SparseMatrix, any': function SparseMatrixAny(x, y) {
23458 return algorithm12(x, y, or, false);
23459 },
23460 'DenseMatrix, any': function DenseMatrixAny(x, y) {
23461 return algorithm14(x, y, or, false);
23462 },
23463 'any, SparseMatrix': function anySparseMatrix(x, y) {
23464 return algorithm12(y, x, or, true);
23465 },
23466 'any, DenseMatrix': function anyDenseMatrix(x, y) {
23467 return algorithm14(y, x, or, true);
23468 },
23469 'Array, any': function ArrayAny(x, y) {
23470 // use matrix implementation
23471 return algorithm14(matrix(x), y, or, false).valueOf();
23472 },
23473 'any, Array': function anyArray(x, y) {
23474 // use matrix implementation
23475 return algorithm14(matrix(y), x, or, true).valueOf();
23476 }
23477 });
23478 return or;
23479});
23480// CONCATENATED MODULE: ./src/function/logical/xor.js
23481
23482
23483
23484
23485
23486
23487
23488var xor_name = 'xor';
23489var xor_dependencies = ['typed', 'matrix', 'DenseMatrix'];
23490var createXor =
23491/* #__PURE__ */
23492Object(factory["a" /* factory */])(xor_name, xor_dependencies, function (_ref) {
23493 var typed = _ref.typed,
23494 matrix = _ref.matrix,
23495 DenseMatrix = _ref.DenseMatrix;
23496 var algorithm03 = createAlgorithm03({
23497 typed: typed
23498 });
23499 var algorithm07 = createAlgorithm07({
23500 typed: typed,
23501 DenseMatrix: DenseMatrix
23502 });
23503 var algorithm12 = createAlgorithm12({
23504 typed: typed,
23505 DenseMatrix: DenseMatrix
23506 });
23507 var algorithm13 = createAlgorithm13({
23508 typed: typed
23509 });
23510 var algorithm14 = createAlgorithm14({
23511 typed: typed
23512 });
23513 /**
23514 * Logical `xor`. Test whether one and only one value is defined with a nonzero/nonempty value.
23515 * For matrices, the function is evaluated element wise.
23516 *
23517 * Syntax:
23518 *
23519 * math.xor(x, y)
23520 *
23521 * Examples:
23522 *
23523 * math.xor(2, 4) // returns false
23524 *
23525 * a = [2, 0, 0]
23526 * b = [2, 7, 0]
23527 * c = 0
23528 *
23529 * math.xor(a, b) // returns [false, true, false]
23530 * math.xor(a, c) // returns [true, false, false]
23531 *
23532 * See also:
23533 *
23534 * and, not, or
23535 *
23536 * @param {number | BigNumber | Complex | Unit | Array | Matrix} x First value to check
23537 * @param {number | BigNumber | Complex | Unit | Array | Matrix} y Second value to check
23538 * @return {boolean | Array | Matrix}
23539 * Returns true when one and only one input is defined with a nonzero/nonempty value.
23540 */
23541
23542 var xor = typed(xor_name, {
23543 'number, number': xorNumber,
23544 'Complex, Complex': function ComplexComplex(x, y) {
23545 return (x.re !== 0 || x.im !== 0) !== (y.re !== 0 || y.im !== 0);
23546 },
23547 'BigNumber, BigNumber': function BigNumberBigNumber(x, y) {
23548 return (!x.isZero() && !x.isNaN()) !== (!y.isZero() && !y.isNaN());
23549 },
23550 'Unit, Unit': function UnitUnit(x, y) {
23551 return xor(x.value || 0, y.value || 0);
23552 },
23553 'SparseMatrix, SparseMatrix': function SparseMatrixSparseMatrix(x, y) {
23554 return algorithm07(x, y, xor);
23555 },
23556 'SparseMatrix, DenseMatrix': function SparseMatrixDenseMatrix(x, y) {
23557 return algorithm03(y, x, xor, true);
23558 },
23559 'DenseMatrix, SparseMatrix': function DenseMatrixSparseMatrix(x, y) {
23560 return algorithm03(x, y, xor, false);
23561 },
23562 'DenseMatrix, DenseMatrix': function DenseMatrixDenseMatrix(x, y) {
23563 return algorithm13(x, y, xor);
23564 },
23565 'Array, Array': function ArrayArray(x, y) {
23566 // use matrix implementation
23567 return xor(matrix(x), matrix(y)).valueOf();
23568 },
23569 'Array, Matrix': function ArrayMatrix(x, y) {
23570 // use matrix implementation
23571 return xor(matrix(x), y);
23572 },
23573 'Matrix, Array': function MatrixArray(x, y) {
23574 // use matrix implementation
23575 return xor(x, matrix(y));
23576 },
23577 'SparseMatrix, any': function SparseMatrixAny(x, y) {
23578 return algorithm12(x, y, xor, false);
23579 },
23580 'DenseMatrix, any': function DenseMatrixAny(x, y) {
23581 return algorithm14(x, y, xor, false);
23582 },
23583 'any, SparseMatrix': function anySparseMatrix(x, y) {
23584 return algorithm12(y, x, xor, true);
23585 },
23586 'any, DenseMatrix': function anyDenseMatrix(x, y) {
23587 return algorithm14(y, x, xor, true);
23588 },
23589 'Array, any': function ArrayAny(x, y) {
23590 // use matrix implementation
23591 return algorithm14(matrix(x), y, xor, false).valueOf();
23592 },
23593 'any, Array': function anyArray(x, y) {
23594 // use matrix implementation
23595 return algorithm14(matrix(y), x, xor, true).valueOf();
23596 }
23597 });
23598 return xor;
23599});
23600// CONCATENATED MODULE: ./src/function/matrix/concat.js
23601
23602
23603
23604
23605
23606
23607var concat_name = 'concat';
23608var concat_dependencies = ['typed', 'matrix', 'isInteger'];
23609var createConcat =
23610/* #__PURE__ */
23611Object(factory["a" /* factory */])(concat_name, concat_dependencies, function (_ref) {
23612 var typed = _ref.typed,
23613 matrix = _ref.matrix,
23614 isInteger = _ref.isInteger;
23615
23616 /**
23617 * Concatenate two or more matrices.
23618 *
23619 * Syntax:
23620 *
23621 * math.concat(A, B, C, ...)
23622 * math.concat(A, B, C, ..., dim)
23623 *
23624 * Where:
23625 *
23626 * - `dim: number` is a zero-based dimension over which to concatenate the matrices.
23627 * By default the last dimension of the matrices.
23628 *
23629 * Examples:
23630 *
23631 * const A = [[1, 2], [5, 6]]
23632 * const B = [[3, 4], [7, 8]]
23633 *
23634 * math.concat(A, B) // returns [[1, 2, 3, 4], [5, 6, 7, 8]]
23635 * math.concat(A, B, 0) // returns [[1, 2], [5, 6], [3, 4], [7, 8]]
23636 * math.concat('hello', ' ', 'world') // returns 'hello world'
23637 *
23638 * See also:
23639 *
23640 * size, squeeze, subset, transpose
23641 *
23642 * @param {... Array | Matrix} args Two or more matrices
23643 * @return {Array | Matrix} Concatenated matrix
23644 */
23645 return typed(concat_name, {
23646 // TODO: change signature to '...Array | Matrix, dim?' when supported
23647 '...Array | Matrix | number | BigNumber': function ArrayMatrixNumberBigNumber(args) {
23648 var i;
23649 var len = args.length;
23650 var dim = -1; // zero-based dimension
23651
23652 var prevDim;
23653 var asMatrix = false;
23654 var matrices = []; // contains multi dimensional arrays
23655
23656 for (i = 0; i < len; i++) {
23657 var arg = args[i]; // test whether we need to return a Matrix (if not we return an Array)
23658
23659 if (Object(is["v" /* isMatrix */])(arg)) {
23660 asMatrix = true;
23661 }
23662
23663 if (Object(is["y" /* isNumber */])(arg) || Object(is["e" /* isBigNumber */])(arg)) {
23664 if (i !== len - 1) {
23665 throw new Error('Dimension must be specified as last argument');
23666 } // last argument contains the dimension on which to concatenate
23667
23668
23669 prevDim = dim;
23670 dim = arg.valueOf(); // change BigNumber to number
23671
23672 if (!isInteger(dim)) {
23673 throw new TypeError('Integer number expected for dimension');
23674 }
23675
23676 if (dim < 0 || i > 0 && dim > prevDim) {
23677 // TODO: would be more clear when throwing a DimensionError here
23678 throw new IndexError["a" /* IndexError */](dim, prevDim + 1);
23679 }
23680 } else {
23681 // this is a matrix or array
23682 var m = Object(utils_object["a" /* clone */])(arg).valueOf();
23683 var size = Object(utils_array["a" /* arraySize */])(m);
23684 matrices[i] = m;
23685 prevDim = dim;
23686 dim = size.length - 1; // verify whether each of the matrices has the same number of dimensions
23687
23688 if (i > 0 && dim !== prevDim) {
23689 throw new DimensionError["a" /* DimensionError */](prevDim + 1, dim + 1);
23690 }
23691 }
23692 }
23693
23694 if (matrices.length === 0) {
23695 throw new SyntaxError('At least one matrix expected');
23696 }
23697
23698 var res = matrices.shift();
23699
23700 while (matrices.length) {
23701 res = _concat(res, matrices.shift(), dim, 0);
23702 }
23703
23704 return asMatrix ? matrix(res) : res;
23705 },
23706 '...string': function string(args) {
23707 return args.join('');
23708 }
23709 });
23710});
23711/**
23712 * Recursively concatenate two matrices.
23713 * The contents of the matrices is not cloned.
23714 * @param {Array} a Multi dimensional array
23715 * @param {Array} b Multi dimensional array
23716 * @param {number} concatDim The dimension on which to concatenate (zero-based)
23717 * @param {number} dim The current dim (zero-based)
23718 * @return {Array} c The concatenated matrix
23719 * @private
23720 */
23721
23722function _concat(a, b, concatDim, dim) {
23723 if (dim < concatDim) {
23724 // recurse into next dimension
23725 if (a.length !== b.length) {
23726 throw new DimensionError["a" /* DimensionError */](a.length, b.length);
23727 }
23728
23729 var c = [];
23730
23731 for (var i = 0; i < a.length; i++) {
23732 c[i] = _concat(a[i], b[i], concatDim, dim + 1);
23733 }
23734
23735 return c;
23736 } else {
23737 // concatenate this dimension
23738 return a.concat(b);
23739 }
23740}
23741// CONCATENATED MODULE: ./src/function/matrix/column.js
23742
23743
23744
23745var column_name = 'column';
23746var column_dependencies = ['typed', 'Index', 'matrix', 'range'];
23747var createColumn =
23748/* #__PURE__ */
23749Object(factory["a" /* factory */])(column_name, column_dependencies, function (_ref) {
23750 var typed = _ref.typed,
23751 Index = _ref.Index,
23752 matrix = _ref.matrix,
23753 range = _ref.range;
23754
23755 /**
23756 * Return a column from a Matrix.
23757 *
23758 * Syntax:
23759 *
23760 * math.column(value, index)
23761 *
23762 * Example:
23763 *
23764 * // get a column
23765 * const d = [[1, 2], [3, 4]]
23766 * math.column(d, 1) // returns [2, 4]
23767 *
23768 * See also:
23769 *
23770 * row
23771 *
23772 * @param {Array | Matrix } value An array or matrix
23773 * @param {number} column The index of the column
23774 * @return {Array | Matrix} The retrieved column
23775 */
23776 var column = typed(column_name, {
23777 'Matrix, number': _column,
23778 'Array, number': function ArrayNumber(value, column) {
23779 return _column(matrix(Object(utils_object["a" /* clone */])(value)), column).valueOf();
23780 }
23781 });
23782 return column;
23783 /**
23784 * Retrieve a column of a matrix
23785 * @param {Matrix } value A matrix
23786 * @param {number} column The index of the column
23787 * @return {Matrix} The retrieved column
23788 */
23789
23790 function _column(value, column) {
23791 // check dimensions
23792 if (value.size().length !== 2) {
23793 throw new Error('Only two dimensional matrix is supported');
23794 }
23795
23796 Object(utils_array["s" /* validateIndex */])(column, value.size()[1]);
23797 var rowRange = range(0, value.size()[0]);
23798 var index = new Index(rowRange, column);
23799 return value.subset(index);
23800 }
23801});
23802// CONCATENATED MODULE: ./src/function/matrix/cross.js
23803
23804
23805var cross_name = 'cross';
23806var cross_dependencies = ['typed', 'matrix', 'subtract', 'multiply'];
23807var createCross =
23808/* #__PURE__ */
23809Object(factory["a" /* factory */])(cross_name, cross_dependencies, function (_ref) {
23810 var typed = _ref.typed,
23811 matrix = _ref.matrix,
23812 subtract = _ref.subtract,
23813 multiply = _ref.multiply;
23814
23815 /**
23816 * Calculate the cross product for two vectors in three dimensional space.
23817 * The cross product of `A = [a1, a2, a3]` and `B = [b1, b2, b3]` is defined
23818 * as:
23819 *
23820 * cross(A, B) = [
23821 * a2 * b3 - a3 * b2,
23822 * a3 * b1 - a1 * b3,
23823 * a1 * b2 - a2 * b1
23824 * ]
23825 *
23826 * If one of the input vectors has a dimension greater than 1, the output
23827 * vector will be a 1x3 (2-dimensional) matrix.
23828 *
23829 * Syntax:
23830 *
23831 * math.cross(x, y)
23832 *
23833 * Examples:
23834 *
23835 * math.cross([1, 1, 0], [0, 1, 1]) // Returns [1, -1, 1]
23836 * math.cross([3, -3, 1], [4, 9, 2]) // Returns [-15, -2, 39]
23837 * math.cross([2, 3, 4], [5, 6, 7]) // Returns [-3, 6, -3]
23838 * math.cross([[1, 2, 3]], [[4], [5], [6]]) // Returns [[-3, 6, -3]]
23839 *
23840 * See also:
23841 *
23842 * dot, multiply
23843 *
23844 * @param {Array | Matrix} x First vector
23845 * @param {Array | Matrix} y Second vector
23846 * @return {Array | Matrix} Returns the cross product of `x` and `y`
23847 */
23848 return typed(cross_name, {
23849 'Matrix, Matrix': function MatrixMatrix(x, y) {
23850 return matrix(_cross(x.toArray(), y.toArray()));
23851 },
23852 'Matrix, Array': function MatrixArray(x, y) {
23853 return matrix(_cross(x.toArray(), y));
23854 },
23855 'Array, Matrix': function ArrayMatrix(x, y) {
23856 return matrix(_cross(x, y.toArray()));
23857 },
23858 'Array, Array': _cross
23859 });
23860 /**
23861 * Calculate the cross product for two arrays
23862 * @param {Array} x First vector
23863 * @param {Array} y Second vector
23864 * @returns {Array} Returns the cross product of x and y
23865 * @private
23866 */
23867
23868 function _cross(x, y) {
23869 var highestDimension = Math.max(Object(utils_array["a" /* arraySize */])(x).length, Object(utils_array["a" /* arraySize */])(y).length);
23870 x = Object(utils_array["p" /* squeeze */])(x);
23871 y = Object(utils_array["p" /* squeeze */])(y);
23872 var xSize = Object(utils_array["a" /* arraySize */])(x);
23873 var ySize = Object(utils_array["a" /* arraySize */])(y);
23874
23875 if (xSize.length !== 1 || ySize.length !== 1 || xSize[0] !== 3 || ySize[0] !== 3) {
23876 throw new RangeError('Vectors with length 3 expected ' + '(Size A = [' + xSize.join(', ') + '], B = [' + ySize.join(', ') + '])');
23877 }
23878
23879 var product = [subtract(multiply(x[1], y[2]), multiply(x[2], y[1])), subtract(multiply(x[2], y[0]), multiply(x[0], y[2])), subtract(multiply(x[0], y[1]), multiply(x[1], y[0]))];
23880
23881 if (highestDimension > 1) {
23882 return [product];
23883 } else {
23884 return product;
23885 }
23886 }
23887});
23888// CONCATENATED MODULE: ./src/function/matrix/diag.js
23889
23890
23891
23892
23893var diag_name = 'diag';
23894var diag_dependencies = ['typed', 'matrix', 'DenseMatrix', 'SparseMatrix'];
23895var createDiag =
23896/* #__PURE__ */
23897Object(factory["a" /* factory */])(diag_name, diag_dependencies, function (_ref) {
23898 var typed = _ref.typed,
23899 matrix = _ref.matrix,
23900 DenseMatrix = _ref.DenseMatrix,
23901 SparseMatrix = _ref.SparseMatrix;
23902
23903 /**
23904 * Create a diagonal matrix or retrieve the diagonal of a matrix
23905 *
23906 * When `x` is a vector, a matrix with vector `x` on the diagonal will be returned.
23907 * When `x` is a two dimensional matrix, the matrixes `k`th diagonal will be returned as vector.
23908 * When k is positive, the values are placed on the super diagonal.
23909 * When k is negative, the values are placed on the sub diagonal.
23910 *
23911 * Syntax:
23912 *
23913 * math.diag(X)
23914 * math.diag(X, format)
23915 * math.diag(X, k)
23916 * math.diag(X, k, format)
23917 *
23918 * Examples:
23919 *
23920 * // create a diagonal matrix
23921 * math.diag([1, 2, 3]) // returns [[1, 0, 0], [0, 2, 0], [0, 0, 3]]
23922 * math.diag([1, 2, 3], 1) // returns [[0, 1, 0, 0], [0, 0, 2, 0], [0, 0, 0, 3]]
23923 * math.diag([1, 2, 3], -1) // returns [[0, 0, 0], [1, 0, 0], [0, 2, 0], [0, 0, 3]]
23924 *
23925 * // retrieve the diagonal from a matrix
23926 * const a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
23927 * math.diag(a) // returns [1, 5, 9]
23928 *
23929 * See also:
23930 *
23931 * ones, zeros, identity
23932 *
23933 * @param {Matrix | Array} x A two dimensional matrix or a vector
23934 * @param {number | BigNumber} [k=0] The diagonal where the vector will be filled
23935 * in or retrieved.
23936 * @param {string} [format='dense'] The matrix storage format.
23937 *
23938 * @returns {Matrix | Array} Diagonal matrix from input vector, or diagonal from input matrix.
23939 */
23940 return typed(diag_name, {
23941 // FIXME: simplify this huge amount of signatures as soon as typed-function supports optional arguments
23942 Array: function Array(x) {
23943 return _diag(x, 0, Object(utils_array["a" /* arraySize */])(x), null);
23944 },
23945 'Array, number': function ArrayNumber(x, k) {
23946 return _diag(x, k, Object(utils_array["a" /* arraySize */])(x), null);
23947 },
23948 'Array, BigNumber': function ArrayBigNumber(x, k) {
23949 return _diag(x, k.toNumber(), Object(utils_array["a" /* arraySize */])(x), null);
23950 },
23951 'Array, string': function ArrayString(x, format) {
23952 return _diag(x, 0, Object(utils_array["a" /* arraySize */])(x), format);
23953 },
23954 'Array, number, string': function ArrayNumberString(x, k, format) {
23955 return _diag(x, k, Object(utils_array["a" /* arraySize */])(x), format);
23956 },
23957 'Array, BigNumber, string': function ArrayBigNumberString(x, k, format) {
23958 return _diag(x, k.toNumber(), Object(utils_array["a" /* arraySize */])(x), format);
23959 },
23960 Matrix: function Matrix(x) {
23961 return _diag(x, 0, x.size(), x.storage());
23962 },
23963 'Matrix, number': function MatrixNumber(x, k) {
23964 return _diag(x, k, x.size(), x.storage());
23965 },
23966 'Matrix, BigNumber': function MatrixBigNumber(x, k) {
23967 return _diag(x, k.toNumber(), x.size(), x.storage());
23968 },
23969 'Matrix, string': function MatrixString(x, format) {
23970 return _diag(x, 0, x.size(), format);
23971 },
23972 'Matrix, number, string': function MatrixNumberString(x, k, format) {
23973 return _diag(x, k, x.size(), format);
23974 },
23975 'Matrix, BigNumber, string': function MatrixBigNumberString(x, k, format) {
23976 return _diag(x, k.toNumber(), x.size(), format);
23977 }
23978 });
23979 /**
23980 * Creeate diagonal matrix from a vector or vice versa
23981 * @param {Array | Matrix} x
23982 * @param {number} k
23983 * @param {string} format Storage format for matrix. If null,
23984 * an Array is returned
23985 * @returns {Array | Matrix}
23986 * @private
23987 */
23988
23989 function _diag(x, k, size, format) {
23990 if (!Object(utils_number["i" /* isInteger */])(k)) {
23991 throw new TypeError('Second parameter in function diag must be an integer');
23992 }
23993
23994 var kSuper = k > 0 ? k : 0;
23995 var kSub = k < 0 ? -k : 0; // check dimensions
23996
23997 switch (size.length) {
23998 case 1:
23999 return _createDiagonalMatrix(x, k, format, size[0], kSub, kSuper);
24000
24001 case 2:
24002 return _getDiagonal(x, k, format, size, kSub, kSuper);
24003 }
24004
24005 throw new RangeError('Matrix for function diag must be 2 dimensional');
24006 }
24007
24008 function _createDiagonalMatrix(x, k, format, l, kSub, kSuper) {
24009 // matrix size
24010 var ms = [l + kSub, l + kSuper];
24011
24012 if (format && format !== 'sparse' && format !== 'dense') {
24013 throw new TypeError("Unknown matrix type ".concat(format, "\""));
24014 } // create diagonal matrix
24015
24016
24017 var m = format === 'sparse' ? SparseMatrix.diagonal(ms, x, k) : DenseMatrix.diagonal(ms, x, k); // check we need to return a matrix
24018
24019 return format !== null ? m : m.valueOf();
24020 }
24021
24022 function _getDiagonal(x, k, format, s, kSub, kSuper) {
24023 // check x is a Matrix
24024 if (Object(is["v" /* isMatrix */])(x)) {
24025 // get diagonal matrix
24026 var dm = x.diagonal(k); // check we need to return a matrix
24027
24028 if (format !== null) {
24029 // check we need to change matrix format
24030 if (format !== dm.storage()) {
24031 return matrix(dm, format);
24032 }
24033
24034 return dm;
24035 }
24036
24037 return dm.valueOf();
24038 } // vector size
24039
24040
24041 var n = Math.min(s[0] - kSub, s[1] - kSuper); // diagonal values
24042
24043 var vector = []; // loop diagonal
24044
24045 for (var i = 0; i < n; i++) {
24046 vector[i] = x[i + kSub][i + kSuper];
24047 } // check we need to return a matrix
24048
24049
24050 return format !== null ? matrix(vector) : vector;
24051 }
24052});
24053// CONCATENATED MODULE: ./src/function/matrix/eye.js
24054// TODO: function eye is removed since v5.0.0 (June 2018). Remove it some day.
24055
24056var createEye =
24057/* #__PURE__ */
24058Object(factory["a" /* factory */])('eye', [], function () {
24059 return function eye() {
24060 throw new Error('Function "eye" is renamed to "identity" since mathjs version 5.0.0. ' + 'To keep eye working, create an alias for it using "math.import({eye: math.identity}, {override: true})"');
24061 };
24062});
24063// CONCATENATED MODULE: ./src/utils/function.js
24064function function_typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { function_typeof = function _typeof(obj) { return typeof obj; }; } else { function_typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return function_typeof(obj); }
24065
24066// function utils
24067
24068/**
24069 * Memoize a given function by caching the computed result.
24070 * The cache of a memoized function can be cleared by deleting the `cache`
24071 * property of the function.
24072 *
24073 * @param {function} fn The function to be memoized.
24074 * Must be a pure function.
24075 * @param {function(args: Array)} [hasher] A custom hash builder.
24076 * Is JSON.stringify by default.
24077 * @return {function} Returns the memoized function
24078 */
24079function memoize(fn, hasher) {
24080 return function memoize() {
24081 if (function_typeof(memoize.cache) !== 'object') {
24082 memoize.cache = {};
24083 }
24084
24085 var args = [];
24086
24087 for (var i = 0; i < arguments.length; i++) {
24088 args[i] = arguments[i];
24089 }
24090
24091 var hash = hasher ? hasher(args) : JSON.stringify(args);
24092
24093 if (!(hash in memoize.cache)) {
24094 memoize.cache[hash] = fn.apply(fn, args);
24095 }
24096
24097 return memoize.cache[hash];
24098 };
24099}
24100/**
24101 * Memoize a given function by caching all results and the arguments,
24102 * and comparing against the arguments of previous results before
24103 * executing again.
24104 * This is less performant than `memoize` which calculates a hash,
24105 * which is very fast to compare. Use `memoizeCompare` only when it is
24106 * not possible to create a unique serializable hash from the function
24107 * arguments.
24108 * The isEqual function must compare two sets of arguments
24109 * and return true when equal (can be a deep equality check for example).
24110 * @param {function} fn
24111 * @param {function(a: *, b: *) : boolean} isEqual
24112 * @returns {function}
24113 */
24114
24115function memoizeCompare(fn, isEqual) {
24116 var memoize = function memoize() {
24117 var args = [];
24118
24119 for (var i = 0; i < arguments.length; i++) {
24120 args[i] = arguments[i];
24121 }
24122
24123 for (var c = 0; c < memoize.cache.length; c++) {
24124 var cached = memoize.cache[c];
24125
24126 if (isEqual(args, cached.args)) {
24127 // TODO: move this cache entry to the top so recently used entries move up?
24128 return cached.res;
24129 }
24130 }
24131
24132 var res = fn.apply(fn, args);
24133 memoize.cache.unshift({
24134 args: args,
24135 res: res
24136 });
24137 return res;
24138 };
24139
24140 memoize.cache = [];
24141 return memoize;
24142}
24143/**
24144 * Find the maximum number of arguments expected by a typed function.
24145 * @param {function} fn A typed function
24146 * @return {number} Returns the maximum number of expected arguments.
24147 * Returns -1 when no signatures where found on the function.
24148 */
24149
24150function maxArgumentCount(fn) {
24151 return Object.keys(fn.signatures || {}).reduce(function (args, signature) {
24152 var count = (signature.match(/,/g) || []).length + 1;
24153 return Math.max(args, count);
24154 }, -1);
24155}
24156// CONCATENATED MODULE: ./src/function/matrix/filter.js
24157
24158
24159
24160var filter_name = 'filter';
24161var filter_dependencies = ['typed'];
24162var createFilter =
24163/* #__PURE__ */
24164Object(factory["a" /* factory */])(filter_name, filter_dependencies, function (_ref) {
24165 var typed = _ref.typed;
24166
24167 /**
24168 * Filter the items in an array or one dimensional matrix.
24169 *
24170 * Syntax:
24171 *
24172 * math.filter(x, test)
24173 *
24174 * Examples:
24175 *
24176 * function isPositive (x) {
24177 * return x > 0
24178 * }
24179 * math.filter([6, -2, -1, 4, 3], isPositive) // returns [6, 4, 3]
24180 *
24181 * math.filter(["23", "foo", "100", "55", "bar"], /[0-9]+/) // returns ["23", "100", "55"]
24182 *
24183 * See also:
24184 *
24185 * forEach, map, sort
24186 *
24187 * @param {Matrix | Array} x A one dimensional matrix or array to filter
24188 * @param {Function | RegExp} test
24189 * A function or regular expression to test items.
24190 * All entries for which `test` returns true are returned.
24191 * When `test` is a function, it is invoked with three parameters:
24192 * the value of the element, the index of the element, and the
24193 * matrix/array being traversed. The function must return a boolean.
24194 * @return {Matrix | Array} Returns the filtered matrix.
24195 */
24196 return typed('filter', {
24197 'Array, function': _filterCallback,
24198 'Matrix, function': function MatrixFunction(x, test) {
24199 return x.create(_filterCallback(x.toArray(), test));
24200 },
24201 'Array, RegExp': utils_array["d" /* filterRegExp */],
24202 'Matrix, RegExp': function MatrixRegExp(x, test) {
24203 return x.create(Object(utils_array["d" /* filterRegExp */])(x.toArray(), test));
24204 }
24205 });
24206});
24207/**
24208 * Filter values in a callback given a callback function
24209 * @param {Array} x
24210 * @param {Function} callback
24211 * @return {Array} Returns the filtered array
24212 * @private
24213 */
24214
24215function _filterCallback(x, callback) {
24216 // figure out what number of arguments the callback function expects
24217 var args = maxArgumentCount(callback);
24218 return Object(utils_array["c" /* filter */])(x, function (value, index, array) {
24219 // invoke the callback function with the right number of arguments
24220 if (args === 1) {
24221 return callback(value);
24222 } else if (args === 2) {
24223 return callback(value, [index]);
24224 } else {
24225 // 3 or -1
24226 return callback(value, [index], array);
24227 }
24228 });
24229}
24230// CONCATENATED MODULE: ./src/function/matrix/flatten.js
24231
24232
24233
24234var flatten_name = 'flatten';
24235var flatten_dependencies = ['typed', 'matrix'];
24236var createFlatten =
24237/* #__PURE__ */
24238Object(factory["a" /* factory */])(flatten_name, flatten_dependencies, function (_ref) {
24239 var typed = _ref.typed,
24240 matrix = _ref.matrix;
24241
24242 /**
24243 * Flatten a multi dimensional matrix into a single dimensional matrix.
24244 *
24245 * Syntax:
24246 *
24247 * math.flatten(x)
24248 *
24249 * Examples:
24250 *
24251 * math.flatten([[1,2], [3,4]]) // returns [1, 2, 3, 4]
24252 *
24253 * See also:
24254 *
24255 * concat, resize, size, squeeze
24256 *
24257 * @param {Matrix | Array} x Matrix to be flattened
24258 * @return {Matrix | Array} Returns the flattened matrix
24259 */
24260 return typed(flatten_name, {
24261 Array: function Array(x) {
24262 return Object(utils_array["e" /* flatten */])(Object(utils_object["a" /* clone */])(x));
24263 },
24264 Matrix: function Matrix(x) {
24265 var flat = Object(utils_array["e" /* flatten */])(Object(utils_object["a" /* clone */])(x.toArray())); // TODO: return the same matrix type as x
24266
24267 return matrix(flat);
24268 }
24269 });
24270});
24271// CONCATENATED MODULE: ./src/function/matrix/forEach.js
24272
24273
24274
24275var forEach_name = 'forEach';
24276var forEach_dependencies = ['typed'];
24277var createForEach =
24278/* #__PURE__ */
24279Object(factory["a" /* factory */])(forEach_name, forEach_dependencies, function (_ref) {
24280 var typed = _ref.typed;
24281
24282 /**
24283 * Iterate over all elements of a matrix/array, and executes the given callback function.
24284 *
24285 * Syntax:
24286 *
24287 * math.forEach(x, callback)
24288 *
24289 * Examples:
24290 *
24291 * math.forEach([1, 2, 3], function(value) {
24292 * console.log(value)
24293 * })
24294 * // outputs 1, 2, 3
24295 *
24296 * See also:
24297 *
24298 * filter, map, sort
24299 *
24300 * @param {Matrix | Array} x The matrix to iterate on.
24301 * @param {Function} callback The callback function is invoked with three
24302 * parameters: the value of the element, the index
24303 * of the element, and the Matrix/array being traversed.
24304 */
24305 return typed(forEach_name, {
24306 'Array, function': forEach_forEach,
24307 'Matrix, function': function MatrixFunction(x, callback) {
24308 return x.forEach(callback);
24309 }
24310 });
24311});
24312/**
24313 * forEach for a multi dimensional array
24314 * @param {Array} array
24315 * @param {Function} callback
24316 * @private
24317 */
24318
24319function forEach_forEach(array, callback) {
24320 // figure out what number of arguments the callback function expects
24321 var args = maxArgumentCount(callback);
24322
24323 var recurse = function recurse(value, index) {
24324 if (Array.isArray(value)) {
24325 Object(utils_array["f" /* forEach */])(value, function (child, i) {
24326 // we create a copy of the index array and append the new index value
24327 recurse(child, index.concat(i));
24328 });
24329 } else {
24330 // invoke the callback function with the right number of arguments
24331 if (args === 1) {
24332 callback(value);
24333 } else if (args === 2) {
24334 callback(value, index);
24335 } else {
24336 // 3 or -1
24337 callback(value, index, array);
24338 }
24339 }
24340 };
24341
24342 recurse(array, []);
24343}
24344// CONCATENATED MODULE: ./src/function/matrix/getMatrixDataType.js
24345
24346
24347
24348var getMatrixDataType_name = 'getMatrixDataType';
24349var getMatrixDataType_dependencies = ['typed'];
24350var createGetMatrixDataType =
24351/* #__PURE__ */
24352Object(factory["a" /* factory */])(getMatrixDataType_name, getMatrixDataType_dependencies, function (_ref) {
24353 var typed = _ref.typed;
24354
24355 /**
24356 * Find the data type of all elements in a matrix or array,
24357 * for example 'number' if all items are a number and 'Complex' if all values
24358 * are complex numbers.
24359 * If a matrix contains more than one data type, it will return 'mixed'.
24360 *
24361 * Syntax:
24362 *
24363 * math.getMatrixDataType(x)
24364 *
24365 * Examples:
24366 *
24367 * const x = [ [1, 2, 3], [4, 5, 6] ]
24368 * const mixedX = [ [1, true], [2, 3] ]
24369 * const fractionX = [ [math.fraction(1, 3)], [math.fraction(1, 3] ]
24370 * const unitX = [ [math.unit('5cm')], [math.unit('5cm')] ]
24371 * const bigNumberX = [ [math.bignumber(1)], [math.bignumber(0)] ]
24372 * const sparse = math.sparse(x)
24373 * const dense = math.matrix(x)
24374 * math.getMatrixDataType(x) // returns 'number'
24375 * math.getMatrixDataType(sparse) // returns 'number'
24376 * math.getMatrixDataType(dense) // returns 'number'
24377 * math.getMatrixDataType(mixedX) // returns 'mixed'
24378 * math.getMatrixDataType(fractionX) // returns 'Fraction'
24379 * math.getMatrixDataType(unitX) // returns 'Unit'
24380 * math.getMatrixDataType(bigNumberX) // return 'BigNumber'
24381 *
24382 * See also:
24383 * SparseMatrix, DenseMatrix
24384 *
24385 * @param {...Matrix | Array} x The Matrix with values.
24386 *
24387 * @return {string} A string representation of the matrix type
24388 */
24389 return typed(getMatrixDataType_name, {
24390 Array: function Array(x) {
24391 return Object(utils_array["h" /* getArrayDataType */])(x, is["M" /* typeOf */]);
24392 },
24393 Matrix: function Matrix(x) {
24394 return x.getDataType();
24395 }
24396 });
24397});
24398// CONCATENATED MODULE: ./src/function/matrix/identity.js
24399
24400
24401
24402
24403var identity_name = 'identity';
24404var identity_dependencies = ['typed', 'config', 'matrix', 'BigNumber', 'DenseMatrix', 'SparseMatrix'];
24405var createIdentity =
24406/* #__PURE__ */
24407Object(factory["a" /* factory */])(identity_name, identity_dependencies, function (_ref) {
24408 var typed = _ref.typed,
24409 config = _ref.config,
24410 matrix = _ref.matrix,
24411 BigNumber = _ref.BigNumber,
24412 DenseMatrix = _ref.DenseMatrix,
24413 SparseMatrix = _ref.SparseMatrix;
24414
24415 /**
24416 * Create a 2-dimensional identity matrix with size m x n or n x n.
24417 * The matrix has ones on the diagonal and zeros elsewhere.
24418 *
24419 * Syntax:
24420 *
24421 * math.identity(n)
24422 * math.identity(n, format)
24423 * math.identity(m, n)
24424 * math.identity(m, n, format)
24425 * math.identity([m, n])
24426 * math.identity([m, n], format)
24427 *
24428 * Examples:
24429 *
24430 * math.identity(3) // returns [[1, 0, 0], [0, 1, 0], [0, 0, 1]]
24431 * math.identity(3, 2) // returns [[1, 0], [0, 1], [0, 0]]
24432 *
24433 * const A = [[1, 2, 3], [4, 5, 6]]
24434 * math.identity(math.size(A)) // returns [[1, 0, 0], [0, 1, 0]]
24435 *
24436 * See also:
24437 *
24438 * diag, ones, zeros, size, range
24439 *
24440 * @param {...number | Matrix | Array} size The size for the matrix
24441 * @param {string} [format] The Matrix storage format
24442 *
24443 * @return {Matrix | Array | number} A matrix with ones on the diagonal.
24444 */
24445 return typed(identity_name, {
24446 '': function _() {
24447 return config.matrix === 'Matrix' ? matrix([]) : [];
24448 },
24449 string: function string(format) {
24450 return matrix(format);
24451 },
24452 'number | BigNumber': function numberBigNumber(rows) {
24453 return _identity(rows, rows, config.matrix === 'Matrix' ? 'dense' : undefined);
24454 },
24455 'number | BigNumber, string': function numberBigNumberString(rows, format) {
24456 return _identity(rows, rows, format);
24457 },
24458 'number | BigNumber, number | BigNumber': function numberBigNumberNumberBigNumber(rows, cols) {
24459 return _identity(rows, cols, config.matrix === 'Matrix' ? 'dense' : undefined);
24460 },
24461 'number | BigNumber, number | BigNumber, string': function numberBigNumberNumberBigNumberString(rows, cols, format) {
24462 return _identity(rows, cols, format);
24463 },
24464 Array: function Array(size) {
24465 return _identityVector(size);
24466 },
24467 'Array, string': function ArrayString(size, format) {
24468 return _identityVector(size, format);
24469 },
24470 Matrix: function Matrix(size) {
24471 return _identityVector(size.valueOf(), size.storage());
24472 },
24473 'Matrix, string': function MatrixString(size, format) {
24474 return _identityVector(size.valueOf(), format);
24475 }
24476 });
24477
24478 function _identityVector(size, format) {
24479 switch (size.length) {
24480 case 0:
24481 return format ? matrix(format) : [];
24482
24483 case 1:
24484 return _identity(size[0], size[0], format);
24485
24486 case 2:
24487 return _identity(size[0], size[1], format);
24488
24489 default:
24490 throw new Error('Vector containing two values expected');
24491 }
24492 }
24493 /**
24494 * Create an identity matrix
24495 * @param {number | BigNumber} rows
24496 * @param {number | BigNumber} cols
24497 * @param {string} [format]
24498 * @returns {Matrix}
24499 * @private
24500 */
24501
24502
24503 function _identity(rows, cols, format) {
24504 // BigNumber constructor with the right precision
24505 var Big = Object(is["e" /* isBigNumber */])(rows) || Object(is["e" /* isBigNumber */])(cols) ? BigNumber : null;
24506 if (Object(is["e" /* isBigNumber */])(rows)) rows = rows.toNumber();
24507 if (Object(is["e" /* isBigNumber */])(cols)) cols = cols.toNumber();
24508
24509 if (!Object(utils_number["i" /* isInteger */])(rows) || rows < 1) {
24510 throw new Error('Parameters in function identity must be positive integers');
24511 }
24512
24513 if (!Object(utils_number["i" /* isInteger */])(cols) || cols < 1) {
24514 throw new Error('Parameters in function identity must be positive integers');
24515 }
24516
24517 var one = Big ? new BigNumber(1) : 1;
24518 var defaultValue = Big ? new Big(0) : 0;
24519 var size = [rows, cols]; // check we need to return a matrix
24520
24521 if (format) {
24522 // create diagonal matrix (use optimized implementation for storage format)
24523 if (format === 'sparse') {
24524 return SparseMatrix.diagonal(size, one, 0, defaultValue);
24525 }
24526
24527 if (format === 'dense') {
24528 return DenseMatrix.diagonal(size, one, 0, defaultValue);
24529 }
24530
24531 throw new TypeError("Unknown matrix type \"".concat(format, "\""));
24532 } // create and resize array
24533
24534
24535 var res = Object(utils_array["o" /* resize */])([], size, defaultValue); // fill in ones on the diagonal
24536
24537 var minimum = rows < cols ? rows : cols; // fill diagonal
24538
24539 for (var d = 0; d < minimum; d++) {
24540 res[d][d] = one;
24541 }
24542
24543 return res;
24544 }
24545});
24546// CONCATENATED MODULE: ./src/function/matrix/kron.js
24547
24548
24549var kron_name = 'kron';
24550var kron_dependencies = ['typed', 'matrix', 'multiplyScalar'];
24551var createKron =
24552/* #__PURE__ */
24553Object(factory["a" /* factory */])(kron_name, kron_dependencies, function (_ref) {
24554 var typed = _ref.typed,
24555 matrix = _ref.matrix,
24556 multiplyScalar = _ref.multiplyScalar;
24557
24558 /**
24559 * Calculates the kronecker product of 2 matrices or vectors.
24560 *
24561 * NOTE: If a one dimensional vector / matrix is given, it will be
24562 * wrapped so its two dimensions.
24563 * See the examples.
24564 *
24565 * Syntax:
24566 *
24567 * math.kron(x, y)
24568 *
24569 * Examples:
24570 *
24571 * math.kron([[1, 0], [0, 1]], [[1, 2], [3, 4]])
24572 * // returns [ [ 1, 2, 0, 0 ], [ 3, 4, 0, 0 ], [ 0, 0, 1, 2 ], [ 0, 0, 3, 4 ] ]
24573 *
24574 * math.kron([1,1], [2,3,4])
24575 * // returns [ [ 2, 3, 4, 2, 3, 4 ] ]
24576 *
24577 * See also:
24578 *
24579 * multiply, dot, cross
24580 *
24581 * @param {Array | Matrix} x First vector
24582 * @param {Array | Matrix} y Second vector
24583 * @return {Array | Matrix} Returns the kronecker product of `x` and `y`
24584 */
24585 return typed(kron_name, {
24586 'Matrix, Matrix': function MatrixMatrix(x, y) {
24587 return matrix(_kron(x.toArray(), y.toArray()));
24588 },
24589 'Matrix, Array': function MatrixArray(x, y) {
24590 return matrix(_kron(x.toArray(), y));
24591 },
24592 'Array, Matrix': function ArrayMatrix(x, y) {
24593 return matrix(_kron(x, y.toArray()));
24594 },
24595 'Array, Array': _kron
24596 });
24597 /**
24598 * Calculate the kronecker product of two matrices / vectors
24599 * @param {Array} a First vector
24600 * @param {Array} b Second vector
24601 * @returns {Array} Returns the kronecker product of x and y
24602 * @private
24603 */
24604
24605 function _kron(a, b) {
24606 // Deal with the dimensions of the matricies.
24607 if (Object(utils_array["a" /* arraySize */])(a).length === 1) {
24608 // Wrap it in a 2D Matrix
24609 a = [a];
24610 }
24611
24612 if (Object(utils_array["a" /* arraySize */])(b).length === 1) {
24613 // Wrap it in a 2D Matrix
24614 b = [b];
24615 }
24616
24617 if (Object(utils_array["a" /* arraySize */])(a).length > 2 || Object(utils_array["a" /* arraySize */])(b).length > 2) {
24618 throw new RangeError('Vectors with dimensions greater then 2 are not supported expected ' + '(Size x = ' + JSON.stringify(a.length) + ', y = ' + JSON.stringify(b.length) + ')');
24619 }
24620
24621 var t = [];
24622 var r = [];
24623 return a.map(function (a) {
24624 return b.map(function (b) {
24625 r = [];
24626 t.push(r);
24627 return a.map(function (y) {
24628 return b.map(function (x) {
24629 return r.push(multiplyScalar(y, x));
24630 });
24631 });
24632 });
24633 }) && t;
24634 }
24635});
24636// CONCATENATED MODULE: ./src/function/matrix/map.js
24637
24638
24639var map_name = 'map';
24640var map_dependencies = ['typed'];
24641var createMap =
24642/* #__PURE__ */
24643Object(factory["a" /* factory */])(map_name, map_dependencies, function (_ref) {
24644 var typed = _ref.typed;
24645
24646 /**
24647 * Create a new matrix or array with the results of the callback function executed on
24648 * each entry of the matrix/array.
24649 *
24650 * Syntax:
24651 *
24652 * math.map(x, callback)
24653 *
24654 * Examples:
24655 *
24656 * math.map([1, 2, 3], function(value) {
24657 * return value * value
24658 * }) // returns [1, 4, 9]
24659 *
24660 * See also:
24661 *
24662 * filter, forEach, sort
24663 *
24664 * @param {Matrix | Array} x The matrix to iterate on.
24665 * @param {Function} callback The callback method is invoked with three
24666 * parameters: the value of the element, the index
24667 * of the element, and the matrix being traversed.
24668 * @return {Matrix | array} Transformed map of x
24669 */
24670 return typed(map_name, {
24671 'Array, function': map_map,
24672 'Matrix, function': function MatrixFunction(x, callback) {
24673 return x.map(callback);
24674 }
24675 });
24676});
24677/**
24678 * Map for a multi dimensional array
24679 * @param {Array} array
24680 * @param {Function} callback
24681 * @return {Array}
24682 * @private
24683 */
24684
24685function map_map(array, callback) {
24686 // figure out what number of arguments the callback function expects
24687 var args = maxArgumentCount(callback);
24688
24689 var recurse = function recurse(value, index) {
24690 if (Array.isArray(value)) {
24691 return value.map(function (child, i) {
24692 // we create a copy of the index array and append the new index value
24693 return recurse(child, index.concat(i));
24694 });
24695 } else {
24696 // invoke the callback function with the right number of arguments
24697 if (args === 1) {
24698 return callback(value);
24699 } else if (args === 2) {
24700 return callback(value, index);
24701 } else {
24702 // 3 or -1
24703 return callback(value, index, array);
24704 }
24705 }
24706 };
24707
24708 return recurse(array, []);
24709}
24710// CONCATENATED MODULE: ./src/function/matrix/ones.js
24711
24712
24713
24714
24715var ones_name = 'ones';
24716var ones_dependencies = ['typed', 'config', 'matrix', 'BigNumber'];
24717var createOnes =
24718/* #__PURE__ */
24719Object(factory["a" /* factory */])(ones_name, ones_dependencies, function (_ref) {
24720 var typed = _ref.typed,
24721 config = _ref.config,
24722 matrix = _ref.matrix,
24723 BigNumber = _ref.BigNumber;
24724
24725 /**
24726 * Create a matrix filled with ones. The created matrix can have one or
24727 * multiple dimensions.
24728 *
24729 * Syntax:
24730 *
24731 * math.ones(m)
24732 * math.ones(m, format)
24733 * math.ones(m, n)
24734 * math.ones(m, n, format)
24735 * math.ones([m, n])
24736 * math.ones([m, n], format)
24737 * math.ones([m, n, p, ...])
24738 * math.ones([m, n, p, ...], format)
24739 *
24740 * Examples:
24741 *
24742 * math.ones(3) // returns [1, 1, 1]
24743 * math.ones(3, 2) // returns [[1, 1], [1, 1], [1, 1]]
24744 * math.ones(3, 2, 'dense') // returns Dense Matrix [[1, 1], [1, 1], [1, 1]]
24745 *
24746 * const A = [[1, 2, 3], [4, 5, 6]]
24747 * math.ones(math.size(A)) // returns [[1, 1, 1], [1, 1, 1]]
24748 *
24749 * See also:
24750 *
24751 * zeros, identity, size, range
24752 *
24753 * @param {...number | Array} size The size of each dimension of the matrix
24754 * @param {string} [format] The Matrix storage format
24755 *
24756 * @return {Array | Matrix | number} A matrix filled with ones
24757 */
24758 return typed('ones', {
24759 '': function _() {
24760 return config.matrix === 'Array' ? _ones([]) : _ones([], 'default');
24761 },
24762 // math.ones(m, n, p, ..., format)
24763 // TODO: more accurate signature '...number | BigNumber, string' as soon as typed-function supports this
24764 '...number | BigNumber | string': function numberBigNumberString(size) {
24765 var last = size[size.length - 1];
24766
24767 if (typeof last === 'string') {
24768 var format = size.pop();
24769 return _ones(size, format);
24770 } else if (config.matrix === 'Array') {
24771 return _ones(size);
24772 } else {
24773 return _ones(size, 'default');
24774 }
24775 },
24776 Array: _ones,
24777 Matrix: function Matrix(size) {
24778 var format = size.storage();
24779 return _ones(size.valueOf(), format);
24780 },
24781 'Array | Matrix, string': function ArrayMatrixString(size, format) {
24782 return _ones(size.valueOf(), format);
24783 }
24784 });
24785 /**
24786 * Create an Array or Matrix with ones
24787 * @param {Array} size
24788 * @param {string} [format='default']
24789 * @return {Array | Matrix}
24790 * @private
24791 */
24792
24793 function _ones(size, format) {
24794 var hasBigNumbers = _normalize(size);
24795
24796 var defaultValue = hasBigNumbers ? new BigNumber(1) : 1;
24797
24798 _validate(size);
24799
24800 if (format) {
24801 // return a matrix
24802 var m = matrix(format);
24803
24804 if (size.length > 0) {
24805 return m.resize(size, defaultValue);
24806 }
24807
24808 return m;
24809 } else {
24810 // return an Array
24811 var arr = [];
24812
24813 if (size.length > 0) {
24814 return Object(utils_array["o" /* resize */])(arr, size, defaultValue);
24815 }
24816
24817 return arr;
24818 }
24819 } // replace BigNumbers with numbers, returns true if size contained BigNumbers
24820
24821
24822 function _normalize(size) {
24823 var hasBigNumbers = false;
24824 size.forEach(function (value, index, arr) {
24825 if (Object(is["e" /* isBigNumber */])(value)) {
24826 hasBigNumbers = true;
24827 arr[index] = value.toNumber();
24828 }
24829 });
24830 return hasBigNumbers;
24831 } // validate arguments
24832
24833
24834 function _validate(size) {
24835 size.forEach(function (value) {
24836 if (typeof value !== 'number' || !Object(utils_number["i" /* isInteger */])(value) || value < 0) {
24837 throw new Error('Parameters in function ones must be positive integers');
24838 }
24839 });
24840 }
24841});
24842// CONCATENATED MODULE: ./src/utils/noop.js
24843function noBignumber() {
24844 throw new Error('No "bignumber" implementation available');
24845}
24846function noFraction() {
24847 throw new Error('No "fraction" implementation available');
24848}
24849function noMatrix() {
24850 throw new Error('No "matrix" implementation available');
24851}
24852function noIndexClass() {
24853 throw new Error('No "Index" implementation available');
24854}
24855function noSubset() {
24856 throw new Error('No "matrix" implementation available');
24857}
24858// CONCATENATED MODULE: ./src/function/matrix/range.js
24859
24860
24861var range_name = 'range';
24862var range_dependencies = ['typed', 'config', '?matrix', '?bignumber', 'smaller', 'smallerEq', 'larger', 'largerEq'];
24863var range_createRange =
24864/* #__PURE__ */
24865Object(factory["a" /* factory */])(range_name, range_dependencies, function (_ref) {
24866 var typed = _ref.typed,
24867 config = _ref.config,
24868 matrix = _ref.matrix,
24869 bignumber = _ref.bignumber,
24870 smaller = _ref.smaller,
24871 smallerEq = _ref.smallerEq,
24872 larger = _ref.larger,
24873 largerEq = _ref.largerEq;
24874
24875 /**
24876 * Create an array from a range.
24877 * By default, the range end is excluded. This can be customized by providing
24878 * an extra parameter `includeEnd`.
24879 *
24880 * Syntax:
24881 *
24882 * math.range(str [, includeEnd]) // Create a range from a string,
24883 * // where the string contains the
24884 * // start, optional step, and end,
24885 * // separated by a colon.
24886 * math.range(start, end [, includeEnd]) // Create a range with start and
24887 * // end and a step size of 1.
24888 * math.range(start, end, step [, includeEnd]) // Create a range with start, step,
24889 * // and end.
24890 *
24891 * Where:
24892 *
24893 * - `str: string`
24894 * A string 'start:end' or 'start:step:end'
24895 * - `start: {number | BigNumber}`
24896 * Start of the range
24897 * - `end: number | BigNumber`
24898 * End of the range, excluded by default, included when parameter includeEnd=true
24899 * - `step: number | BigNumber`
24900 * Step size. Default value is 1.
24901 * - `includeEnd: boolean`
24902 * Option to specify whether to include the end or not. False by default.
24903 *
24904 * Examples:
24905 *
24906 * math.range(2, 6) // [2, 3, 4, 5]
24907 * math.range(2, -3, -1) // [2, 1, 0, -1, -2]
24908 * math.range('2:1:6') // [2, 3, 4, 5]
24909 * math.range(2, 6, true) // [2, 3, 4, 5, 6]
24910 *
24911 * See also:
24912 *
24913 * ones, zeros, size, subset
24914 *
24915 * @param {*} args Parameters describing the ranges `start`, `end`, and optional `step`.
24916 * @return {Array | Matrix} range
24917 */
24918 return typed(range_name, {
24919 // TODO: simplify signatures when typed-function supports default values and optional arguments
24920 // TODO: a number or boolean should not be converted to string here
24921 string: _strRange,
24922 'string, boolean': _strRange,
24923 'number, number': function numberNumber(start, end) {
24924 return _out(_rangeEx(start, end, 1));
24925 },
24926 'number, number, number': function numberNumberNumber(start, end, step) {
24927 return _out(_rangeEx(start, end, step));
24928 },
24929 'number, number, boolean': function numberNumberBoolean(start, end, includeEnd) {
24930 return includeEnd ? _out(_rangeInc(start, end, 1)) : _out(_rangeEx(start, end, 1));
24931 },
24932 'number, number, number, boolean': function numberNumberNumberBoolean(start, end, step, includeEnd) {
24933 return includeEnd ? _out(_rangeInc(start, end, step)) : _out(_rangeEx(start, end, step));
24934 },
24935 'BigNumber, BigNumber': function BigNumberBigNumber(start, end) {
24936 var BigNumber = start.constructor;
24937 return _out(_bigRangeEx(start, end, new BigNumber(1)));
24938 },
24939 'BigNumber, BigNumber, BigNumber': function BigNumberBigNumberBigNumber(start, end, step) {
24940 return _out(_bigRangeEx(start, end, step));
24941 },
24942 'BigNumber, BigNumber, boolean': function BigNumberBigNumberBoolean(start, end, includeEnd) {
24943 var BigNumber = start.constructor;
24944 return includeEnd ? _out(_bigRangeInc(start, end, new BigNumber(1))) : _out(_bigRangeEx(start, end, new BigNumber(1)));
24945 },
24946 'BigNumber, BigNumber, BigNumber, boolean': function BigNumberBigNumberBigNumberBoolean(start, end, step, includeEnd) {
24947 return includeEnd ? _out(_bigRangeInc(start, end, step)) : _out(_bigRangeEx(start, end, step));
24948 }
24949 });
24950
24951 function _out(arr) {
24952 if (config.matrix === 'Matrix') {
24953 return matrix ? matrix(arr) : noMatrix();
24954 }
24955
24956 return arr;
24957 }
24958
24959 function _strRange(str, includeEnd) {
24960 var r = _parse(str);
24961
24962 if (!r) {
24963 throw new SyntaxError('String "' + str + '" is no valid range');
24964 }
24965
24966 var fn;
24967
24968 if (config.number === 'BigNumber') {
24969 if (bignumber === undefined) {
24970 noBignumber();
24971 }
24972
24973 fn = includeEnd ? _bigRangeInc : _bigRangeEx;
24974 return _out(fn(bignumber(r.start), bignumber(r.end), bignumber(r.step)));
24975 } else {
24976 fn = includeEnd ? _rangeInc : _rangeEx;
24977 return _out(fn(r.start, r.end, r.step));
24978 }
24979 }
24980 /**
24981 * Create a range with numbers. End is excluded
24982 * @param {number} start
24983 * @param {number} end
24984 * @param {number} step
24985 * @returns {Array} range
24986 * @private
24987 */
24988
24989
24990 function _rangeEx(start, end, step) {
24991 var array = [];
24992 var x = start;
24993
24994 if (step > 0) {
24995 while (smaller(x, end)) {
24996 array.push(x);
24997 x += step;
24998 }
24999 } else if (step < 0) {
25000 while (larger(x, end)) {
25001 array.push(x);
25002 x += step;
25003 }
25004 }
25005
25006 return array;
25007 }
25008 /**
25009 * Create a range with numbers. End is included
25010 * @param {number} start
25011 * @param {number} end
25012 * @param {number} step
25013 * @returns {Array} range
25014 * @private
25015 */
25016
25017
25018 function _rangeInc(start, end, step) {
25019 var array = [];
25020 var x = start;
25021
25022 if (step > 0) {
25023 while (smallerEq(x, end)) {
25024 array.push(x);
25025 x += step;
25026 }
25027 } else if (step < 0) {
25028 while (largerEq(x, end)) {
25029 array.push(x);
25030 x += step;
25031 }
25032 }
25033
25034 return array;
25035 }
25036 /**
25037 * Create a range with big numbers. End is excluded
25038 * @param {BigNumber} start
25039 * @param {BigNumber} end
25040 * @param {BigNumber} step
25041 * @returns {Array} range
25042 * @private
25043 */
25044
25045
25046 function _bigRangeEx(start, end, step) {
25047 var zero = bignumber(0);
25048 var array = [];
25049 var x = start;
25050
25051 if (step.gt(zero)) {
25052 while (smaller(x, end)) {
25053 array.push(x);
25054 x = x.plus(step);
25055 }
25056 } else if (step.lt(zero)) {
25057 while (larger(x, end)) {
25058 array.push(x);
25059 x = x.plus(step);
25060 }
25061 }
25062
25063 return array;
25064 }
25065 /**
25066 * Create a range with big numbers. End is included
25067 * @param {BigNumber} start
25068 * @param {BigNumber} end
25069 * @param {BigNumber} step
25070 * @returns {Array} range
25071 * @private
25072 */
25073
25074
25075 function _bigRangeInc(start, end, step) {
25076 var zero = bignumber(0);
25077 var array = [];
25078 var x = start;
25079
25080 if (step.gt(zero)) {
25081 while (smallerEq(x, end)) {
25082 array.push(x);
25083 x = x.plus(step);
25084 }
25085 } else if (step.lt(zero)) {
25086 while (largerEq(x, end)) {
25087 array.push(x);
25088 x = x.plus(step);
25089 }
25090 }
25091
25092 return array;
25093 }
25094 /**
25095 * Parse a string into a range,
25096 * The string contains the start, optional step, and end, separated by a colon.
25097 * If the string does not contain a valid range, null is returned.
25098 * For example str='0:2:11'.
25099 * @param {string} str
25100 * @return {{start: number, end: number, step: number} | null} range Object containing properties start, end, step
25101 * @private
25102 */
25103
25104
25105 function _parse(str) {
25106 var args = str.split(':'); // number
25107
25108 var nums = args.map(function (arg) {
25109 // use Number and not parseFloat as Number returns NaN on invalid garbage in the string
25110 return Number(arg);
25111 });
25112 var invalid = nums.some(function (num) {
25113 return isNaN(num);
25114 });
25115
25116 if (invalid) {
25117 return null;
25118 }
25119
25120 switch (nums.length) {
25121 case 2:
25122 return {
25123 start: nums[0],
25124 end: nums[1],
25125 step: 1
25126 };
25127
25128 case 3:
25129 return {
25130 start: nums[0],
25131 end: nums[2],
25132 step: nums[1]
25133 };
25134
25135 default:
25136 return null;
25137 }
25138 }
25139});
25140// CONCATENATED MODULE: ./src/function/matrix/reshape.js
25141
25142
25143var reshape_name = 'reshape';
25144var reshape_dependencies = ['typed', 'isInteger', 'matrix'];
25145var createReshape =
25146/* #__PURE__ */
25147Object(factory["a" /* factory */])(reshape_name, reshape_dependencies, function (_ref) {
25148 var typed = _ref.typed,
25149 isInteger = _ref.isInteger,
25150 matrix = _ref.matrix;
25151
25152 /**
25153 * Reshape a multi dimensional array to fit the specified dimensions
25154 *
25155 * Syntax:
25156 *
25157 * math.reshape(x, sizes)
25158 *
25159 * Examples:
25160 *
25161 * math.reshape([1, 2, 3, 4, 5, 6], [2, 3])
25162 * // returns Array [[1, 2, 3], [4, 5, 6]]
25163 *
25164 * math.reshape([[1, 2], [3, 4]], [1, 4])
25165 * // returns Array [[1, 2, 3, 4]]
25166 *
25167 * math.reshape([[1, 2], [3, 4]], [4])
25168 * // returns Array [1, 2, 3, 4]
25169 *
25170 * const x = math.matrix([1, 2, 3, 4, 5, 6, 7, 8])
25171 * math.reshape(x, [2, 2, 2])
25172 * // returns Matrix [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]
25173 *
25174 * See also:
25175 *
25176 * size, squeeze, resize
25177 *
25178 * @param {Array | Matrix | *} x Matrix to be reshaped
25179 * @param {number[]} sizes One dimensional array with integral sizes for
25180 * each dimension
25181 *
25182 * @return {* | Array | Matrix} A reshaped clone of matrix `x`
25183 *
25184 * @throws {TypeError} If `sizes` does not contain solely integers
25185 * @throws {DimensionError} If the product of the new dimension sizes does
25186 * not equal that of the old ones
25187 */
25188 return typed(reshape_name, {
25189 'Matrix, Array': function MatrixArray(x, sizes) {
25190 if (x.reshape) {
25191 return x.reshape(sizes);
25192 } else {
25193 return matrix(Object(utils_array["n" /* reshape */])(x.valueOf(), sizes));
25194 }
25195 },
25196 'Array, Array': function ArrayArray(x, sizes) {
25197 sizes.forEach(function (size) {
25198 if (!isInteger(size)) {
25199 throw new TypeError('Invalid size for dimension: ' + size);
25200 }
25201 });
25202 return Object(utils_array["n" /* reshape */])(x, sizes);
25203 }
25204 });
25205});
25206// EXTERNAL MODULE: ./src/error/ArgumentsError.js
25207var ArgumentsError = __webpack_require__(13);
25208
25209// CONCATENATED MODULE: ./src/function/matrix/resize.js
25210
25211
25212
25213
25214
25215
25216
25217
25218var resize_name = 'resize';
25219var resize_dependencies = ['config', 'matrix'];
25220var createResize =
25221/* #__PURE__ */
25222Object(factory["a" /* factory */])(resize_name, resize_dependencies, function (_ref) {
25223 var config = _ref.config,
25224 matrix = _ref.matrix;
25225
25226 /**
25227 * Resize a matrix
25228 *
25229 * Syntax:
25230 *
25231 * math.resize(x, size)
25232 * math.resize(x, size, defaultValue)
25233 *
25234 * Examples:
25235 *
25236 * math.resize([1, 2, 3, 4, 5], [3]) // returns Array [1, 2, 3]
25237 * math.resize([1, 2, 3], [5], 0) // returns Array [1, 2, 3, 0, 0]
25238 * math.resize(2, [2, 3], 0) // returns Matrix [[2, 0, 0], [0, 0, 0]]
25239 * math.resize("hello", [8], "!") // returns string 'hello!!!'
25240 *
25241 * See also:
25242 *
25243 * size, squeeze, subset, reshape
25244 *
25245 * @param {Array | Matrix | *} x Matrix to be resized
25246 * @param {Array | Matrix} size One dimensional array with numbers
25247 * @param {number | string} [defaultValue=0] Zero by default, except in
25248 * case of a string, in that case
25249 * defaultValue = ' '
25250 * @return {* | Array | Matrix} A resized clone of matrix `x`
25251 */
25252 // TODO: rework resize to a typed-function
25253 return function resize(x, size, defaultValue) {
25254 if (arguments.length !== 2 && arguments.length !== 3) {
25255 throw new ArgumentsError["a" /* ArgumentsError */]('resize', arguments.length, 2, 3);
25256 }
25257
25258 if (Object(is["v" /* isMatrix */])(size)) {
25259 size = size.valueOf(); // get Array
25260 }
25261
25262 if (Object(is["e" /* isBigNumber */])(size[0])) {
25263 // convert bignumbers to numbers
25264 size = size.map(function (value) {
25265 return !Object(is["e" /* isBigNumber */])(value) ? value : value.toNumber();
25266 });
25267 } // check x is a Matrix
25268
25269
25270 if (Object(is["v" /* isMatrix */])(x)) {
25271 // use optimized matrix implementation, return copy
25272 return x.resize(size, defaultValue, true);
25273 }
25274
25275 if (typeof x === 'string') {
25276 // resize string
25277 return _resizeString(x, size, defaultValue);
25278 } // check result should be a matrix
25279
25280
25281 var asMatrix = Array.isArray(x) ? false : config.matrix !== 'Array';
25282
25283 if (size.length === 0) {
25284 // output a scalar
25285 while (Array.isArray(x)) {
25286 x = x[0];
25287 }
25288
25289 return Object(utils_object["a" /* clone */])(x);
25290 } else {
25291 // output an array/matrix
25292 if (!Array.isArray(x)) {
25293 x = [x];
25294 }
25295
25296 x = Object(utils_object["a" /* clone */])(x);
25297 var res = Object(utils_array["o" /* resize */])(x, size, defaultValue);
25298 return asMatrix ? matrix(res) : res;
25299 }
25300 };
25301 /**
25302 * Resize a string
25303 * @param {string} str
25304 * @param {number[]} size
25305 * @param {string} [defaultChar=' ']
25306 * @private
25307 */
25308
25309 function _resizeString(str, size, defaultChar) {
25310 if (defaultChar !== undefined) {
25311 if (typeof defaultChar !== 'string' || defaultChar.length !== 1) {
25312 throw new TypeError('Single character expected as defaultValue');
25313 }
25314 } else {
25315 defaultChar = ' ';
25316 }
25317
25318 if (size.length !== 1) {
25319 throw new DimensionError["a" /* DimensionError */](size.length, 1);
25320 }
25321
25322 var len = size[0];
25323
25324 if (typeof len !== 'number' || !Object(utils_number["i" /* isInteger */])(len)) {
25325 throw new TypeError('Invalid size, must contain positive integers ' + '(size: ' + Object(utils_string["d" /* format */])(size) + ')');
25326 }
25327
25328 if (str.length > len) {
25329 return str.substring(0, len);
25330 } else if (str.length < len) {
25331 var res = str;
25332
25333 for (var i = 0, ii = len - str.length; i < ii; i++) {
25334 res += defaultChar;
25335 }
25336
25337 return res;
25338 } else {
25339 return str;
25340 }
25341 }
25342});
25343// CONCATENATED MODULE: ./src/function/matrix/row.js
25344
25345
25346
25347var row_name = 'row';
25348var row_dependencies = ['typed', 'Index', 'matrix', 'range'];
25349var createRow =
25350/* #__PURE__ */
25351Object(factory["a" /* factory */])(row_name, row_dependencies, function (_ref) {
25352 var typed = _ref.typed,
25353 Index = _ref.Index,
25354 matrix = _ref.matrix,
25355 range = _ref.range;
25356
25357 /**
25358 * Return a row from a Matrix.
25359 *
25360 * Syntax:
25361 *
25362 * math.row(value, index)
25363 *
25364 * Example:
25365 *
25366 * // get a row
25367 * const d = [[1, 2], [3, 4]]
25368 * math.row(d, 1) // returns [3, 4]
25369 *
25370 * See also:
25371 *
25372 * column
25373 *
25374 * @param {Array | Matrix } value An array or matrix
25375 * @param {number} row The index of the row
25376 * @return {Array | Matrix} The retrieved row
25377 */
25378 var row = typed(row_name, {
25379 'Matrix, number': _row,
25380 'Array, number': function ArrayNumber(value, row) {
25381 return _row(matrix(Object(utils_object["a" /* clone */])(value)), row).valueOf();
25382 }
25383 });
25384 return row;
25385 /**
25386 * Retrieve a row of a matrix
25387 * @param {Matrix } value A matrix
25388 * @param {number} row The index of the row
25389 * @return {Matrix} The retrieved row
25390 */
25391
25392 function _row(value, row) {
25393 // check dimensions
25394 if (value.size().length !== 2) {
25395 throw new Error('Only two dimensional matrix is supported');
25396 }
25397
25398 Object(utils_array["s" /* validateIndex */])(row, value.size()[0]);
25399 var columnRange = range(0, value.size()[1]);
25400 var index = new Index(row, columnRange);
25401 return value.subset(index);
25402 }
25403});
25404// CONCATENATED MODULE: ./src/function/matrix/size.js
25405
25406
25407
25408var size_name = 'size';
25409var size_dependencies = ['typed', 'config', '?matrix'];
25410var createSize =
25411/* #__PURE__ */
25412Object(factory["a" /* factory */])(size_name, size_dependencies, function (_ref) {
25413 var typed = _ref.typed,
25414 config = _ref.config,
25415 matrix = _ref.matrix;
25416
25417 /**
25418 * Calculate the size of a matrix or scalar.
25419 *
25420 * Syntax:
25421 *
25422 * math.size(x)
25423 *
25424 * Examples:
25425 *
25426 * math.size(2.3) // returns []
25427 * math.size('hello world') // returns [11]
25428 *
25429 * const A = [[1, 2, 3], [4, 5, 6]]
25430 * math.size(A) // returns [2, 3]
25431 * math.size(math.range(1,6)) // returns [5]
25432 *
25433 * See also:
25434 *
25435 * resize, squeeze, subset
25436 *
25437 * @param {boolean | number | Complex | Unit | string | Array | Matrix} x A matrix
25438 * @return {Array | Matrix} A vector with size of `x`.
25439 */
25440 return typed(size_name, {
25441 Matrix: function Matrix(x) {
25442 return x.create(x.size());
25443 },
25444 Array: utils_array["a" /* arraySize */],
25445 string: function string(x) {
25446 return config.matrix === 'Array' ? [x.length] : matrix([x.length]);
25447 },
25448 'number | Complex | BigNumber | Unit | boolean | null': function numberComplexBigNumberUnitBooleanNull(x) {
25449 // scalar
25450 return config.matrix === 'Array' ? [] : matrix ? matrix([]) : noMatrix();
25451 }
25452 });
25453});
25454// CONCATENATED MODULE: ./src/function/matrix/squeeze.js
25455
25456
25457
25458var squeeze_name = 'squeeze';
25459var squeeze_dependencies = ['typed', 'matrix'];
25460var createSqueeze =
25461/* #__PURE__ */
25462Object(factory["a" /* factory */])(squeeze_name, squeeze_dependencies, function (_ref) {
25463 var typed = _ref.typed,
25464 matrix = _ref.matrix;
25465
25466 /**
25467 * Squeeze a matrix, remove inner and outer singleton dimensions from a matrix.
25468 *
25469 * Syntax:
25470 *
25471 * math.squeeze(x)
25472 *
25473 * Examples:
25474 *
25475 * math.squeeze([3]) // returns 3
25476 * math.squeeze([[3]]) // returns 3
25477 *
25478 * const A = math.zeros(3, 1) // returns [[0], [0], [0]] (size 3x1)
25479 * math.squeeze(A) // returns [0, 0, 0] (size 3)
25480 *
25481 * const B = math.zeros(1, 3) // returns [[0, 0, 0]] (size 1x3)
25482 * math.squeeze(B) // returns [0, 0, 0] (size 3)
25483 *
25484 * // only inner and outer dimensions are removed
25485 * const C = math.zeros(2, 1, 3) // returns [[[0, 0, 0]], [[0, 0, 0]]] (size 2x1x3)
25486 * math.squeeze(C) // returns [[[0, 0, 0]], [[0, 0, 0]]] (size 2x1x3)
25487 *
25488 * See also:
25489 *
25490 * subset
25491 *
25492 * @param {Matrix | Array} x Matrix to be squeezed
25493 * @return {Matrix | Array} Squeezed matrix
25494 */
25495 return typed(squeeze_name, {
25496 Array: function Array(x) {
25497 return Object(utils_array["p" /* squeeze */])(Object(utils_object["a" /* clone */])(x));
25498 },
25499 Matrix: function Matrix(x) {
25500 var res = Object(utils_array["p" /* squeeze */])(x.toArray()); // FIXME: return the same type of matrix as the input
25501
25502 return Array.isArray(res) ? matrix(res) : res;
25503 },
25504 any: function any(x) {
25505 // scalar
25506 return Object(utils_object["a" /* clone */])(x);
25507 }
25508 });
25509});
25510// CONCATENATED MODULE: ./src/utils/customs.js
25511function customs_typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { customs_typeof = function _typeof(obj) { return typeof obj; }; } else { customs_typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return customs_typeof(obj); }
25512
25513
25514/**
25515 * Get a property of a plain object
25516 * Throws an error in case the object is not a plain object or the
25517 * property is not defined on the object itself
25518 * @param {Object} object
25519 * @param {string} prop
25520 * @return {*} Returns the property value when safe
25521 */
25522
25523function getSafeProperty(object, prop) {
25524 // only allow getting safe properties of a plain object
25525 if (isPlainObject(object) && isSafeProperty(object, prop)) {
25526 return object[prop];
25527 }
25528
25529 if (typeof object[prop] === 'function' && isSafeMethod(object, prop)) {
25530 throw new Error('Cannot access method "' + prop + '" as a property');
25531 }
25532
25533 throw new Error('No access to property "' + prop + '"');
25534}
25535/**
25536 * Set a property on a plain object.
25537 * Throws an error in case the object is not a plain object or the
25538 * property would override an inherited property like .constructor or .toString
25539 * @param {Object} object
25540 * @param {string} prop
25541 * @param {*} value
25542 * @return {*} Returns the value
25543 */
25544// TODO: merge this function into access.js?
25545
25546
25547function setSafeProperty(object, prop, value) {
25548 // only allow setting safe properties of a plain object
25549 if (isPlainObject(object) && isSafeProperty(object, prop)) {
25550 object[prop] = value;
25551 return value;
25552 }
25553
25554 throw new Error('No access to property "' + prop + '"');
25555}
25556/**
25557 * Test whether a property is safe to use for an object.
25558 * For example .toString and .constructor are not safe
25559 * @param {string} prop
25560 * @return {boolean} Returns true when safe
25561 */
25562
25563
25564function isSafeProperty(object, prop) {
25565 if (!object || customs_typeof(object) !== 'object') {
25566 return false;
25567 } // SAFE: whitelisted
25568 // e.g length
25569
25570
25571 if (Object(utils_object["f" /* hasOwnProperty */])(safeNativeProperties, prop)) {
25572 return true;
25573 } // UNSAFE: inherited from Object prototype
25574 // e.g constructor
25575
25576
25577 if (prop in Object.prototype) {
25578 // 'in' is used instead of hasOwnProperty for nodejs v0.10
25579 // which is inconsistent on root prototypes. It is safe
25580 // here because Object.prototype is a root object
25581 return false;
25582 } // UNSAFE: inherited from Function prototype
25583 // e.g call, apply
25584
25585
25586 if (prop in Function.prototype) {
25587 // 'in' is used instead of hasOwnProperty for nodejs v0.10
25588 // which is inconsistent on root prototypes. It is safe
25589 // here because Function.prototype is a root object
25590 return false;
25591 }
25592
25593 return true;
25594}
25595/**
25596 * Validate whether a method is safe.
25597 * Throws an error when that's not the case.
25598 * @param {Object} object
25599 * @param {string} method
25600 */
25601// TODO: merge this function into assign.js?
25602
25603
25604function validateSafeMethod(object, method) {
25605 if (!isSafeMethod(object, method)) {
25606 throw new Error('No access to method "' + method + '"');
25607 }
25608}
25609/**
25610 * Check whether a method is safe.
25611 * Throws an error when that's not the case (for example for `constructor`).
25612 * @param {Object} object
25613 * @param {string} method
25614 * @return {boolean} Returns true when safe, false otherwise
25615 */
25616
25617
25618function isSafeMethod(object, method) {
25619 if (object === null || object === undefined || typeof object[method] !== 'function') {
25620 return false;
25621 } // UNSAFE: ghosted
25622 // e.g overridden toString
25623 // Note that IE10 doesn't support __proto__ and we can't do this check there.
25624
25625
25626 if (Object(utils_object["f" /* hasOwnProperty */])(object, method) && Object.getPrototypeOf && method in Object.getPrototypeOf(object)) {
25627 return false;
25628 } // SAFE: whitelisted
25629 // e.g toString
25630
25631
25632 if (Object(utils_object["f" /* hasOwnProperty */])(safeNativeMethods, method)) {
25633 return true;
25634 } // UNSAFE: inherited from Object prototype
25635 // e.g constructor
25636
25637
25638 if (method in Object.prototype) {
25639 // 'in' is used instead of hasOwnProperty for nodejs v0.10
25640 // which is inconsistent on root prototypes. It is safe
25641 // here because Object.prototype is a root object
25642 return false;
25643 } // UNSAFE: inherited from Function prototype
25644 // e.g call, apply
25645
25646
25647 if (method in Function.prototype) {
25648 // 'in' is used instead of hasOwnProperty for nodejs v0.10
25649 // which is inconsistent on root prototypes. It is safe
25650 // here because Function.prototype is a root object
25651 return false;
25652 }
25653
25654 return true;
25655}
25656
25657function isPlainObject(object) {
25658 return customs_typeof(object) === 'object' && object && object.constructor === Object;
25659}
25660
25661var safeNativeProperties = {
25662 length: true,
25663 name: true
25664};
25665var safeNativeMethods = {
25666 toString: true,
25667 valueOf: true,
25668 toLocaleString: true
25669};
25670
25671
25672
25673
25674
25675
25676// CONCATENATED MODULE: ./src/function/matrix/subset.js
25677
25678
25679
25680
25681
25682
25683var subset_name = 'subset';
25684var subset_dependencies = ['typed', 'matrix'];
25685var createSubset =
25686/* #__PURE__ */
25687Object(factory["a" /* factory */])(subset_name, subset_dependencies, function (_ref) {
25688 var typed = _ref.typed,
25689 matrix = _ref.matrix;
25690
25691 /**
25692 * Get or set a subset of a matrix or string.
25693 *
25694 * Syntax:
25695 * math.subset(value, index) // retrieve a subset
25696 * math.subset(value, index, replacement [, defaultValue]) // replace a subset
25697 *
25698 * Examples:
25699 *
25700 * // get a subset
25701 * const d = [[1, 2], [3, 4]]
25702 * math.subset(d, math.index(1, 0)) // returns 3
25703 * math.subset(d, math.index([0, 1], 1)) // returns [[2], [4]]
25704 *
25705 * // replace a subset
25706 * const e = []
25707 * const f = math.subset(e, math.index(0, [0, 2]), [5, 6]) // f = [[5, 6]]
25708 * const g = math.subset(f, math.index(1, 1), 7, 0) // g = [[5, 6], [0, 7]]
25709 *
25710 * See also:
25711 *
25712 * size, resize, squeeze, index
25713 *
25714 * @param {Array | Matrix | string} matrix An array, matrix, or string
25715 * @param {Index} index An index containing ranges for each
25716 * dimension
25717 * @param {*} [replacement] An array, matrix, or scalar.
25718 * If provided, the subset is replaced with replacement.
25719 * If not provided, the subset is returned
25720 * @param {*} [defaultValue=undefined] Default value, filled in on new entries when
25721 * the matrix is resized. If not provided,
25722 * math.matrix elements will be left undefined.
25723 * @return {Array | Matrix | string} Either the retrieved subset or the updated matrix.
25724 */
25725 return typed(subset_name, {
25726 // get subset
25727 'Array, Index': function ArrayIndex(value, index) {
25728 var m = matrix(value);
25729 var subset = m.subset(index); // returns a Matrix
25730
25731 return index.isScalar() ? subset : subset.valueOf(); // return an Array (like the input)
25732 },
25733 'Matrix, Index': function MatrixIndex(value, index) {
25734 return value.subset(index);
25735 },
25736 'Object, Index': _getObjectProperty,
25737 'string, Index': _getSubstring,
25738 // set subset
25739 'Array, Index, any': function ArrayIndexAny(value, index, replacement) {
25740 return matrix(Object(utils_object["a" /* clone */])(value)).subset(index, replacement, undefined).valueOf();
25741 },
25742 'Array, Index, any, any': function ArrayIndexAnyAny(value, index, replacement, defaultValue) {
25743 return matrix(Object(utils_object["a" /* clone */])(value)).subset(index, replacement, defaultValue).valueOf();
25744 },
25745 'Matrix, Index, any': function MatrixIndexAny(value, index, replacement) {
25746 return value.clone().subset(index, replacement);
25747 },
25748 'Matrix, Index, any, any': function MatrixIndexAnyAny(value, index, replacement, defaultValue) {
25749 return value.clone().subset(index, replacement, defaultValue);
25750 },
25751 'string, Index, string': _setSubstring,
25752 'string, Index, string, string': _setSubstring,
25753 'Object, Index, any': _setObjectProperty
25754 });
25755});
25756/**
25757 * Retrieve a subset of a string
25758 * @param {string} str string from which to get a substring
25759 * @param {Index} index An index containing ranges for each dimension
25760 * @returns {string} substring
25761 * @private
25762 */
25763
25764function _getSubstring(str, index) {
25765 if (!Object(is["t" /* isIndex */])(index)) {
25766 // TODO: better error message
25767 throw new TypeError('Index expected');
25768 }
25769
25770 if (index.size().length !== 1) {
25771 throw new DimensionError["a" /* DimensionError */](index.size().length, 1);
25772 } // validate whether the range is out of range
25773
25774
25775 var strLen = str.length;
25776 Object(utils_array["s" /* validateIndex */])(index.min()[0], strLen);
25777 Object(utils_array["s" /* validateIndex */])(index.max()[0], strLen);
25778 var range = index.dimension(0);
25779 var substr = '';
25780 range.forEach(function (v) {
25781 substr += str.charAt(v);
25782 });
25783 return substr;
25784}
25785/**
25786 * Replace a substring in a string
25787 * @param {string} str string to be replaced
25788 * @param {Index} index An index containing ranges for each dimension
25789 * @param {string} replacement Replacement string
25790 * @param {string} [defaultValue] Default value to be uses when resizing
25791 * the string. is ' ' by default
25792 * @returns {string} result
25793 * @private
25794 */
25795
25796
25797function _setSubstring(str, index, replacement, defaultValue) {
25798 if (!index || index.isIndex !== true) {
25799 // TODO: better error message
25800 throw new TypeError('Index expected');
25801 }
25802
25803 if (index.size().length !== 1) {
25804 throw new DimensionError["a" /* DimensionError */](index.size().length, 1);
25805 }
25806
25807 if (defaultValue !== undefined) {
25808 if (typeof defaultValue !== 'string' || defaultValue.length !== 1) {
25809 throw new TypeError('Single character expected as defaultValue');
25810 }
25811 } else {
25812 defaultValue = ' ';
25813 }
25814
25815 var range = index.dimension(0);
25816 var len = range.size()[0];
25817
25818 if (len !== replacement.length) {
25819 throw new DimensionError["a" /* DimensionError */](range.size()[0], replacement.length);
25820 } // validate whether the range is out of range
25821
25822
25823 var strLen = str.length;
25824 Object(utils_array["s" /* validateIndex */])(index.min()[0]);
25825 Object(utils_array["s" /* validateIndex */])(index.max()[0]); // copy the string into an array with characters
25826
25827 var chars = [];
25828
25829 for (var i = 0; i < strLen; i++) {
25830 chars[i] = str.charAt(i);
25831 }
25832
25833 range.forEach(function (v, i) {
25834 chars[v] = replacement.charAt(i[0]);
25835 }); // initialize undefined characters with a space
25836
25837 if (chars.length > strLen) {
25838 for (var _i = strLen - 1, _len = chars.length; _i < _len; _i++) {
25839 if (!chars[_i]) {
25840 chars[_i] = defaultValue;
25841 }
25842 }
25843 }
25844
25845 return chars.join('');
25846}
25847/**
25848 * Retrieve a property from an object
25849 * @param {Object} object
25850 * @param {Index} index
25851 * @return {*} Returns the value of the property
25852 * @private
25853 */
25854
25855
25856function _getObjectProperty(object, index) {
25857 if (index.size().length !== 1) {
25858 throw new DimensionError["a" /* DimensionError */](index.size(), 1);
25859 }
25860
25861 var key = index.dimension(0);
25862
25863 if (typeof key !== 'string') {
25864 throw new TypeError('String expected as index to retrieve an object property');
25865 }
25866
25867 return getSafeProperty(object, key);
25868}
25869/**
25870 * Set a property on an object
25871 * @param {Object} object
25872 * @param {Index} index
25873 * @param {*} replacement
25874 * @return {*} Returns the updated object
25875 * @private
25876 */
25877
25878
25879function _setObjectProperty(object, index, replacement) {
25880 if (index.size().length !== 1) {
25881 throw new DimensionError["a" /* DimensionError */](index.size(), 1);
25882 }
25883
25884 var key = index.dimension(0);
25885
25886 if (typeof key !== 'string') {
25887 throw new TypeError('String expected as index to retrieve an object property');
25888 } // clone the object, and apply the property to the clone
25889
25890
25891 var updated = Object(utils_object["a" /* clone */])(object);
25892 setSafeProperty(updated, key, replacement);
25893 return updated;
25894}
25895// CONCATENATED MODULE: ./src/function/matrix/transpose.js
25896
25897
25898
25899var transpose_name = 'transpose';
25900var transpose_dependencies = ['typed', 'matrix'];
25901var createTranspose =
25902/* #__PURE__ */
25903Object(factory["a" /* factory */])(transpose_name, transpose_dependencies, function (_ref) {
25904 var typed = _ref.typed,
25905 matrix = _ref.matrix;
25906
25907 /**
25908 * Transpose a matrix. All values of the matrix are reflected over its
25909 * main diagonal. Only applicable to two dimensional matrices containing
25910 * a vector (i.e. having size `[1,n]` or `[n,1]`). One dimensional
25911 * vectors and scalars return the input unchanged.
25912 *
25913 * Syntax:
25914 *
25915 * math.transpose(x)
25916 *
25917 * Examples:
25918 *
25919 * const A = [[1, 2, 3], [4, 5, 6]]
25920 * math.transpose(A) // returns [[1, 4], [2, 5], [3, 6]]
25921 *
25922 * See also:
25923 *
25924 * diag, inv, subset, squeeze
25925 *
25926 * @param {Array | Matrix} x Matrix to be transposed
25927 * @return {Array | Matrix} The transposed matrix
25928 */
25929 var transpose = typed('transpose', {
25930 Array: function Array(x) {
25931 // use dense matrix implementation
25932 return transpose(matrix(x)).valueOf();
25933 },
25934 Matrix: function Matrix(x) {
25935 // matrix size
25936 var size = x.size(); // result
25937
25938 var c; // process dimensions
25939
25940 switch (size.length) {
25941 case 1:
25942 // vector
25943 c = x.clone();
25944 break;
25945
25946 case 2:
25947 {
25948 // rows and columns
25949 var rows = size[0];
25950 var columns = size[1]; // check columns
25951
25952 if (columns === 0) {
25953 // throw exception
25954 throw new RangeError('Cannot transpose a 2D matrix with no columns (size: ' + Object(utils_string["d" /* format */])(size) + ')');
25955 } // process storage format
25956
25957
25958 switch (x.storage()) {
25959 case 'dense':
25960 c = _denseTranspose(x, rows, columns);
25961 break;
25962
25963 case 'sparse':
25964 c = _sparseTranspose(x, rows, columns);
25965 break;
25966 }
25967 }
25968 break;
25969
25970 default:
25971 // multi dimensional
25972 throw new RangeError('Matrix must be a vector or two dimensional (size: ' + Object(utils_string["d" /* format */])(this._size) + ')');
25973 }
25974
25975 return c;
25976 },
25977 // scalars
25978 any: function any(x) {
25979 return Object(utils_object["a" /* clone */])(x);
25980 }
25981 });
25982
25983 function _denseTranspose(m, rows, columns) {
25984 // matrix array
25985 var data = m._data; // transposed matrix data
25986
25987 var transposed = [];
25988 var transposedRow; // loop columns
25989
25990 for (var j = 0; j < columns; j++) {
25991 // initialize row
25992 transposedRow = transposed[j] = []; // loop rows
25993
25994 for (var i = 0; i < rows; i++) {
25995 // set data
25996 transposedRow[i] = Object(utils_object["a" /* clone */])(data[i][j]);
25997 }
25998 } // return matrix
25999
26000
26001 return m.createDenseMatrix({
26002 data: transposed,
26003 size: [columns, rows],
26004 datatype: m._datatype
26005 });
26006 }
26007
26008 function _sparseTranspose(m, rows, columns) {
26009 // matrix arrays
26010 var values = m._values;
26011 var index = m._index;
26012 var ptr = m._ptr; // result matrices
26013
26014 var cvalues = values ? [] : undefined;
26015 var cindex = [];
26016 var cptr = []; // row counts
26017
26018 var w = [];
26019
26020 for (var x = 0; x < rows; x++) {
26021 w[x] = 0;
26022 } // vars
26023
26024
26025 var p, l, j; // loop values in matrix
26026
26027 for (p = 0, l = index.length; p < l; p++) {
26028 // number of values in row
26029 w[index[p]]++;
26030 } // cumulative sum
26031
26032
26033 var sum = 0; // initialize cptr with the cummulative sum of row counts
26034
26035 for (var i = 0; i < rows; i++) {
26036 // update cptr
26037 cptr.push(sum); // update sum
26038
26039 sum += w[i]; // update w
26040
26041 w[i] = cptr[i];
26042 } // update cptr
26043
26044
26045 cptr.push(sum); // loop columns
26046
26047 for (j = 0; j < columns; j++) {
26048 // values & index in column
26049 for (var k0 = ptr[j], k1 = ptr[j + 1], k = k0; k < k1; k++) {
26050 // C values & index
26051 var q = w[index[k]]++; // C[j, i] = A[i, j]
26052
26053 cindex[q] = j; // check we need to process values (pattern matrix)
26054
26055 if (values) {
26056 cvalues[q] = Object(utils_object["a" /* clone */])(values[k]);
26057 }
26058 }
26059 } // return matrix
26060
26061
26062 return m.createSparseMatrix({
26063 values: cvalues,
26064 index: cindex,
26065 ptr: cptr,
26066 size: [columns, rows],
26067 datatype: m._datatype
26068 });
26069 }
26070
26071 return transpose;
26072});
26073// CONCATENATED MODULE: ./src/function/matrix/ctranspose.js
26074
26075var ctranspose_name = 'ctranspose';
26076var ctranspose_dependencies = ['typed', 'transpose', 'conj'];
26077var createCtranspose =
26078/* #__PURE__ */
26079Object(factory["a" /* factory */])(ctranspose_name, ctranspose_dependencies, function (_ref) {
26080 var typed = _ref.typed,
26081 transpose = _ref.transpose,
26082 conj = _ref.conj;
26083
26084 /**
26085 * Transpose and complex conjugate a matrix. All values of the matrix are
26086 * reflected over its main diagonal and then the complex conjugate is
26087 * taken. This is equivalent to complex conjugation for scalars and
26088 * vectors.
26089 *
26090 * Syntax:
26091 *
26092 * math.ctranspose(x)
26093 *
26094 * Examples:
26095 *
26096 * const A = [[1, 2, 3], [4, 5, math.complex(6,7)]]
26097 * math.ctranspose(A) // returns [[1, 4], [2, 5], [3, {re:6,im:7}]]
26098 *
26099 * See also:
26100 *
26101 * transpose, diag, inv, subset, squeeze
26102 *
26103 * @param {Array | Matrix} x Matrix to be ctransposed
26104 * @return {Array | Matrix} The ctransposed matrix
26105 */
26106 return typed(ctranspose_name, {
26107 any: function any(x) {
26108 return conj(transpose(x));
26109 }
26110 });
26111});
26112// CONCATENATED MODULE: ./src/function/matrix/zeros.js
26113
26114
26115
26116
26117var zeros_name = 'zeros';
26118var zeros_dependencies = ['typed', 'config', 'matrix', 'BigNumber'];
26119var createZeros =
26120/* #__PURE__ */
26121Object(factory["a" /* factory */])(zeros_name, zeros_dependencies, function (_ref) {
26122 var typed = _ref.typed,
26123 config = _ref.config,
26124 matrix = _ref.matrix,
26125 BigNumber = _ref.BigNumber;
26126
26127 /**
26128 * Create a matrix filled with zeros. The created matrix can have one or
26129 * multiple dimensions.
26130 *
26131 * Syntax:
26132 *
26133 * math.zeros(m)
26134 * math.zeros(m, format)
26135 * math.zeros(m, n)
26136 * math.zeros(m, n, format)
26137 * math.zeros([m, n])
26138 * math.zeros([m, n], format)
26139 *
26140 * Examples:
26141 *
26142 * math.zeros(3) // returns [0, 0, 0]
26143 * math.zeros(3, 2) // returns [[0, 0], [0, 0], [0, 0]]
26144 * math.zeros(3, 'dense') // returns [0, 0, 0]
26145 *
26146 * const A = [[1, 2, 3], [4, 5, 6]]
26147 * math.zeros(math.size(A)) // returns [[0, 0, 0], [0, 0, 0]]
26148 *
26149 * See also:
26150 *
26151 * ones, identity, size, range
26152 *
26153 * @param {...number | Array} size The size of each dimension of the matrix
26154 * @param {string} [format] The Matrix storage format
26155 *
26156 * @return {Array | Matrix} A matrix filled with zeros
26157 */
26158 return typed(zeros_name, {
26159 '': function _() {
26160 return config.matrix === 'Array' ? _zeros([]) : _zeros([], 'default');
26161 },
26162 // math.zeros(m, n, p, ..., format)
26163 // TODO: more accurate signature '...number | BigNumber, string' as soon as typed-function supports this
26164 '...number | BigNumber | string': function numberBigNumberString(size) {
26165 var last = size[size.length - 1];
26166
26167 if (typeof last === 'string') {
26168 var format = size.pop();
26169 return _zeros(size, format);
26170 } else if (config.matrix === 'Array') {
26171 return _zeros(size);
26172 } else {
26173 return _zeros(size, 'default');
26174 }
26175 },
26176 Array: _zeros,
26177 Matrix: function Matrix(size) {
26178 var format = size.storage();
26179 return _zeros(size.valueOf(), format);
26180 },
26181 'Array | Matrix, string': function ArrayMatrixString(size, format) {
26182 return _zeros(size.valueOf(), format);
26183 }
26184 });
26185 /**
26186 * Create an Array or Matrix with zeros
26187 * @param {Array} size
26188 * @param {string} [format='default']
26189 * @return {Array | Matrix}
26190 * @private
26191 */
26192
26193 function _zeros(size, format) {
26194 var hasBigNumbers = _normalize(size);
26195
26196 var defaultValue = hasBigNumbers ? new BigNumber(0) : 0;
26197
26198 _validate(size);
26199
26200 if (format) {
26201 // return a matrix
26202 var m = matrix(format);
26203
26204 if (size.length > 0) {
26205 return m.resize(size, defaultValue);
26206 }
26207
26208 return m;
26209 } else {
26210 // return an Array
26211 var arr = [];
26212
26213 if (size.length > 0) {
26214 return Object(utils_array["o" /* resize */])(arr, size, defaultValue);
26215 }
26216
26217 return arr;
26218 }
26219 } // replace BigNumbers with numbers, returns true if size contained BigNumbers
26220
26221
26222 function _normalize(size) {
26223 var hasBigNumbers = false;
26224 size.forEach(function (value, index, arr) {
26225 if (Object(is["e" /* isBigNumber */])(value)) {
26226 hasBigNumbers = true;
26227 arr[index] = value.toNumber();
26228 }
26229 });
26230 return hasBigNumbers;
26231 } // validate arguments
26232
26233
26234 function _validate(size) {
26235 size.forEach(function (value) {
26236 if (typeof value !== 'number' || !Object(utils_number["i" /* isInteger */])(value) || value < 0) {
26237 throw new Error('Parameters in function zeros must be positive integers');
26238 }
26239 });
26240 }
26241}); // TODO: zeros contains almost the same code as ones. Reuse this?
26242// CONCATENATED MODULE: ./src/function/special/erf.js
26243
26244
26245
26246var erf_name = 'erf';
26247var erf_dependencies = ['typed'];
26248var createErf =
26249/* #__PURE__ */
26250Object(factory["a" /* factory */])(erf_name, erf_dependencies, function (_ref) {
26251 var typed = _ref.typed;
26252
26253 /**
26254 * Compute the erf function of a value using a rational Chebyshev
26255 * approximations for different intervals of x.
26256 *
26257 * This is a translation of W. J. Cody's Fortran implementation from 1987
26258 * ( https://www.netlib.org/specfun/erf ). See the AMS publication
26259 * "Rational Chebyshev Approximations for the Error Function" by W. J. Cody
26260 * for an explanation of this process.
26261 *
26262 * For matrices, the function is evaluated element wise.
26263 *
26264 * Syntax:
26265 *
26266 * math.erf(x)
26267 *
26268 * Examples:
26269 *
26270 * math.erf(0.2) // returns 0.22270258921047847
26271 * math.erf(-0.5) // returns -0.5204998778130465
26272 * math.erf(4) // returns 0.9999999845827421
26273 *
26274 * @param {number | Array | Matrix} x A real number
26275 * @return {number | Array | Matrix} The erf of `x`
26276 */
26277 var erf = typed('name', {
26278 number: function number(x) {
26279 var y = Math.abs(x);
26280
26281 if (y >= MAX_NUM) {
26282 return Object(utils_number["n" /* sign */])(x);
26283 }
26284
26285 if (y <= THRESH) {
26286 return Object(utils_number["n" /* sign */])(x) * erf1(y);
26287 }
26288
26289 if (y <= 4.0) {
26290 return Object(utils_number["n" /* sign */])(x) * (1 - erfc2(y));
26291 }
26292
26293 return Object(utils_number["n" /* sign */])(x) * (1 - erfc3(y));
26294 },
26295 'Array | Matrix': function ArrayMatrix(n) {
26296 return deepMap(n, erf);
26297 } // TODO: For complex numbers, use the approximation for the Faddeeva function
26298 // from "More Efficient Computation of the Complex Error Function" (AMS)
26299
26300 });
26301 /**
26302 * Approximates the error function erf() for x <= 0.46875 using this function:
26303 * n
26304 * erf(x) = x * sum (p_j * x^(2j)) / (q_j * x^(2j))
26305 * j=0
26306 */
26307
26308 function erf1(y) {
26309 var ysq = y * y;
26310 var xnum = erf_P[0][4] * ysq;
26311 var xden = ysq;
26312 var i;
26313
26314 for (i = 0; i < 3; i += 1) {
26315 xnum = (xnum + erf_P[0][i]) * ysq;
26316 xden = (xden + Q[0][i]) * ysq;
26317 }
26318
26319 return y * (xnum + erf_P[0][3]) / (xden + Q[0][3]);
26320 }
26321 /**
26322 * Approximates the complement of the error function erfc() for
26323 * 0.46875 <= x <= 4.0 using this function:
26324 * n
26325 * erfc(x) = e^(-x^2) * sum (p_j * x^j) / (q_j * x^j)
26326 * j=0
26327 */
26328
26329
26330 function erfc2(y) {
26331 var xnum = erf_P[1][8] * y;
26332 var xden = y;
26333 var i;
26334
26335 for (i = 0; i < 7; i += 1) {
26336 xnum = (xnum + erf_P[1][i]) * y;
26337 xden = (xden + Q[1][i]) * y;
26338 }
26339
26340 var result = (xnum + erf_P[1][7]) / (xden + Q[1][7]);
26341 var ysq = parseInt(y * 16) / 16;
26342 var del = (y - ysq) * (y + ysq);
26343 return Math.exp(-ysq * ysq) * Math.exp(-del) * result;
26344 }
26345 /**
26346 * Approximates the complement of the error function erfc() for x > 4.0 using
26347 * this function:
26348 *
26349 * erfc(x) = (e^(-x^2) / x) * [ 1/sqrt(pi) +
26350 * n
26351 * 1/(x^2) * sum (p_j * x^(-2j)) / (q_j * x^(-2j)) ]
26352 * j=0
26353 */
26354
26355
26356 function erfc3(y) {
26357 var ysq = 1 / (y * y);
26358 var xnum = erf_P[2][5] * ysq;
26359 var xden = ysq;
26360 var i;
26361
26362 for (i = 0; i < 4; i += 1) {
26363 xnum = (xnum + erf_P[2][i]) * ysq;
26364 xden = (xden + Q[2][i]) * ysq;
26365 }
26366
26367 var result = ysq * (xnum + erf_P[2][4]) / (xden + Q[2][4]);
26368 result = (SQRPI - result) / y;
26369 ysq = parseInt(y * 16) / 16;
26370 var del = (y - ysq) * (y + ysq);
26371 return Math.exp(-ysq * ysq) * Math.exp(-del) * result;
26372 }
26373
26374 return erf;
26375});
26376/**
26377 * Upper bound for the first approximation interval, 0 <= x <= THRESH
26378 * @constant
26379 */
26380
26381var THRESH = 0.46875;
26382/**
26383 * Constant used by W. J. Cody's Fortran77 implementation to denote sqrt(pi)
26384 * @constant
26385 */
26386
26387var SQRPI = 5.6418958354775628695e-1;
26388/**
26389 * Coefficients for each term of the numerator sum (p_j) for each approximation
26390 * interval (see W. J. Cody's paper for more details)
26391 * @constant
26392 */
26393
26394var erf_P = [[3.16112374387056560e00, 1.13864154151050156e02, 3.77485237685302021e02, 3.20937758913846947e03, 1.85777706184603153e-1], [5.64188496988670089e-1, 8.88314979438837594e00, 6.61191906371416295e01, 2.98635138197400131e02, 8.81952221241769090e02, 1.71204761263407058e03, 2.05107837782607147e03, 1.23033935479799725e03, 2.15311535474403846e-8], [3.05326634961232344e-1, 3.60344899949804439e-1, 1.25781726111229246e-1, 1.60837851487422766e-2, 6.58749161529837803e-4, 1.63153871373020978e-2]];
26395/**
26396 * Coefficients for each term of the denominator sum (q_j) for each approximation
26397 * interval (see W. J. Cody's paper for more details)
26398 * @constant
26399 */
26400
26401var Q = [[2.36012909523441209e01, 2.44024637934444173e02, 1.28261652607737228e03, 2.84423683343917062e03], [1.57449261107098347e01, 1.17693950891312499e02, 5.37181101862009858e02, 1.62138957456669019e03, 3.29079923573345963e03, 4.36261909014324716e03, 3.43936767414372164e03, 1.23033935480374942e03], [2.56852019228982242e00, 1.87295284992346047e00, 5.27905102951428412e-1, 6.05183413124413191e-2, 2.33520497626869185e-3]];
26402/**
26403 * Maximum/minimum safe numbers to input to erf() (in ES6+, this number is
26404 * Number.[MAX|MIN]_SAFE_INTEGER). erf() for all numbers beyond this limit will
26405 * return 1
26406 */
26407
26408var MAX_NUM = Math.pow(2, 53);
26409// CONCATENATED MODULE: ./src/function/statistics/mode.js
26410
26411
26412var mode_name = 'mode';
26413var mode_dependencies = ['typed', 'isNaN', 'isNumeric'];
26414var createMode =
26415/* #__PURE__ */
26416Object(factory["a" /* factory */])(mode_name, mode_dependencies, function (_ref) {
26417 var typed = _ref.typed,
26418 isNaN = _ref.isNaN,
26419 isNumeric = _ref.isNumeric;
26420
26421 /**
26422 * Computes the mode of a set of numbers or a list with values(numbers or characters).
26423 * If there are more than one modes, it returns a list of those values.
26424 *
26425 * Syntax:
26426 *
26427 * math.mode(a, b, c, ...)
26428 * math.mode(A)
26429 *
26430 * Examples:
26431 *
26432 * math.mode(2, 1, 4, 3, 1) // returns [1]
26433 * math.mode([1, 2.7, 3.2, 4, 2.7]) // returns [2.7]
26434 * math.mode(1, 4, 6, 1, 6) // returns [1, 6]
26435 * math.mode('a','a','b','c') // returns ["a"]
26436 * math.mode(1, 1.5, 'abc') // returns [1, 1.5, "abc"]
26437 *
26438 * See also:
26439 *
26440 * median,
26441 * mean
26442 *
26443 * @param {... *} args A single matrix
26444 * @return {*} The mode of all values
26445 */
26446 return typed(mode_name, {
26447 'Array | Matrix': _mode,
26448 '...': function _(args) {
26449 return _mode(args);
26450 }
26451 });
26452 /**
26453 * Calculates the mode in an 1-dimensional array
26454 * @param {Array} values
26455 * @return {Array} mode
26456 * @private
26457 */
26458
26459 function _mode(values) {
26460 values = Object(utils_array["e" /* flatten */])(values.valueOf());
26461 var num = values.length;
26462
26463 if (num === 0) {
26464 throw new Error('Cannot calculate mode of an empty array');
26465 }
26466
26467 var count = {};
26468 var mode = [];
26469 var max = 0;
26470
26471 for (var i = 0; i < values.length; i++) {
26472 var value = values[i];
26473
26474 if (isNumeric(value) && isNaN(value)) {
26475 throw new Error('Cannot calculate mode of an array containing NaN values');
26476 }
26477
26478 if (!(value in count)) {
26479 count[value] = 0;
26480 }
26481
26482 count[value]++;
26483
26484 if (count[value] === max) {
26485 mode.push(value);
26486 } else if (count[value] > max) {
26487 max = count[value];
26488 mode = [value];
26489 }
26490 }
26491
26492 return mode;
26493 }
26494});
26495// CONCATENATED MODULE: ./src/function/statistics/utils/improveErrorMessage.js
26496
26497/**
26498 * Improve error messages for statistics functions. Errors are typically
26499 * thrown in an internally used function like larger, causing the error
26500 * not to mention the function (like max) which is actually used by the user.
26501 *
26502 * @param {Error} err
26503 * @param {String} fnName
26504 * @param {*} [value]
26505 * @return {Error}
26506 */
26507
26508function improveErrorMessage(err, fnName, value) {
26509 // TODO: add information with the index (also needs transform in expression parser)
26510 var details;
26511
26512 if (String(err).indexOf('Unexpected type') !== -1) {
26513 details = arguments.length > 2 ? ' (type: ' + Object(is["M" /* typeOf */])(value) + ', value: ' + JSON.stringify(value) + ')' : ' (type: ' + err.data.actual + ')';
26514 return new TypeError('Cannot calculate ' + fnName + ', unexpected type of argument' + details);
26515 }
26516
26517 if (String(err).indexOf('complex numbers') !== -1) {
26518 details = arguments.length > 2 ? ' (type: ' + Object(is["M" /* typeOf */])(value) + ', value: ' + JSON.stringify(value) + ')' : '';
26519 return new TypeError('Cannot calculate ' + fnName + ', no ordering relation is defined for complex numbers' + details);
26520 }
26521
26522 return err;
26523}
26524// CONCATENATED MODULE: ./src/function/statistics/prod.js
26525
26526
26527
26528var prod_name = 'prod';
26529var prod_dependencies = ['typed', 'multiply'];
26530var createProd =
26531/* #__PURE__ */
26532Object(factory["a" /* factory */])(prod_name, prod_dependencies, function (_ref) {
26533 var typed = _ref.typed,
26534 multiply = _ref.multiply;
26535
26536 /**
26537 * Compute the product of a matrix or a list with values.
26538 * In case of a (multi dimensional) array or matrix, the sum of all
26539 * elements will be calculated.
26540 *
26541 * Syntax:
26542 *
26543 * math.prod(a, b, c, ...)
26544 * math.prod(A)
26545 *
26546 * Examples:
26547 *
26548 * math.multiply(2, 3) // returns 6
26549 * math.prod(2, 3) // returns 6
26550 * math.prod(2, 3, 4) // returns 24
26551 * math.prod([2, 3, 4]) // returns 24
26552 * math.prod([[2, 5], [4, 3]]) // returns 120
26553 *
26554 * See also:
26555 *
26556 * mean, median, min, max, sum, std, variance
26557 *
26558 * @param {... *} args A single matrix or or multiple scalar values
26559 * @return {*} The product of all values
26560 */
26561 return typed(prod_name, {
26562 // prod([a, b, c, d, ...])
26563 'Array | Matrix': _prod,
26564 // prod([a, b, c, d, ...], dim)
26565 'Array | Matrix, number | BigNumber': function ArrayMatrixNumberBigNumber(array, dim) {
26566 // TODO: implement prod(A, dim)
26567 throw new Error('prod(A, dim) is not yet supported'); // return reduce(arguments[0], arguments[1], math.prod)
26568 },
26569 // prod(a, b, c, d, ...)
26570 '...': function _(args) {
26571 return _prod(args);
26572 }
26573 });
26574 /**
26575 * Recursively calculate the product of an n-dimensional array
26576 * @param {Array} array
26577 * @return {number} prod
26578 * @private
26579 */
26580
26581 function _prod(array) {
26582 var prod;
26583 deepForEach(array, function (value) {
26584 try {
26585 prod = prod === undefined ? value : multiply(prod, value);
26586 } catch (err) {
26587 throw improveErrorMessage(err, 'prod', value);
26588 }
26589 });
26590
26591 if (prod === undefined) {
26592 throw new Error('Cannot calculate prod of an empty array');
26593 }
26594
26595 return prod;
26596 }
26597});
26598// CONCATENATED MODULE: ./src/function/string/format.js
26599
26600
26601var format_name = 'format';
26602var format_dependencies = ['typed'];
26603var createFormat =
26604/* #__PURE__ */
26605Object(factory["a" /* factory */])(format_name, format_dependencies, function (_ref) {
26606 var typed = _ref.typed;
26607
26608 /**
26609 * Format a value of any type into a string.
26610 *
26611 * Syntax:
26612 *
26613 * math.format(value)
26614 * math.format(value, options)
26615 * math.format(value, precision)
26616 * math.format(value, callback)
26617 *
26618 * Where:
26619 *
26620 * - `value: *`
26621 * The value to be formatted
26622 * - `options: Object`
26623 * An object with formatting options. Available options:
26624 * - `notation: string`
26625 * Number notation. Choose from:
26626 * - 'fixed'
26627 * Always use regular number notation.
26628 * For example '123.40' and '14000000'
26629 * - 'exponential'
26630 * Always use exponential notation.
26631 * For example '1.234e+2' and '1.4e+7'
26632 * - 'engineering'
26633 * Always use engineering notation.
26634 * For example '123.4e+0' and '14.0e+6'
26635 * - 'auto' (default)
26636 * Regular number notation for numbers having an absolute value between
26637 * `lower` and `upper` bounds, and uses exponential notation elsewhere.
26638 * Lower bound is included, upper bound is excluded.
26639 * For example '123.4' and '1.4e7'.
26640 * - `precision: number`
26641 * A number between 0 and 16 to round the digits of the number. In case
26642 * of notations 'exponential', 'engineering', and 'auto', `precision`
26643 * defines the total number of significant digits returned.
26644 * In case of notation 'fixed', `precision` defines the number of
26645 * significant digits after the decimal point.
26646 * `precision` is undefined by default.
26647 * - `lowerExp: number`
26648 * Exponent determining the lower boundary for formatting a value with
26649 * an exponent when `notation='auto`. Default value is `-3`.
26650 * - `upperExp: number`
26651 * Exponent determining the upper boundary for formatting a value with
26652 * an exponent when `notation='auto`. Default value is `5`.
26653 * - `fraction: string`. Available values: 'ratio' (default) or 'decimal'.
26654 * For example `format(fraction(1, 3))` will output '1/3' when 'ratio' is
26655 * configured, and will output `0.(3)` when 'decimal' is configured.
26656 * - `callback: function`
26657 * A custom formatting function, invoked for all numeric elements in `value`,
26658 * for example all elements of a matrix, or the real and imaginary
26659 * parts of a complex number. This callback can be used to override the
26660 * built-in numeric notation with any type of formatting. Function `callback`
26661 * is called with `value` as parameter and must return a string.
26662 *
26663 * When `value` is an Object:
26664 *
26665 * - When the object contains a property `format` being a function, this function
26666 * is invoked as `value.format(options)` and the result is returned.
26667 * - When the object has its own `toString` method, this method is invoked
26668 * and the result is returned.
26669 * - In other cases the function will loop over all object properties and
26670 * return JSON object notation like '{"a": 2, "b": 3}'.
26671 *
26672 * When value is a function:
26673 *
26674 * - When the function has a property `syntax`, it returns this
26675 * syntax description.
26676 * - In other cases, a string `'function'` is returned.
26677 *
26678 * Examples:
26679 *
26680 * math.format(6.4) // returns '6.4'
26681 * math.format(1240000) // returns '1.24e6'
26682 * math.format(1/3) // returns '0.3333333333333333'
26683 * math.format(1/3, 3) // returns '0.333'
26684 * math.format(21385, 2) // returns '21000'
26685 * math.format(12e8, {notation: 'fixed'}) // returns '1200000000'
26686 * math.format(2.3, {notation: 'fixed', precision: 4}) // returns '2.3000'
26687 * math.format(52.8, {notation: 'exponential'}) // returns '5.28e+1'
26688 * math.format(12400,{notation: 'engineering'}) // returns '12.400e+3'
26689 * math.format(2000, {lowerExp: -2, upperExp: 2}) // returns '2e+3'
26690 *
26691 * function formatCurrency(value) {
26692 * // return currency notation with two digits:
26693 * return '$' + value.toFixed(2)
26694 *
26695 * // you could also use math.format inside the callback:
26696 * // return '$' + math.format(value, {notation: 'fixed', precision: 2})
26697 * }
26698 * math.format([2.1, 3, 0.016], formatCurrency} // returns '[$2.10, $3.00, $0.02]'
26699 *
26700 * See also:
26701 *
26702 * print
26703 *
26704 * @param {*} value Value to be stringified
26705 * @param {Object | Function | number} [options] Formatting options
26706 * @return {string} The formatted value
26707 */
26708 return typed(format_name, {
26709 any: utils_string["d" /* format */],
26710 'any, Object | function | number': utils_string["d" /* format */]
26711 });
26712});
26713// CONCATENATED MODULE: ./src/function/string/print.js
26714
26715
26716
26717var print_name = 'print';
26718var print_dependencies = ['typed'];
26719var createPrint =
26720/* #__PURE__ */
26721Object(factory["a" /* factory */])(print_name, print_dependencies, function (_ref) {
26722 var typed = _ref.typed;
26723
26724 /**
26725 * Interpolate values into a string template.
26726 *
26727 * Syntax:
26728 *
26729 * math.print(template, values)
26730 * math.print(template, values, precision)
26731 * math.print(template, values, options)
26732 *
26733 * Example usage:
26734 *
26735 * // the following outputs: 'Lucy is 5 years old'
26736 * math.print('Lucy is $age years old', {age: 5})
26737 *
26738 * // the following outputs: 'The value of pi is 3.141592654'
26739 * math.print('The value of pi is $pi', {pi: math.pi}, 10)
26740 *
26741 * // the following outputs: 'hello Mary! The date is 2013-03-23'
26742 * math.print('Hello $user.name! The date is $date', {
26743 * user: {
26744 * name: 'Mary',
26745 * },
26746 * date: new Date(2013, 2, 23).toISOString().substring(0, 10)
26747 * })
26748 *
26749 * // the following outputs: 'My favorite fruits are apples and bananas !'
26750 * math.print('My favorite fruits are $0 and $1 !', [
26751 * 'apples',
26752 * 'bananas'
26753 * ])
26754 *
26755 * See also:
26756 *
26757 * format
26758 *
26759 * @param {string} template A string containing variable placeholders.
26760 * @param {Object | Array | Matrix} values An object or array containing variables
26761 * which will be filled in in the template.
26762 * @param {number | Object} [options] Formatting options,
26763 * or the number of digits to format numbers.
26764 * See function math.format for a description
26765 * of all options.
26766 * @return {string} Interpolated string
26767 */
26768 return typed(print_name, {
26769 // note: Matrix will be converted automatically to an Array
26770 'string, Object | Array': _print,
26771 'string, Object | Array, number | Object': _print
26772 });
26773});
26774/**
26775 * Interpolate values into a string template.
26776 * @param {string} template
26777 * @param {Object} values
26778 * @param {number | Object} [options]
26779 * @returns {string} Interpolated string
26780 * @private
26781 */
26782
26783function _print(template, values, options) {
26784 return template.replace(/\$([\w.]+)/g, function (original, key) {
26785 var keys = key.split('.');
26786 var value = values[keys.shift()];
26787
26788 while (keys.length && value !== undefined) {
26789 var k = keys.shift();
26790 value = k ? value[k] : value + '.';
26791 }
26792
26793 if (value !== undefined) {
26794 if (!Object(is["I" /* isString */])(value)) {
26795 return Object(utils_string["d" /* format */])(value, options);
26796 } else {
26797 return value;
26798 }
26799 }
26800
26801 return original;
26802 });
26803}
26804// CONCATENATED MODULE: ./src/function/unit/to.js
26805
26806
26807
26808var to_name = 'to';
26809var to_dependencies = ['typed', 'matrix'];
26810var createTo =
26811/* #__PURE__ */
26812Object(factory["a" /* factory */])(to_name, to_dependencies, function (_ref) {
26813 var typed = _ref.typed,
26814 matrix = _ref.matrix;
26815 var algorithm13 = createAlgorithm13({
26816 typed: typed
26817 });
26818 var algorithm14 = createAlgorithm14({
26819 typed: typed
26820 });
26821 /**
26822 * Change the unit of a value.
26823 *
26824 * For matrices, the function is evaluated element wise.
26825 *
26826 * Syntax:
26827 *
26828 * math.to(x, unit)
26829 *
26830 * Examples:
26831 *
26832 * math.to(math.unit('2 inch'), 'cm') // returns Unit 5.08 cm
26833 * math.to(math.unit('2 inch'), math.unit(null, 'cm')) // returns Unit 5.08 cm
26834 * math.to(math.unit(16, 'bytes'), 'bits') // returns Unit 128 bits
26835 *
26836 * See also:
26837 *
26838 * unit
26839 *
26840 * @param {Unit | Array | Matrix} x The unit to be converted.
26841 * @param {Unit | Array | Matrix} unit New unit. Can be a string like "cm"
26842 * or a unit without value.
26843 * @return {Unit | Array | Matrix} value with changed, fixed unit.
26844 */
26845
26846 var to = typed(to_name, {
26847 'Unit, Unit | string': function UnitUnitString(x, unit) {
26848 return x.to(unit);
26849 },
26850 'Matrix, Matrix': function MatrixMatrix(x, y) {
26851 // SparseMatrix does not support Units
26852 return algorithm13(x, y, to);
26853 },
26854 'Array, Array': function ArrayArray(x, y) {
26855 // use matrix implementation
26856 return to(matrix(x), matrix(y)).valueOf();
26857 },
26858 'Array, Matrix': function ArrayMatrix(x, y) {
26859 // use matrix implementation
26860 return to(matrix(x), y);
26861 },
26862 'Matrix, Array': function MatrixArray(x, y) {
26863 // use matrix implementation
26864 return to(x, matrix(y));
26865 },
26866 'Matrix, any': function MatrixAny(x, y) {
26867 // SparseMatrix does not support Units
26868 return algorithm14(x, y, to, false);
26869 },
26870 'any, Matrix': function anyMatrix(x, y) {
26871 // SparseMatrix does not support Units
26872 return algorithm14(y, x, to, true);
26873 },
26874 'Array, any': function ArrayAny(x, y) {
26875 // use matrix implementation
26876 return algorithm14(matrix(x), y, to, false).valueOf();
26877 },
26878 'any, Array': function anyArray(x, y) {
26879 // use matrix implementation
26880 return algorithm14(matrix(y), x, to, true).valueOf();
26881 }
26882 });
26883 return to;
26884});
26885// CONCATENATED MODULE: ./src/function/utils/isPrime.js
26886
26887
26888var isPrime_name = 'isPrime';
26889var isPrime_dependencies = ['typed'];
26890var createIsPrime =
26891/* #__PURE__ */
26892Object(factory["a" /* factory */])(isPrime_name, isPrime_dependencies, function (_ref) {
26893 var typed = _ref.typed;
26894
26895 /**
26896 * Test whether a value is prime: has no divisors other than itself and one.
26897 * The function supports type `number`, `bignumber`.
26898 *
26899 * The function is evaluated element-wise in case of Array or Matrix input.
26900 *
26901 * Syntax:
26902 *
26903 * math.isPrime(x)
26904 *
26905 * Examples:
26906 *
26907 * math.isPrime(3) // returns true
26908 * math.isPrime(-2) // returns false
26909 * math.isPrime(0) // returns false
26910 * math.isPrime(-0) // returns false
26911 * math.isPrime(0.5) // returns false
26912 * math.isPrime('2') // returns true
26913 * math.isPrime([2, 17, 100]) // returns [true, true, false]
26914 *
26915 * See also:
26916 *
26917 * isNumeric, isZero, isNegative, isInteger
26918 *
26919 * @param {number | BigNumber | Array | Matrix} x Value to be tested
26920 * @return {boolean} Returns true when `x` is larger than zero.
26921 * Throws an error in case of an unknown data type.
26922 */
26923 var isPrime = typed(isPrime_name, {
26924 number: function number(x) {
26925 if (x * 0 !== 0) {
26926 return false;
26927 }
26928
26929 if (x <= 3) {
26930 return x > 1;
26931 }
26932
26933 if (x % 2 === 0 || x % 3 === 0) {
26934 return false;
26935 }
26936
26937 for (var i = 5; i * i <= x; i += 6) {
26938 if (x % i === 0 || x % (i + 2) === 0) {
26939 return false;
26940 }
26941 }
26942
26943 return true;
26944 },
26945 BigNumber: function BigNumber(n) {
26946 if (n.toNumber() * 0 !== 0) {
26947 return false;
26948 }
26949
26950 if (n.lte(3)) return n.gt(1);
26951 if (n.mod(2).eq(0) || n.mod(3).eq(0)) return false;
26952
26953 for (var i = 5; n.gte(i * i); i += 6) {
26954 if (n.mod(i).eq(0) || n.mod(i + 2).eq(0)) {
26955 return false;
26956 }
26957 }
26958
26959 return true;
26960 },
26961 'Array | Matrix': function ArrayMatrix(x) {
26962 return deepMap(x, isPrime);
26963 }
26964 });
26965 return isPrime;
26966});
26967// CONCATENATED MODULE: ./src/function/utils/numeric.js
26968
26969
26970
26971var numeric_name = 'numeric';
26972var numeric_dependencies = ['number', '?bignumber', '?fraction'];
26973var createNumeric =
26974/* #__PURE__ */
26975Object(factory["a" /* factory */])(numeric_name, numeric_dependencies, function (_ref) {
26976 var _number = _ref.number,
26977 bignumber = _ref.bignumber,
26978 fraction = _ref.fraction;
26979 var validInputTypes = {
26980 string: true,
26981 number: true,
26982 BigNumber: true,
26983 Fraction: true
26984 }; // Load the conversion functions for each output type
26985
26986 var validOutputTypes = {
26987 number: function number(x) {
26988 return _number(x);
26989 },
26990 BigNumber: bignumber ? function (x) {
26991 return bignumber(x);
26992 } : noBignumber,
26993 Fraction: fraction ? function (x) {
26994 return fraction(x);
26995 } : noFraction
26996 };
26997 /**
26998 * Convert a numeric input to a specific numeric type: number, BigNumber, or Fraction.
26999 *
27000 * Syntax:
27001 *
27002 * math.numeric(x)
27003 *
27004 * Examples:
27005 *
27006 * math.numeric('4') // returns number 4
27007 * math.numeric('4', 'number') // returns number 4
27008 * math.numeric('4', 'BigNumber') // returns BigNumber 4
27009 * math.numeric('4', 'Fraction') // returns Fraction 4
27010 * math.numeric(4, 'Fraction') // returns Fraction 4
27011 * math.numeric(math.fraction(2, 5), 'number') // returns number 0.4
27012 *
27013 * See also:
27014 *
27015 * number, fraction, bignumber, string, format
27016 *
27017 * @param {string | number | BigNumber | Fraction } value
27018 * A numeric value or a string containing a numeric value
27019 * @param {string} outputType
27020 * Desired numeric output type.
27021 * Available values: 'number', 'BigNumber', or 'Fraction'
27022 * @return {number | BigNumber | Fraction}
27023 * Returns an instance of the numeric in the requested type
27024 */
27025
27026 return function numeric(value, outputType) {
27027 var inputType = Object(is["M" /* typeOf */])(value);
27028
27029 if (!(inputType in validInputTypes)) {
27030 throw new TypeError('Cannot convert ' + value + ' of type "' + inputType + '"; valid input types are ' + Object.keys(validInputTypes).join(', '));
27031 }
27032
27033 if (!(outputType in validOutputTypes)) {
27034 throw new TypeError('Cannot convert ' + value + ' to type "' + outputType + '"; valid output types are ' + Object.keys(validOutputTypes).join(', '));
27035 }
27036
27037 if (outputType === inputType) {
27038 return value;
27039 } else {
27040 return validOutputTypes[outputType](value);
27041 }
27042 };
27043});
27044// CONCATENATED MODULE: ./src/function/arithmetic/divideScalar.js
27045
27046
27047var divideScalar_name = 'divideScalar';
27048var divideScalar_dependencies = ['typed', 'numeric'];
27049var createDivideScalar =
27050/* #__PURE__ */
27051Object(factory["a" /* factory */])(divideScalar_name, divideScalar_dependencies, function (_ref) {
27052 var typed = _ref.typed,
27053 numeric = _ref.numeric;
27054
27055 /**
27056 * Divide two scalar values, `x / y`.
27057 * This function is meant for internal use: it is used by the public functions
27058 * `divide` and `inv`.
27059 *
27060 * This function does not support collections (Array or Matrix).
27061 *
27062 * @param {number | BigNumber | Fraction | Complex | Unit} x Numerator
27063 * @param {number | BigNumber | Fraction | Complex} y Denominator
27064 * @return {number | BigNumber | Fraction | Complex | Unit} Quotient, `x / y`
27065 * @private
27066 */
27067 var divideScalar = typed(divideScalar_name, {
27068 'number, number': function numberNumber(x, y) {
27069 return x / y;
27070 },
27071 'Complex, Complex': function ComplexComplex(x, y) {
27072 return x.div(y);
27073 },
27074 'BigNumber, BigNumber': function BigNumberBigNumber(x, y) {
27075 return x.div(y);
27076 },
27077 'Fraction, Fraction': function FractionFraction(x, y) {
27078 return x.div(y);
27079 },
27080 'Unit, number | Fraction | BigNumber': function UnitNumberFractionBigNumber(x, y) {
27081 var res = x.clone(); // TODO: move the divide function to Unit.js, it uses internals of Unit
27082
27083 var one = numeric(1, Object(is["M" /* typeOf */])(y));
27084 res.value = divideScalar(res.value === null ? res._normalize(one) : res.value, y);
27085 return res;
27086 },
27087 'number | Fraction | BigNumber, Unit': function numberFractionBigNumberUnit(x, y) {
27088 var res = y.clone();
27089 res = res.pow(-1); // TODO: move the divide function to Unit.js, it uses internals of Unit
27090
27091 var one = numeric(1, Object(is["M" /* typeOf */])(x));
27092 res.value = divideScalar(x, y.value === null ? y._normalize(one) : y.value);
27093 return res;
27094 },
27095 'Unit, Unit': function UnitUnit(x, y) {
27096 return x.divide(y);
27097 }
27098 });
27099 return divideScalar;
27100});
27101// CONCATENATED MODULE: ./src/function/arithmetic/pow.js
27102
27103
27104
27105
27106var pow_name = 'pow';
27107var pow_dependencies = ['typed', 'config', 'identity', 'multiply', 'matrix', 'fraction', 'number', 'Complex'];
27108var createPow =
27109/* #__PURE__ */
27110Object(factory["a" /* factory */])(pow_name, pow_dependencies, function (_ref) {
27111 var typed = _ref.typed,
27112 config = _ref.config,
27113 identity = _ref.identity,
27114 multiply = _ref.multiply,
27115 matrix = _ref.matrix,
27116 number = _ref.number,
27117 fraction = _ref.fraction,
27118 Complex = _ref.Complex;
27119
27120 /**
27121 * Calculates the power of x to y, `x ^ y`.
27122 * Matrix exponentiation is supported for square matrices `x`, and positive
27123 * integer exponents `y`.
27124 *
27125 * For cubic roots of negative numbers, the function returns the principal
27126 * root by default. In order to let the function return the real root,
27127 * math.js can be configured with `math.config({predictable: true})`.
27128 * To retrieve all cubic roots of a value, use `math.cbrt(x, true)`.
27129 *
27130 * Syntax:
27131 *
27132 * math.pow(x, y)
27133 *
27134 * Examples:
27135 *
27136 * math.pow(2, 3) // returns number 8
27137 *
27138 * const a = math.complex(2, 3)
27139 * math.pow(a, 2) // returns Complex -5 + 12i
27140 *
27141 * const b = [[1, 2], [4, 3]]
27142 * math.pow(b, 2) // returns Array [[9, 8], [16, 17]]
27143 *
27144 * See also:
27145 *
27146 * multiply, sqrt, cbrt, nthRoot
27147 *
27148 * @param {number | BigNumber | Complex | Unit | Array | Matrix} x The base
27149 * @param {number | BigNumber | Complex} y The exponent
27150 * @return {number | BigNumber | Complex | Array | Matrix} The value of `x` to the power `y`
27151 */
27152 return typed(pow_name, {
27153 'number, number': _pow,
27154 'Complex, Complex': function ComplexComplex(x, y) {
27155 return x.pow(y);
27156 },
27157 'BigNumber, BigNumber': function BigNumberBigNumber(x, y) {
27158 if (y.isInteger() || x >= 0 || config.predictable) {
27159 return x.pow(y);
27160 } else {
27161 return new Complex(x.toNumber(), 0).pow(y.toNumber(), 0);
27162 }
27163 },
27164 'Fraction, Fraction': function FractionFraction(x, y) {
27165 if (y.d !== 1) {
27166 if (config.predictable) {
27167 throw new Error('Function pow does not support non-integer exponents for fractions.');
27168 } else {
27169 return _pow(x.valueOf(), y.valueOf());
27170 }
27171 } else {
27172 return x.pow(y);
27173 }
27174 },
27175 'Array, number': _powArray,
27176 'Array, BigNumber': function ArrayBigNumber(x, y) {
27177 return _powArray(x, y.toNumber());
27178 },
27179 'Matrix, number': _powMatrix,
27180 'Matrix, BigNumber': function MatrixBigNumber(x, y) {
27181 return _powMatrix(x, y.toNumber());
27182 },
27183 'Unit, number | BigNumber': function UnitNumberBigNumber(x, y) {
27184 return x.pow(y);
27185 }
27186 });
27187 /**
27188 * Calculates the power of x to y, x^y, for two numbers.
27189 * @param {number} x
27190 * @param {number} y
27191 * @return {number | Complex} res
27192 * @private
27193 */
27194
27195 function _pow(x, y) {
27196 // Alternatively could define a 'realmode' config option or something, but
27197 // 'predictable' will work for now
27198 if (config.predictable && !Object(utils_number["i" /* isInteger */])(y) && x < 0) {
27199 // Check to see if y can be represented as a fraction
27200 try {
27201 var yFrac = fraction(y);
27202 var yNum = number(yFrac);
27203
27204 if (y === yNum || Math.abs((y - yNum) / y) < 1e-14) {
27205 if (yFrac.d % 2 === 1) {
27206 return (yFrac.n % 2 === 0 ? 1 : -1) * Math.pow(-x, y);
27207 }
27208 }
27209 } catch (ex) {} // fraction() throws an error if y is Infinity, etc.
27210 // Unable to express y as a fraction, so continue on
27211
27212 } // **for predictable mode** x^Infinity === NaN if x < -1
27213 // N.B. this behavour is different from `Math.pow` which gives
27214 // (-2)^Infinity === Infinity
27215
27216
27217 if (config.predictable && (x < -1 && y === Infinity || x > -1 && x < 0 && y === -Infinity)) {
27218 return NaN;
27219 }
27220
27221 if (Object(utils_number["i" /* isInteger */])(y) || x >= 0 || config.predictable) {
27222 return powNumber(x, y);
27223 } else {
27224 // TODO: the following infinity checks are duplicated from powNumber. Deduplicate this somehow
27225 // x^Infinity === 0 if -1 < x < 1
27226 // A real number 0 is returned instead of complex(0)
27227 if (x * x < 1 && y === Infinity || x * x > 1 && y === -Infinity) {
27228 return 0;
27229 }
27230
27231 return new Complex(x, 0).pow(y, 0);
27232 }
27233 }
27234 /**
27235 * Calculate the power of a 2d array
27236 * @param {Array} x must be a 2 dimensional, square matrix
27237 * @param {number} y a positive, integer value
27238 * @returns {Array}
27239 * @private
27240 */
27241
27242
27243 function _powArray(x, y) {
27244 if (!Object(utils_number["i" /* isInteger */])(y) || y < 0) {
27245 throw new TypeError('For A^b, b must be a positive integer (value is ' + y + ')');
27246 } // verify that A is a 2 dimensional square matrix
27247
27248
27249 var s = Object(utils_array["a" /* arraySize */])(x);
27250
27251 if (s.length !== 2) {
27252 throw new Error('For A^b, A must be 2 dimensional (A has ' + s.length + ' dimensions)');
27253 }
27254
27255 if (s[0] !== s[1]) {
27256 throw new Error('For A^b, A must be square (size is ' + s[0] + 'x' + s[1] + ')');
27257 }
27258
27259 var res = identity(s[0]).valueOf();
27260 var px = x;
27261
27262 while (y >= 1) {
27263 if ((y & 1) === 1) {
27264 res = multiply(px, res);
27265 }
27266
27267 y >>= 1;
27268 px = multiply(px, px);
27269 }
27270
27271 return res;
27272 }
27273 /**
27274 * Calculate the power of a 2d matrix
27275 * @param {Matrix} x must be a 2 dimensional, square matrix
27276 * @param {number} y a positive, integer value
27277 * @returns {Matrix}
27278 * @private
27279 */
27280
27281
27282 function _powMatrix(x, y) {
27283 return matrix(_powArray(x.valueOf(), y));
27284 }
27285});
27286// CONCATENATED MODULE: ./src/function/arithmetic/round.js
27287function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
27288
27289function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(source, true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(source).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
27290
27291function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
27292
27293
27294
27295
27296
27297
27298
27299
27300var NO_INT = 'Number of decimals in function round must be an integer';
27301var round_name = 'round';
27302var round_dependencies = ['typed', 'matrix', 'equalScalar', 'zeros', 'BigNumber', 'DenseMatrix'];
27303var createRound =
27304/* #__PURE__ */
27305Object(factory["a" /* factory */])(round_name, round_dependencies, function (_ref) {
27306 var typed = _ref.typed,
27307 matrix = _ref.matrix,
27308 equalScalar = _ref.equalScalar,
27309 zeros = _ref.zeros,
27310 BigNumber = _ref.BigNumber,
27311 DenseMatrix = _ref.DenseMatrix;
27312 var algorithm11 = createAlgorithm11({
27313 typed: typed,
27314 equalScalar: equalScalar
27315 });
27316 var algorithm12 = createAlgorithm12({
27317 typed: typed,
27318 DenseMatrix: DenseMatrix
27319 });
27320 var algorithm14 = createAlgorithm14({
27321 typed: typed
27322 });
27323 /**
27324 * Round a value towards the nearest integer.
27325 * For matrices, the function is evaluated element wise.
27326 *
27327 * Syntax:
27328 *
27329 * math.round(x)
27330 * math.round(x, n)
27331 *
27332 * Examples:
27333 *
27334 * math.round(3.2) // returns number 3
27335 * math.round(3.8) // returns number 4
27336 * math.round(-4.2) // returns number -4
27337 * math.round(-4.7) // returns number -5
27338 * math.round(math.pi, 3) // returns number 3.142
27339 * math.round(123.45678, 2) // returns number 123.46
27340 *
27341 * const c = math.complex(3.2, -2.7)
27342 * math.round(c) // returns Complex 3 - 3i
27343 *
27344 * math.round([3.2, 3.8, -4.7]) // returns Array [3, 4, -5]
27345 *
27346 * See also:
27347 *
27348 * ceil, fix, floor
27349 *
27350 * @param {number | BigNumber | Fraction | Complex | Array | Matrix} x Number to be rounded
27351 * @param {number | BigNumber | Array} [n=0] Number of decimals
27352 * @return {number | BigNumber | Fraction | Complex | Array | Matrix} Rounded value
27353 */
27354
27355 var round = typed(round_name, _objectSpread({}, roundNumberSignatures, {
27356 Complex: function Complex(x) {
27357 return x.round();
27358 },
27359 'Complex, number': function ComplexNumber(x, n) {
27360 if (n % 1) {
27361 throw new TypeError(NO_INT);
27362 }
27363
27364 return x.round(n);
27365 },
27366 'Complex, BigNumber': function ComplexBigNumber(x, n) {
27367 if (!n.isInteger()) {
27368 throw new TypeError(NO_INT);
27369 }
27370
27371 var _n = n.toNumber();
27372
27373 return x.round(_n);
27374 },
27375 'number, BigNumber': function numberBigNumber(x, n) {
27376 if (!n.isInteger()) {
27377 throw new TypeError(NO_INT);
27378 }
27379
27380 return new BigNumber(x).toDecimalPlaces(n.toNumber());
27381 },
27382 BigNumber: function BigNumber(x) {
27383 return x.toDecimalPlaces(0);
27384 },
27385 'BigNumber, BigNumber': function BigNumberBigNumber(x, n) {
27386 if (!n.isInteger()) {
27387 throw new TypeError(NO_INT);
27388 }
27389
27390 return x.toDecimalPlaces(n.toNumber());
27391 },
27392 Fraction: function Fraction(x) {
27393 return x.round();
27394 },
27395 'Fraction, number': function FractionNumber(x, n) {
27396 if (n % 1) {
27397 throw new TypeError(NO_INT);
27398 }
27399
27400 return x.round(n);
27401 },
27402 'Array | Matrix': function ArrayMatrix(x) {
27403 // deep map collection, skip zeros since round(0) = 0
27404 return deepMap(x, round, true);
27405 },
27406 'SparseMatrix, number | BigNumber': function SparseMatrixNumberBigNumber(x, y) {
27407 return algorithm11(x, y, round, false);
27408 },
27409 'DenseMatrix, number | BigNumber': function DenseMatrixNumberBigNumber(x, y) {
27410 return algorithm14(x, y, round, false);
27411 },
27412 'number | Complex | BigNumber, SparseMatrix': function numberComplexBigNumberSparseMatrix(x, y) {
27413 // check scalar is zero
27414 if (equalScalar(x, 0)) {
27415 // do not execute algorithm, result will be a zero matrix
27416 return zeros(y.size(), y.storage());
27417 }
27418
27419 return algorithm12(y, x, round, true);
27420 },
27421 'number | Complex | BigNumber, DenseMatrix': function numberComplexBigNumberDenseMatrix(x, y) {
27422 // check scalar is zero
27423 if (equalScalar(x, 0)) {
27424 // do not execute algorithm, result will be a zero matrix
27425 return zeros(y.size(), y.storage());
27426 }
27427
27428 return algorithm14(y, x, round, true);
27429 },
27430 'Array, number | BigNumber': function ArrayNumberBigNumber(x, y) {
27431 // use matrix implementation
27432 return algorithm14(matrix(x), y, round, false).valueOf();
27433 },
27434 'number | Complex | BigNumber, Array': function numberComplexBigNumberArray(x, y) {
27435 // use matrix implementation
27436 return algorithm14(matrix(y), x, round, true).valueOf();
27437 }
27438 }));
27439 return round;
27440});
27441var roundNumberSignatures = {
27442 number: roundNumber,
27443 'number, number': function numberNumber(x, n) {
27444 if (!Object(utils_number["i" /* isInteger */])(n)) {
27445 throw new TypeError(NO_INT);
27446 }
27447
27448 if (n < 0 || n > 15) {
27449 throw new Error('Number of decimals in function round must be in te range of 0-15');
27450 }
27451
27452 return roundNumber(x, n);
27453 }
27454};
27455var createRoundNumber =
27456/* #__PURE__ */
27457Object(factory["a" /* factory */])(round_name, ['typed'], function (_ref2) {
27458 var typed = _ref2.typed;
27459 return typed(round_name, roundNumberSignatures);
27460});
27461// CONCATENATED MODULE: ./src/function/arithmetic/log.js
27462
27463
27464
27465var log_name = 'log';
27466var log_dependencies = ['config', 'typed', 'divideScalar', 'Complex'];
27467var createLog =
27468/* #__PURE__ */
27469Object(factory["a" /* factory */])(log_name, log_dependencies, function (_ref) {
27470 var typed = _ref.typed,
27471 config = _ref.config,
27472 divideScalar = _ref.divideScalar,
27473 Complex = _ref.Complex;
27474
27475 /**
27476 * Calculate the logarithm of a value.
27477 *
27478 * For matrices, the function is evaluated element wise.
27479 *
27480 * Syntax:
27481 *
27482 * math.log(x)
27483 * math.log(x, base)
27484 *
27485 * Examples:
27486 *
27487 * math.log(3.5) // returns 1.252762968495368
27488 * math.exp(math.log(2.4)) // returns 2.4
27489 *
27490 * math.pow(10, 4) // returns 10000
27491 * math.log(10000, 10) // returns 4
27492 * math.log(10000) / math.log(10) // returns 4
27493 *
27494 * math.log(1024, 2) // returns 10
27495 * math.pow(2, 10) // returns 1024
27496 *
27497 * See also:
27498 *
27499 * exp, log2, log10, log1p
27500 *
27501 * @param {number | BigNumber | Complex | Array | Matrix} x
27502 * Value for which to calculate the logarithm.
27503 * @param {number | BigNumber | Complex} [base=e]
27504 * Optional base for the logarithm. If not provided, the natural
27505 * logarithm of `x` is calculated.
27506 * @return {number | BigNumber | Complex | Array | Matrix}
27507 * Returns the logarithm of `x`
27508 */
27509 var log = typed(log_name, {
27510 number: function number(x) {
27511 if (x >= 0 || config.predictable) {
27512 return logNumber(x);
27513 } else {
27514 // negative value -> complex value computation
27515 return new Complex(x, 0).log();
27516 }
27517 },
27518 Complex: function Complex(x) {
27519 return x.log();
27520 },
27521 BigNumber: function BigNumber(x) {
27522 if (!x.isNegative() || config.predictable) {
27523 return x.ln();
27524 } else {
27525 // downgrade to number, return Complex valued result
27526 return new Complex(x.toNumber(), 0).log();
27527 }
27528 },
27529 'Array | Matrix': function ArrayMatrix(x) {
27530 return deepMap(x, log);
27531 },
27532 'any, any': function anyAny(x, base) {
27533 // calculate logarithm for a specified base, log(x, base)
27534 return divideScalar(log(x), log(base));
27535 }
27536 });
27537 return log;
27538});
27539// CONCATENATED MODULE: ./src/function/arithmetic/log1p.js
27540
27541
27542
27543var log1p_name = 'log1p';
27544var log1p_dependencies = ['typed', 'config', 'divideScalar', 'log', 'Complex'];
27545var createLog1p =
27546/* #__PURE__ */
27547Object(factory["a" /* factory */])(log1p_name, log1p_dependencies, function (_ref) {
27548 var typed = _ref.typed,
27549 config = _ref.config,
27550 divideScalar = _ref.divideScalar,
27551 log = _ref.log,
27552 Complex = _ref.Complex;
27553
27554 /**
27555 * Calculate the logarithm of a `value+1`.
27556 *
27557 * For matrices, the function is evaluated element wise.
27558 *
27559 * Syntax:
27560 *
27561 * math.log1p(x)
27562 * math.log1p(x, base)
27563 *
27564 * Examples:
27565 *
27566 * math.log1p(2.5) // returns 1.252762968495368
27567 * math.exp(math.log1p(1.4)) // returns 2.4
27568 *
27569 * math.pow(10, 4) // returns 10000
27570 * math.log1p(9999, 10) // returns 4
27571 * math.log1p(9999) / math.log(10) // returns 4
27572 *
27573 * See also:
27574 *
27575 * exp, log, log2, log10
27576 *
27577 * @param {number | BigNumber | Complex | Array | Matrix} x
27578 * Value for which to calculate the logarithm of `x+1`.
27579 * @param {number | BigNumber | Complex} [base=e]
27580 * Optional base for the logarithm. If not provided, the natural
27581 * logarithm of `x+1` is calculated.
27582 * @return {number | BigNumber | Complex | Array | Matrix}
27583 * Returns the logarithm of `x+1`
27584 */
27585 var log1p = typed(log1p_name, {
27586 number: function number(x) {
27587 if (x >= -1 || config.predictable) {
27588 return Object(utils_number["k" /* log1p */])(x);
27589 } else {
27590 // negative value -> complex value computation
27591 return _log1pComplex(new Complex(x, 0));
27592 }
27593 },
27594 Complex: _log1pComplex,
27595 BigNumber: function BigNumber(x) {
27596 var y = x.plus(1);
27597
27598 if (!y.isNegative() || config.predictable) {
27599 return y.ln();
27600 } else {
27601 // downgrade to number, return Complex valued result
27602 return _log1pComplex(new Complex(x.toNumber(), 0));
27603 }
27604 },
27605 'Array | Matrix': function ArrayMatrix(x) {
27606 return deepMap(x, log1p);
27607 },
27608 'any, any': function anyAny(x, base) {
27609 // calculate logarithm for a specified base, log1p(x, base)
27610 return divideScalar(log1p(x), log(base));
27611 }
27612 });
27613 /**
27614 * Calculate the natural logarithm of a complex number + 1
27615 * @param {Complex} x
27616 * @returns {Complex}
27617 * @private
27618 */
27619
27620 function _log1pComplex(x) {
27621 var xRe1p = x.re + 1;
27622 return new Complex(Math.log(Math.sqrt(xRe1p * xRe1p + x.im * x.im)), Math.atan2(x.im, xRe1p));
27623 }
27624
27625 return log1p;
27626});
27627// CONCATENATED MODULE: ./src/function/arithmetic/nthRoots.js
27628
27629var nthRoots_name = 'nthRoots';
27630var nthRoots_dependencies = ['config', 'typed', 'divideScalar', 'Complex'];
27631var createNthRoots =
27632/* #__PURE__ */
27633Object(factory["a" /* factory */])(nthRoots_name, nthRoots_dependencies, function (_ref) {
27634 var typed = _ref.typed,
27635 config = _ref.config,
27636 divideScalar = _ref.divideScalar,
27637 Complex = _ref.Complex;
27638
27639 /**
27640 * Calculate the nth roots of a value.
27641 * An nth root of a positive real number A,
27642 * is a positive real solution of the equation "x^root = A".
27643 * This function returns an array of complex values.
27644 *
27645 * Syntax:
27646 *
27647 * math.nthRoots(x)
27648 * math.nthRoots(x, root)
27649 *
27650 * Examples:
27651 *
27652 * math.nthRoots(1)
27653 * // returns [
27654 * // {re: 1, im: 0},
27655 * // {re: -1, im: 0}
27656 * // ]
27657 * nthRoots(1, 3)
27658 * // returns [
27659 * // { re: 1, im: 0 },
27660 * // { re: -0.4999999999999998, im: 0.8660254037844387 },
27661 * // { re: -0.5000000000000004, im: -0.8660254037844385 }
27662 * ]
27663 *
27664 * See also:
27665 *
27666 * nthRoot, pow, sqrt
27667 *
27668 * @param {number | BigNumber | Fraction | Complex | Array | Matrix} x Number to be rounded
27669 * @return {number | BigNumber | Fraction | Complex | Array | Matrix} Rounded value
27670 */
27671 var nthRoots = typed(nthRoots_name, {
27672 Complex: function Complex(x) {
27673 return _nthComplexRoots(x, 2);
27674 },
27675 'Complex, number': _nthComplexRoots
27676 });
27677 /**
27678 * Each function here returns a real multiple of i as a Complex value.
27679 * @param {number} val
27680 * @return {Complex} val, i*val, -val or -i*val for index 0, 1, 2, 3
27681 */
27682 // This is used to fix float artifacts for zero-valued components.
27683
27684 var _calculateExactResult = [function realPos(val) {
27685 return new Complex(val, 0);
27686 }, function imagPos(val) {
27687 return new Complex(0, val);
27688 }, function realNeg(val) {
27689 return new Complex(-val, 0);
27690 }, function imagNeg(val) {
27691 return new Complex(0, -val);
27692 }];
27693 /**
27694 * Calculate the nth root of a Complex Number a using De Movire's Theorem.
27695 * @param {Complex} a
27696 * @param {number} root
27697 * @return {Array} array of n Complex Roots
27698 */
27699
27700 function _nthComplexRoots(a, root) {
27701 if (root < 0) throw new Error('Root must be greater than zero');
27702 if (root === 0) throw new Error('Root must be non-zero');
27703 if (root % 1 !== 0) throw new Error('Root must be an integer');
27704 if (a === 0 || a.abs() === 0) return [new Complex(0, 0)];
27705 var aIsNumeric = typeof a === 'number';
27706 var offset; // determine the offset (argument of a)/(pi/2)
27707
27708 if (aIsNumeric || a.re === 0 || a.im === 0) {
27709 if (aIsNumeric) {
27710 offset = 2 * +(a < 0); // numeric value on the real axis
27711 } else if (a.im === 0) {
27712 offset = 2 * +(a.re < 0); // complex value on the real axis
27713 } else {
27714 offset = 2 * +(a.im < 0) + 1; // complex value on the imaginary axis
27715 }
27716 }
27717
27718 var arg = a.arg();
27719 var abs = a.abs();
27720 var roots = [];
27721 var r = Math.pow(abs, 1 / root);
27722
27723 for (var k = 0; k < root; k++) {
27724 var halfPiFactor = (offset + 4 * k) / root;
27725 /**
27726 * If (offset + 4*k)/root is an integral multiple of pi/2
27727 * then we can produce a more exact result.
27728 */
27729
27730 if (halfPiFactor === Math.round(halfPiFactor)) {
27731 roots.push(_calculateExactResult[halfPiFactor % 4](r));
27732 continue;
27733 }
27734
27735 roots.push(new Complex({
27736 r: r,
27737 phi: (arg + 2 * Math.PI * k) / root
27738 }));
27739 }
27740
27741 return roots;
27742 }
27743
27744 return nthRoots;
27745});
27746// CONCATENATED MODULE: ./src/function/arithmetic/dotPow.js
27747
27748
27749
27750
27751
27752
27753
27754var dotPow_name = 'dotPow';
27755var dotPow_dependencies = ['typed', 'equalScalar', 'matrix', 'pow', 'DenseMatrix'];
27756var createDotPow =
27757/* #__PURE__ */
27758Object(factory["a" /* factory */])(dotPow_name, dotPow_dependencies, function (_ref) {
27759 var typed = _ref.typed,
27760 equalScalar = _ref.equalScalar,
27761 matrix = _ref.matrix,
27762 pow = _ref.pow,
27763 DenseMatrix = _ref.DenseMatrix;
27764 var algorithm03 = createAlgorithm03({
27765 typed: typed
27766 });
27767 var algorithm07 = createAlgorithm07({
27768 typed: typed,
27769 DenseMatrix: DenseMatrix
27770 });
27771 var algorithm11 = createAlgorithm11({
27772 typed: typed,
27773 equalScalar: equalScalar
27774 });
27775 var algorithm12 = createAlgorithm12({
27776 typed: typed,
27777 DenseMatrix: DenseMatrix
27778 });
27779 var algorithm13 = createAlgorithm13({
27780 typed: typed
27781 });
27782 var algorithm14 = createAlgorithm14({
27783 typed: typed
27784 });
27785 /**
27786 * Calculates the power of x to y element wise.
27787 *
27788 * Syntax:
27789 *
27790 * math.dotPow(x, y)
27791 *
27792 * Examples:
27793 *
27794 * math.dotPow(2, 3) // returns number 8
27795 *
27796 * const a = [[1, 2], [4, 3]]
27797 * math.dotPow(a, 2) // returns Array [[1, 4], [16, 9]]
27798 * math.pow(a, 2) // returns Array [[9, 8], [16, 17]]
27799 *
27800 * See also:
27801 *
27802 * pow, sqrt, multiply
27803 *
27804 * @param {number | BigNumber | Complex | Unit | Array | Matrix} x The base
27805 * @param {number | BigNumber | Complex | Unit | Array | Matrix} y The exponent
27806 * @return {number | BigNumber | Complex | Unit | Array | Matrix} The value of `x` to the power `y`
27807 */
27808
27809 var dotPow = typed(dotPow_name, {
27810 'any, any': pow,
27811 'SparseMatrix, SparseMatrix': function SparseMatrixSparseMatrix(x, y) {
27812 return algorithm07(x, y, pow, false);
27813 },
27814 'SparseMatrix, DenseMatrix': function SparseMatrixDenseMatrix(x, y) {
27815 return algorithm03(y, x, pow, true);
27816 },
27817 'DenseMatrix, SparseMatrix': function DenseMatrixSparseMatrix(x, y) {
27818 return algorithm03(x, y, pow, false);
27819 },
27820 'DenseMatrix, DenseMatrix': function DenseMatrixDenseMatrix(x, y) {
27821 return algorithm13(x, y, pow);
27822 },
27823 'Array, Array': function ArrayArray(x, y) {
27824 // use matrix implementation
27825 return dotPow(matrix(x), matrix(y)).valueOf();
27826 },
27827 'Array, Matrix': function ArrayMatrix(x, y) {
27828 // use matrix implementation
27829 return dotPow(matrix(x), y);
27830 },
27831 'Matrix, Array': function MatrixArray(x, y) {
27832 // use matrix implementation
27833 return dotPow(x, matrix(y));
27834 },
27835 'SparseMatrix, any': function SparseMatrixAny(x, y) {
27836 return algorithm11(x, y, dotPow, false);
27837 },
27838 'DenseMatrix, any': function DenseMatrixAny(x, y) {
27839 return algorithm14(x, y, dotPow, false);
27840 },
27841 'any, SparseMatrix': function anySparseMatrix(x, y) {
27842 return algorithm12(y, x, dotPow, true);
27843 },
27844 'any, DenseMatrix': function anyDenseMatrix(x, y) {
27845 return algorithm14(y, x, dotPow, true);
27846 },
27847 'Array, any': function ArrayAny(x, y) {
27848 // use matrix implementation
27849 return algorithm14(matrix(x), y, dotPow, false).valueOf();
27850 },
27851 'any, Array': function anyArray(x, y) {
27852 // use matrix implementation
27853 return algorithm14(matrix(y), x, dotPow, true).valueOf();
27854 }
27855 });
27856 return dotPow;
27857});
27858// CONCATENATED MODULE: ./src/function/arithmetic/dotDivide.js
27859
27860
27861
27862
27863
27864
27865
27866
27867var dotDivide_name = 'dotDivide';
27868var dotDivide_dependencies = ['typed', 'matrix', 'equalScalar', 'divideScalar', 'DenseMatrix'];
27869var createDotDivide =
27870/* #__PURE__ */
27871Object(factory["a" /* factory */])(dotDivide_name, dotDivide_dependencies, function (_ref) {
27872 var typed = _ref.typed,
27873 matrix = _ref.matrix,
27874 equalScalar = _ref.equalScalar,
27875 divideScalar = _ref.divideScalar,
27876 DenseMatrix = _ref.DenseMatrix;
27877 var algorithm02 = createAlgorithm02({
27878 typed: typed,
27879 equalScalar: equalScalar
27880 });
27881 var algorithm03 = createAlgorithm03({
27882 typed: typed
27883 });
27884 var algorithm07 = createAlgorithm07({
27885 typed: typed,
27886 DenseMatrix: DenseMatrix
27887 });
27888 var algorithm11 = createAlgorithm11({
27889 typed: typed,
27890 equalScalar: equalScalar
27891 });
27892 var algorithm12 = createAlgorithm12({
27893 typed: typed,
27894 DenseMatrix: DenseMatrix
27895 });
27896 var algorithm13 = createAlgorithm13({
27897 typed: typed
27898 });
27899 var algorithm14 = createAlgorithm14({
27900 typed: typed
27901 });
27902 /**
27903 * Divide two matrices element wise. The function accepts both matrices and
27904 * scalar values.
27905 *
27906 * Syntax:
27907 *
27908 * math.dotDivide(x, y)
27909 *
27910 * Examples:
27911 *
27912 * math.dotDivide(2, 4) // returns 0.5
27913 *
27914 * a = [[9, 5], [6, 1]]
27915 * b = [[3, 2], [5, 2]]
27916 *
27917 * math.dotDivide(a, b) // returns [[3, 2.5], [1.2, 0.5]]
27918 * math.divide(a, b) // returns [[1.75, 0.75], [-1.75, 2.25]]
27919 *
27920 * See also:
27921 *
27922 * divide, multiply, dotMultiply
27923 *
27924 * @param {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} x Numerator
27925 * @param {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} y Denominator
27926 * @return {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} Quotient, `x ./ y`
27927 */
27928
27929 var dotDivide = typed(dotDivide_name, {
27930 'any, any': divideScalar,
27931 'SparseMatrix, SparseMatrix': function SparseMatrixSparseMatrix(x, y) {
27932 return algorithm07(x, y, divideScalar, false);
27933 },
27934 'SparseMatrix, DenseMatrix': function SparseMatrixDenseMatrix(x, y) {
27935 return algorithm02(y, x, divideScalar, true);
27936 },
27937 'DenseMatrix, SparseMatrix': function DenseMatrixSparseMatrix(x, y) {
27938 return algorithm03(x, y, divideScalar, false);
27939 },
27940 'DenseMatrix, DenseMatrix': function DenseMatrixDenseMatrix(x, y) {
27941 return algorithm13(x, y, divideScalar);
27942 },
27943 'Array, Array': function ArrayArray(x, y) {
27944 // use matrix implementation
27945 return dotDivide(matrix(x), matrix(y)).valueOf();
27946 },
27947 'Array, Matrix': function ArrayMatrix(x, y) {
27948 // use matrix implementation
27949 return dotDivide(matrix(x), y);
27950 },
27951 'Matrix, Array': function MatrixArray(x, y) {
27952 // use matrix implementation
27953 return dotDivide(x, matrix(y));
27954 },
27955 'SparseMatrix, any': function SparseMatrixAny(x, y) {
27956 return algorithm11(x, y, divideScalar, false);
27957 },
27958 'DenseMatrix, any': function DenseMatrixAny(x, y) {
27959 return algorithm14(x, y, divideScalar, false);
27960 },
27961 'any, SparseMatrix': function anySparseMatrix(x, y) {
27962 return algorithm12(y, x, divideScalar, true);
27963 },
27964 'any, DenseMatrix': function anyDenseMatrix(x, y) {
27965 return algorithm14(y, x, divideScalar, true);
27966 },
27967 'Array, any': function ArrayAny(x, y) {
27968 // use matrix implementation
27969 return algorithm14(matrix(x), y, divideScalar, false).valueOf();
27970 },
27971 'any, Array': function anyArray(x, y) {
27972 // use matrix implementation
27973 return algorithm14(matrix(y), x, divideScalar, true).valueOf();
27974 }
27975 });
27976 return dotDivide;
27977});
27978// CONCATENATED MODULE: ./src/function/algebra/solver/utils/solveValidation.js
27979
27980
27981
27982function createSolveValidation(_ref) {
27983 var DenseMatrix = _ref.DenseMatrix;
27984
27985 /**
27986 * Validates matrix and column vector b for backward/forward substitution algorithms.
27987 *
27988 * @param {Matrix} m An N x N matrix
27989 * @param {Array | Matrix} b A column vector
27990 * @param {Boolean} copy Return a copy of vector b
27991 *
27992 * @return {DenseMatrix} Dense column vector b
27993 */
27994 return function solveValidation(m, b, copy) {
27995 // matrix size
27996 var size = m.size(); // validate matrix dimensions
27997
27998 if (size.length !== 2) {
27999 throw new RangeError('Matrix must be two dimensional (size: ' + Object(utils_string["d" /* format */])(size) + ')');
28000 } // rows & columns
28001
28002
28003 var rows = size[0];
28004 var columns = size[1]; // validate rows & columns
28005
28006 if (rows !== columns) {
28007 throw new RangeError('Matrix must be square (size: ' + Object(utils_string["d" /* format */])(size) + ')');
28008 } // vars
28009
28010
28011 var data, i, bdata; // check b is matrix
28012
28013 if (Object(is["v" /* isMatrix */])(b)) {
28014 // matrix size
28015 var msize = b.size(); // vector
28016
28017 if (msize.length === 1) {
28018 // check vector length
28019 if (msize[0] !== rows) {
28020 throw new RangeError('Dimension mismatch. Matrix columns must match vector length.');
28021 } // create data array
28022
28023
28024 data = []; // matrix data (DenseMatrix)
28025
28026 bdata = b._data; // loop b data
28027
28028 for (i = 0; i < rows; i++) {
28029 // row array
28030 data[i] = [bdata[i]];
28031 } // return Dense Matrix
28032
28033
28034 return new DenseMatrix({
28035 data: data,
28036 size: [rows, 1],
28037 datatype: b._datatype
28038 });
28039 } // two dimensions
28040
28041
28042 if (msize.length === 2) {
28043 // array must be a column vector
28044 if (msize[0] !== rows || msize[1] !== 1) {
28045 throw new RangeError('Dimension mismatch. Matrix columns must match vector length.');
28046 } // check matrix type
28047
28048
28049 if (Object(is["n" /* isDenseMatrix */])(b)) {
28050 // check a copy is needed
28051 if (copy) {
28052 // create data array
28053 data = []; // matrix data (DenseMatrix)
28054
28055 bdata = b._data; // loop b data
28056
28057 for (i = 0; i < rows; i++) {
28058 // row array
28059 data[i] = [bdata[i][0]];
28060 } // return Dense Matrix
28061
28062
28063 return new DenseMatrix({
28064 data: data,
28065 size: [rows, 1],
28066 datatype: b._datatype
28067 });
28068 } // b is already a column vector
28069
28070
28071 return b;
28072 } // create data array
28073
28074
28075 data = [];
28076
28077 for (i = 0; i < rows; i++) {
28078 data[i] = [0];
28079 } // sparse matrix arrays
28080
28081
28082 var values = b._values;
28083 var index = b._index;
28084 var ptr = b._ptr; // loop values in column 0
28085
28086 for (var k1 = ptr[1], k = ptr[0]; k < k1; k++) {
28087 // row
28088 i = index[k]; // add to data
28089
28090 data[i][0] = values[k];
28091 } // return Dense Matrix
28092
28093
28094 return new DenseMatrix({
28095 data: data,
28096 size: [rows, 1],
28097 datatype: b._datatype
28098 });
28099 } // throw error
28100
28101
28102 throw new RangeError('Dimension mismatch. Matrix columns must match vector length.');
28103 } // check b is array
28104
28105
28106 if (Object(is["b" /* isArray */])(b)) {
28107 // size
28108 var asize = Object(utils_array["a" /* arraySize */])(b); // check matrix dimensions, vector
28109
28110 if (asize.length === 1) {
28111 // check vector length
28112 if (asize[0] !== rows) {
28113 throw new RangeError('Dimension mismatch. Matrix columns must match vector length.');
28114 } // create data array
28115
28116
28117 data = []; // loop b
28118
28119 for (i = 0; i < rows; i++) {
28120 // row array
28121 data[i] = [b[i]];
28122 } // return Dense Matrix
28123
28124
28125 return new DenseMatrix({
28126 data: data,
28127 size: [rows, 1]
28128 });
28129 }
28130
28131 if (asize.length === 2) {
28132 // array must be a column vector
28133 if (asize[0] !== rows || asize[1] !== 1) {
28134 throw new RangeError('Dimension mismatch. Matrix columns must match vector length.');
28135 } // create data array
28136
28137
28138 data = []; // loop b data
28139
28140 for (i = 0; i < rows; i++) {
28141 // row array
28142 data[i] = [b[i][0]];
28143 } // return Dense Matrix
28144
28145
28146 return new DenseMatrix({
28147 data: data,
28148 size: [rows, 1]
28149 });
28150 } // throw error
28151
28152
28153 throw new RangeError('Dimension mismatch. Matrix columns must match vector length.');
28154 }
28155 };
28156}
28157// CONCATENATED MODULE: ./src/function/algebra/solver/lsolve.js
28158
28159
28160var lsolve_name = 'lsolve';
28161var lsolve_dependencies = ['typed', 'matrix', 'divideScalar', 'multiplyScalar', 'subtract', 'equalScalar', 'DenseMatrix'];
28162var createLsolve =
28163/* #__PURE__ */
28164Object(factory["a" /* factory */])(lsolve_name, lsolve_dependencies, function (_ref) {
28165 var typed = _ref.typed,
28166 matrix = _ref.matrix,
28167 divideScalar = _ref.divideScalar,
28168 multiplyScalar = _ref.multiplyScalar,
28169 subtract = _ref.subtract,
28170 equalScalar = _ref.equalScalar,
28171 DenseMatrix = _ref.DenseMatrix;
28172 var solveValidation = createSolveValidation({
28173 DenseMatrix: DenseMatrix
28174 });
28175 /**
28176 * Solves the linear equation system by forwards substitution. Matrix must be a lower triangular matrix.
28177 *
28178 * `L * x = b`
28179 *
28180 * Syntax:
28181 *
28182 * math.lsolve(L, b)
28183 *
28184 * Examples:
28185 *
28186 * const a = [[-2, 3], [2, 1]]
28187 * const b = [11, 9]
28188 * const x = lsolve(a, b) // [[-5.5], [20]]
28189 *
28190 * See also:
28191 *
28192 * lup, slu, usolve, lusolve
28193 *
28194 * @param {Matrix, Array} L A N x N matrix or array (L)
28195 * @param {Matrix, Array} b A column vector with the b values
28196 *
28197 * @return {DenseMatrix | Array} A column vector with the linear system solution (x)
28198 */
28199
28200 return typed(lsolve_name, {
28201 'SparseMatrix, Array | Matrix': function SparseMatrixArrayMatrix(m, b) {
28202 // process matrix
28203 return _sparseForwardSubstitution(m, b);
28204 },
28205 'DenseMatrix, Array | Matrix': function DenseMatrixArrayMatrix(m, b) {
28206 // process matrix
28207 return _denseForwardSubstitution(m, b);
28208 },
28209 'Array, Array | Matrix': function ArrayArrayMatrix(a, b) {
28210 // create dense matrix from array
28211 var m = matrix(a); // use matrix implementation
28212
28213 var r = _denseForwardSubstitution(m, b); // result
28214
28215
28216 return r.valueOf();
28217 }
28218 });
28219
28220 function _denseForwardSubstitution(m, b) {
28221 // validate matrix and vector, return copy of column vector b
28222 b = solveValidation(m, b, true); // column vector data
28223
28224 var bdata = b._data; // rows & columns
28225
28226 var rows = m._size[0];
28227 var columns = m._size[1]; // result
28228
28229 var x = []; // data
28230
28231 var data = m._data; // forward solve m * x = b, loop columns
28232
28233 for (var j = 0; j < columns; j++) {
28234 // b[j]
28235 var bj = bdata[j][0] || 0; // x[j]
28236
28237 var xj = void 0; // forward substitution (outer product) avoids inner looping when bj === 0
28238
28239 if (!equalScalar(bj, 0)) {
28240 // value @ [j, j]
28241 var vjj = data[j][j]; // check vjj
28242
28243 if (equalScalar(vjj, 0)) {
28244 // system cannot be solved
28245 throw new Error('Linear system cannot be solved since matrix is singular');
28246 } // calculate xj
28247
28248
28249 xj = divideScalar(bj, vjj); // loop rows
28250
28251 for (var i = j + 1; i < rows; i++) {
28252 // update copy of b
28253 bdata[i] = [subtract(bdata[i][0] || 0, multiplyScalar(xj, data[i][j]))];
28254 }
28255 } else {
28256 // zero @ j
28257 xj = 0;
28258 } // update x
28259
28260
28261 x[j] = [xj];
28262 } // return vector
28263
28264
28265 return new DenseMatrix({
28266 data: x,
28267 size: [rows, 1]
28268 });
28269 }
28270
28271 function _sparseForwardSubstitution(m, b) {
28272 // validate matrix and vector, return copy of column vector b
28273 b = solveValidation(m, b, true); // column vector data
28274
28275 var bdata = b._data; // rows & columns
28276
28277 var rows = m._size[0];
28278 var columns = m._size[1]; // matrix arrays
28279
28280 var values = m._values;
28281 var index = m._index;
28282 var ptr = m._ptr; // vars
28283
28284 var i, k; // result
28285
28286 var x = []; // forward solve m * x = b, loop columns
28287
28288 for (var j = 0; j < columns; j++) {
28289 // b[j]
28290 var bj = bdata[j][0] || 0; // forward substitution (outer product) avoids inner looping when bj === 0
28291
28292 if (!equalScalar(bj, 0)) {
28293 // value @ [j, j]
28294 var vjj = 0; // lower triangular matrix values & index (column j)
28295
28296 var jvalues = [];
28297 var jindex = []; // last index in column
28298
28299 var l = ptr[j + 1]; // values in column, find value @ [j, j]
28300
28301 for (k = ptr[j]; k < l; k++) {
28302 // row
28303 i = index[k]; // check row (rows are not sorted!)
28304
28305 if (i === j) {
28306 // update vjj
28307 vjj = values[k];
28308 } else if (i > j) {
28309 // store lower triangular
28310 jvalues.push(values[k]);
28311 jindex.push(i);
28312 }
28313 } // at this point we must have a value @ [j, j]
28314
28315
28316 if (equalScalar(vjj, 0)) {
28317 // system cannot be solved, there is no value @ [j, j]
28318 throw new Error('Linear system cannot be solved since matrix is singular');
28319 } // calculate xj
28320
28321
28322 var xj = divideScalar(bj, vjj); // loop lower triangular
28323
28324 for (k = 0, l = jindex.length; k < l; k++) {
28325 // row
28326 i = jindex[k]; // update copy of b
28327
28328 bdata[i] = [subtract(bdata[i][0] || 0, multiplyScalar(xj, jvalues[k]))];
28329 } // update x
28330
28331
28332 x[j] = [xj];
28333 } else {
28334 // update x
28335 x[j] = [0];
28336 }
28337 } // return vector
28338
28339
28340 return new DenseMatrix({
28341 data: x,
28342 size: [rows, 1]
28343 });
28344 }
28345});
28346// CONCATENATED MODULE: ./src/function/algebra/solver/usolve.js
28347
28348
28349var usolve_name = 'usolve';
28350var usolve_dependencies = ['typed', 'matrix', 'divideScalar', 'multiplyScalar', 'subtract', 'equalScalar', 'DenseMatrix'];
28351var createUsolve =
28352/* #__PURE__ */
28353Object(factory["a" /* factory */])(usolve_name, usolve_dependencies, function (_ref) {
28354 var typed = _ref.typed,
28355 matrix = _ref.matrix,
28356 divideScalar = _ref.divideScalar,
28357 multiplyScalar = _ref.multiplyScalar,
28358 subtract = _ref.subtract,
28359 equalScalar = _ref.equalScalar,
28360 DenseMatrix = _ref.DenseMatrix;
28361 var solveValidation = createSolveValidation({
28362 DenseMatrix: DenseMatrix
28363 });
28364 /**
28365 * Solves the linear equation system by backward substitution. Matrix must be an upper triangular matrix.
28366 *
28367 * `U * x = b`
28368 *
28369 * Syntax:
28370 *
28371 * math.usolve(U, b)
28372 *
28373 * Examples:
28374 *
28375 * const a = [[-2, 3], [2, 1]]
28376 * const b = [11, 9]
28377 * const x = usolve(a, b) // [[8], [9]]
28378 *
28379 * See also:
28380 *
28381 * lup, slu, usolve, lusolve
28382 *
28383 * @param {Matrix, Array} U A N x N matrix or array (U)
28384 * @param {Matrix, Array} b A column vector with the b values
28385 *
28386 * @return {DenseMatrix | Array} A column vector with the linear system solution (x)
28387 */
28388
28389 return typed(usolve_name, {
28390 'SparseMatrix, Array | Matrix': function SparseMatrixArrayMatrix(m, b) {
28391 // process matrix
28392 return _sparseBackwardSubstitution(m, b);
28393 },
28394 'DenseMatrix, Array | Matrix': function DenseMatrixArrayMatrix(m, b) {
28395 // process matrix
28396 return _denseBackwardSubstitution(m, b);
28397 },
28398 'Array, Array | Matrix': function ArrayArrayMatrix(a, b) {
28399 // create dense matrix from array
28400 var m = matrix(a); // use matrix implementation
28401
28402 var r = _denseBackwardSubstitution(m, b); // result
28403
28404
28405 return r.valueOf();
28406 }
28407 });
28408
28409 function _denseBackwardSubstitution(m, b) {
28410 // validate matrix and vector, return copy of column vector b
28411 b = solveValidation(m, b, true); // column vector data
28412
28413 var bdata = b._data; // rows & columns
28414
28415 var rows = m._size[0];
28416 var columns = m._size[1]; // result
28417
28418 var x = []; // arrays
28419
28420 var data = m._data; // backward solve m * x = b, loop columns (backwards)
28421
28422 for (var j = columns - 1; j >= 0; j--) {
28423 // b[j]
28424 var bj = bdata[j][0] || 0; // x[j]
28425
28426 var xj = void 0; // backward substitution (outer product) avoids inner looping when bj === 0
28427
28428 if (!equalScalar(bj, 0)) {
28429 // value @ [j, j]
28430 var vjj = data[j][j]; // check vjj
28431
28432 if (equalScalar(vjj, 0)) {
28433 // system cannot be solved
28434 throw new Error('Linear system cannot be solved since matrix is singular');
28435 } // calculate xj
28436
28437
28438 xj = divideScalar(bj, vjj); // loop rows
28439
28440 for (var i = j - 1; i >= 0; i--) {
28441 // update copy of b
28442 bdata[i] = [subtract(bdata[i][0] || 0, multiplyScalar(xj, data[i][j]))];
28443 }
28444 } else {
28445 // zero value @ j
28446 xj = 0;
28447 } // update x
28448
28449
28450 x[j] = [xj];
28451 } // return column vector
28452
28453
28454 return new DenseMatrix({
28455 data: x,
28456 size: [rows, 1]
28457 });
28458 }
28459
28460 function _sparseBackwardSubstitution(m, b) {
28461 // validate matrix and vector, return copy of column vector b
28462 b = solveValidation(m, b, true); // column vector data
28463
28464 var bdata = b._data; // rows & columns
28465
28466 var rows = m._size[0];
28467 var columns = m._size[1]; // matrix arrays
28468
28469 var values = m._values;
28470 var index = m._index;
28471 var ptr = m._ptr; // vars
28472
28473 var i, k; // result
28474
28475 var x = []; // backward solve m * x = b, loop columns (backwards)
28476
28477 for (var j = columns - 1; j >= 0; j--) {
28478 // b[j]
28479 var bj = bdata[j][0] || 0; // backward substitution (outer product) avoids inner looping when bj === 0
28480
28481 if (!equalScalar(bj, 0)) {
28482 // value @ [j, j]
28483 var vjj = 0; // upper triangular matrix values & index (column j)
28484
28485 var jvalues = [];
28486 var jindex = []; // first & last indeces in column
28487
28488 var f = ptr[j];
28489 var l = ptr[j + 1]; // values in column, find value @ [j, j], loop backwards
28490
28491 for (k = l - 1; k >= f; k--) {
28492 // row
28493 i = index[k]; // check row
28494
28495 if (i === j) {
28496 // update vjj
28497 vjj = values[k];
28498 } else if (i < j) {
28499 // store upper triangular
28500 jvalues.push(values[k]);
28501 jindex.push(i);
28502 }
28503 } // at this point we must have a value @ [j, j]
28504
28505
28506 if (equalScalar(vjj, 0)) {
28507 // system cannot be solved, there is no value @ [j, j]
28508 throw new Error('Linear system cannot be solved since matrix is singular');
28509 } // calculate xj
28510
28511
28512 var xj = divideScalar(bj, vjj); // loop upper triangular
28513
28514 for (k = 0, l = jindex.length; k < l; k++) {
28515 // row
28516 i = jindex[k]; // update copy of b
28517
28518 bdata[i] = [subtract(bdata[i][0], multiplyScalar(xj, jvalues[k]))];
28519 } // update x
28520
28521
28522 x[j] = [xj];
28523 } else {
28524 // update x
28525 x[j] = [0];
28526 }
28527 } // return vector
28528
28529
28530 return new DenseMatrix({
28531 data: x,
28532 size: [rows, 1]
28533 });
28534 }
28535});
28536// CONCATENATED MODULE: ./src/type/matrix/utils/algorithm08.js
28537
28538
28539var algorithm08_name = 'algorithm08';
28540var algorithm08_dependencies = ['typed', 'equalScalar'];
28541var createAlgorithm08 =
28542/* #__PURE__ */
28543Object(factory["a" /* factory */])(algorithm08_name, algorithm08_dependencies, function (_ref) {
28544 var typed = _ref.typed,
28545 equalScalar = _ref.equalScalar;
28546
28547 /**
28548 * Iterates over SparseMatrix A and SparseMatrix B nonzero items and invokes the callback function f(Aij, Bij).
28549 * Callback function invoked MAX(NNZA, NNZB) times
28550 *
28551 *
28552 * ┌ f(Aij, Bij) ; A(i,j) !== 0 && B(i,j) !== 0
28553 * C(i,j) = ┤ A(i,j) ; A(i,j) !== 0
28554 * └ 0 ; otherwise
28555 *
28556 *
28557 * @param {Matrix} a The SparseMatrix instance (A)
28558 * @param {Matrix} b The SparseMatrix instance (B)
28559 * @param {Function} callback The f(Aij,Bij) operation to invoke
28560 *
28561 * @return {Matrix} SparseMatrix (C)
28562 *
28563 * see https://github.com/josdejong/mathjs/pull/346#issuecomment-97620294
28564 */
28565 return function algorithm08(a, b, callback) {
28566 // sparse matrix arrays
28567 var avalues = a._values;
28568 var aindex = a._index;
28569 var aptr = a._ptr;
28570 var asize = a._size;
28571 var adt = a._datatype; // sparse matrix arrays
28572
28573 var bvalues = b._values;
28574 var bindex = b._index;
28575 var bptr = b._ptr;
28576 var bsize = b._size;
28577 var bdt = b._datatype; // validate dimensions
28578
28579 if (asize.length !== bsize.length) {
28580 throw new DimensionError["a" /* DimensionError */](asize.length, bsize.length);
28581 } // check rows & columns
28582
28583
28584 if (asize[0] !== bsize[0] || asize[1] !== bsize[1]) {
28585 throw new RangeError('Dimension mismatch. Matrix A (' + asize + ') must match Matrix B (' + bsize + ')');
28586 } // sparse matrix cannot be a Pattern matrix
28587
28588
28589 if (!avalues || !bvalues) {
28590 throw new Error('Cannot perform operation on Pattern Sparse Matrices');
28591 } // rows & columns
28592
28593
28594 var rows = asize[0];
28595 var columns = asize[1]; // datatype
28596
28597 var dt; // equal signature to use
28598
28599 var eq = equalScalar; // zero value
28600
28601 var zero = 0; // callback signature to use
28602
28603 var cf = callback; // process data types
28604
28605 if (typeof adt === 'string' && adt === bdt) {
28606 // datatype
28607 dt = adt; // find signature that matches (dt, dt)
28608
28609 eq = typed.find(equalScalar, [dt, dt]); // convert 0 to the same datatype
28610
28611 zero = typed.convert(0, dt); // callback
28612
28613 cf = typed.find(callback, [dt, dt]);
28614 } // result arrays
28615
28616
28617 var cvalues = [];
28618 var cindex = [];
28619 var cptr = []; // matrix
28620
28621 var c = a.createSparseMatrix({
28622 values: cvalues,
28623 index: cindex,
28624 ptr: cptr,
28625 size: [rows, columns],
28626 datatype: dt
28627 }); // workspace
28628
28629 var x = []; // marks indicating we have a value in x for a given column
28630
28631 var w = []; // vars
28632
28633 var k, k0, k1, i; // loop columns
28634
28635 for (var j = 0; j < columns; j++) {
28636 // update cptr
28637 cptr[j] = cindex.length; // columns mark
28638
28639 var mark = j + 1; // loop values in a
28640
28641 for (k0 = aptr[j], k1 = aptr[j + 1], k = k0; k < k1; k++) {
28642 // row
28643 i = aindex[k]; // mark workspace
28644
28645 w[i] = mark; // set value
28646
28647 x[i] = avalues[k]; // add index
28648
28649 cindex.push(i);
28650 } // loop values in b
28651
28652
28653 for (k0 = bptr[j], k1 = bptr[j + 1], k = k0; k < k1; k++) {
28654 // row
28655 i = bindex[k]; // check value exists in workspace
28656
28657 if (w[i] === mark) {
28658 // evaluate callback
28659 x[i] = cf(x[i], bvalues[k]);
28660 }
28661 } // initialize first index in j
28662
28663
28664 k = cptr[j]; // loop index in j
28665
28666 while (k < cindex.length) {
28667 // row
28668 i = cindex[k]; // value @ i
28669
28670 var v = x[i]; // check for zero value
28671
28672 if (!eq(v, zero)) {
28673 // push value
28674 cvalues.push(v); // increment pointer
28675
28676 k++;
28677 } else {
28678 // remove value @ i, do not increment pointer
28679 cindex.splice(k, 1);
28680 }
28681 }
28682 } // update cptr
28683
28684
28685 cptr[columns] = cindex.length; // return sparse matrix
28686
28687 return c;
28688 };
28689});
28690// CONCATENATED MODULE: ./src/function/bitwise/leftShift.js
28691
28692
28693
28694
28695
28696
28697
28698
28699
28700
28701var leftShift_name = 'leftShift';
28702var leftShift_dependencies = ['typed', 'matrix', 'equalScalar', 'zeros', 'DenseMatrix'];
28703var createLeftShift =
28704/* #__PURE__ */
28705Object(factory["a" /* factory */])(leftShift_name, leftShift_dependencies, function (_ref) {
28706 var typed = _ref.typed,
28707 matrix = _ref.matrix,
28708 equalScalar = _ref.equalScalar,
28709 zeros = _ref.zeros,
28710 DenseMatrix = _ref.DenseMatrix;
28711 var algorithm01 = createAlgorithm01({
28712 typed: typed
28713 });
28714 var algorithm02 = createAlgorithm02({
28715 typed: typed,
28716 equalScalar: equalScalar
28717 });
28718 var algorithm08 = createAlgorithm08({
28719 typed: typed,
28720 equalScalar: equalScalar
28721 });
28722 var algorithm10 = createAlgorithm10({
28723 typed: typed,
28724 DenseMatrix: DenseMatrix
28725 });
28726 var algorithm11 = createAlgorithm11({
28727 typed: typed,
28728 equalScalar: equalScalar
28729 });
28730 var algorithm13 = createAlgorithm13({
28731 typed: typed
28732 });
28733 var algorithm14 = createAlgorithm14({
28734 typed: typed
28735 });
28736 /**
28737 * Bitwise left logical shift of a value x by y number of bits, `x << y`.
28738 * For matrices, the function is evaluated element wise.
28739 * For units, the function is evaluated on the best prefix base.
28740 *
28741 * Syntax:
28742 *
28743 * math.leftShift(x, y)
28744 *
28745 * Examples:
28746 *
28747 * math.leftShift(1, 2) // returns number 4
28748 *
28749 * math.leftShift([1, 2, 3], 4) // returns Array [16, 32, 64]
28750 *
28751 * See also:
28752 *
28753 * leftShift, bitNot, bitOr, bitXor, rightArithShift, rightLogShift
28754 *
28755 * @param {number | BigNumber | Array | Matrix} x Value to be shifted
28756 * @param {number | BigNumber} y Amount of shifts
28757 * @return {number | BigNumber | Array | Matrix} `x` shifted left `y` times
28758 */
28759
28760 var leftShift = typed(leftShift_name, {
28761 'number, number': leftShiftNumber,
28762 'BigNumber, BigNumber': leftShiftBigNumber,
28763 'SparseMatrix, SparseMatrix': function SparseMatrixSparseMatrix(x, y) {
28764 return algorithm08(x, y, leftShift, false);
28765 },
28766 'SparseMatrix, DenseMatrix': function SparseMatrixDenseMatrix(x, y) {
28767 return algorithm02(y, x, leftShift, true);
28768 },
28769 'DenseMatrix, SparseMatrix': function DenseMatrixSparseMatrix(x, y) {
28770 return algorithm01(x, y, leftShift, false);
28771 },
28772 'DenseMatrix, DenseMatrix': function DenseMatrixDenseMatrix(x, y) {
28773 return algorithm13(x, y, leftShift);
28774 },
28775 'Array, Array': function ArrayArray(x, y) {
28776 // use matrix implementation
28777 return leftShift(matrix(x), matrix(y)).valueOf();
28778 },
28779 'Array, Matrix': function ArrayMatrix(x, y) {
28780 // use matrix implementation
28781 return leftShift(matrix(x), y);
28782 },
28783 'Matrix, Array': function MatrixArray(x, y) {
28784 // use matrix implementation
28785 return leftShift(x, matrix(y));
28786 },
28787 'SparseMatrix, number | BigNumber': function SparseMatrixNumberBigNumber(x, y) {
28788 // check scalar
28789 if (equalScalar(y, 0)) {
28790 return x.clone();
28791 }
28792
28793 return algorithm11(x, y, leftShift, false);
28794 },
28795 'DenseMatrix, number | BigNumber': function DenseMatrixNumberBigNumber(x, y) {
28796 // check scalar
28797 if (equalScalar(y, 0)) {
28798 return x.clone();
28799 }
28800
28801 return algorithm14(x, y, leftShift, false);
28802 },
28803 'number | BigNumber, SparseMatrix': function numberBigNumberSparseMatrix(x, y) {
28804 // check scalar
28805 if (equalScalar(x, 0)) {
28806 return zeros(y.size(), y.storage());
28807 }
28808
28809 return algorithm10(y, x, leftShift, true);
28810 },
28811 'number | BigNumber, DenseMatrix': function numberBigNumberDenseMatrix(x, y) {
28812 // check scalar
28813 if (equalScalar(x, 0)) {
28814 return zeros(y.size(), y.storage());
28815 }
28816
28817 return algorithm14(y, x, leftShift, true);
28818 },
28819 'Array, number | BigNumber': function ArrayNumberBigNumber(x, y) {
28820 // use matrix implementation
28821 return leftShift(matrix(x), y).valueOf();
28822 },
28823 'number | BigNumber, Array': function numberBigNumberArray(x, y) {
28824 // use matrix implementation
28825 return leftShift(x, matrix(y)).valueOf();
28826 }
28827 });
28828 return leftShift;
28829});
28830// CONCATENATED MODULE: ./src/function/bitwise/rightArithShift.js
28831
28832
28833
28834
28835
28836
28837
28838
28839
28840
28841var rightArithShift_name = 'rightArithShift';
28842var rightArithShift_dependencies = ['typed', 'matrix', 'equalScalar', 'zeros', 'DenseMatrix'];
28843var createRightArithShift =
28844/* #__PURE__ */
28845Object(factory["a" /* factory */])(rightArithShift_name, rightArithShift_dependencies, function (_ref) {
28846 var typed = _ref.typed,
28847 matrix = _ref.matrix,
28848 equalScalar = _ref.equalScalar,
28849 zeros = _ref.zeros,
28850 DenseMatrix = _ref.DenseMatrix;
28851 var algorithm01 = createAlgorithm01({
28852 typed: typed
28853 });
28854 var algorithm02 = createAlgorithm02({
28855 typed: typed,
28856 equalScalar: equalScalar
28857 });
28858 var algorithm08 = createAlgorithm08({
28859 typed: typed,
28860 equalScalar: equalScalar
28861 });
28862 var algorithm10 = createAlgorithm10({
28863 typed: typed,
28864 DenseMatrix: DenseMatrix
28865 });
28866 var algorithm11 = createAlgorithm11({
28867 typed: typed,
28868 equalScalar: equalScalar
28869 });
28870 var algorithm13 = createAlgorithm13({
28871 typed: typed
28872 });
28873 var algorithm14 = createAlgorithm14({
28874 typed: typed
28875 });
28876 /**
28877 * Bitwise right arithmetic shift of a value x by y number of bits, `x >> y`.
28878 * For matrices, the function is evaluated element wise.
28879 * For units, the function is evaluated on the best prefix base.
28880 *
28881 * Syntax:
28882 *
28883 * math.rightArithShift(x, y)
28884 *
28885 * Examples:
28886 *
28887 * math.rightArithShift(4, 2) // returns number 1
28888 *
28889 * math.rightArithShift([16, -32, 64], 4) // returns Array [1, -2, 3]
28890 *
28891 * See also:
28892 *
28893 * bitAnd, bitNot, bitOr, bitXor, rightArithShift, rightLogShift
28894 *
28895 * @param {number | BigNumber | Array | Matrix} x Value to be shifted
28896 * @param {number | BigNumber} y Amount of shifts
28897 * @return {number | BigNumber | Array | Matrix} `x` sign-filled shifted right `y` times
28898 */
28899
28900 var rightArithShift = typed(rightArithShift_name, {
28901 'number, number': rightArithShiftNumber,
28902 'BigNumber, BigNumber': rightArithShiftBigNumber,
28903 'SparseMatrix, SparseMatrix': function SparseMatrixSparseMatrix(x, y) {
28904 return algorithm08(x, y, rightArithShift, false);
28905 },
28906 'SparseMatrix, DenseMatrix': function SparseMatrixDenseMatrix(x, y) {
28907 return algorithm02(y, x, rightArithShift, true);
28908 },
28909 'DenseMatrix, SparseMatrix': function DenseMatrixSparseMatrix(x, y) {
28910 return algorithm01(x, y, rightArithShift, false);
28911 },
28912 'DenseMatrix, DenseMatrix': function DenseMatrixDenseMatrix(x, y) {
28913 return algorithm13(x, y, rightArithShift);
28914 },
28915 'Array, Array': function ArrayArray(x, y) {
28916 // use matrix implementation
28917 return rightArithShift(matrix(x), matrix(y)).valueOf();
28918 },
28919 'Array, Matrix': function ArrayMatrix(x, y) {
28920 // use matrix implementation
28921 return rightArithShift(matrix(x), y);
28922 },
28923 'Matrix, Array': function MatrixArray(x, y) {
28924 // use matrix implementation
28925 return rightArithShift(x, matrix(y));
28926 },
28927 'SparseMatrix, number | BigNumber': function SparseMatrixNumberBigNumber(x, y) {
28928 // check scalar
28929 if (equalScalar(y, 0)) {
28930 return x.clone();
28931 }
28932
28933 return algorithm11(x, y, rightArithShift, false);
28934 },
28935 'DenseMatrix, number | BigNumber': function DenseMatrixNumberBigNumber(x, y) {
28936 // check scalar
28937 if (equalScalar(y, 0)) {
28938 return x.clone();
28939 }
28940
28941 return algorithm14(x, y, rightArithShift, false);
28942 },
28943 'number | BigNumber, SparseMatrix': function numberBigNumberSparseMatrix(x, y) {
28944 // check scalar
28945 if (equalScalar(x, 0)) {
28946 return zeros(y.size(), y.storage());
28947 }
28948
28949 return algorithm10(y, x, rightArithShift, true);
28950 },
28951 'number | BigNumber, DenseMatrix': function numberBigNumberDenseMatrix(x, y) {
28952 // check scalar
28953 if (equalScalar(x, 0)) {
28954 return zeros(y.size(), y.storage());
28955 }
28956
28957 return algorithm14(y, x, rightArithShift, true);
28958 },
28959 'Array, number | BigNumber': function ArrayNumberBigNumber(x, y) {
28960 // use matrix implementation
28961 return rightArithShift(matrix(x), y).valueOf();
28962 },
28963 'number | BigNumber, Array': function numberBigNumberArray(x, y) {
28964 // use matrix implementation
28965 return rightArithShift(x, matrix(y)).valueOf();
28966 }
28967 });
28968 return rightArithShift;
28969});
28970// CONCATENATED MODULE: ./src/function/bitwise/rightLogShift.js
28971
28972
28973
28974
28975
28976
28977
28978
28979
28980var rightLogShift_name = 'rightLogShift';
28981var rightLogShift_dependencies = ['typed', 'matrix', 'equalScalar', 'zeros', 'DenseMatrix'];
28982var createRightLogShift =
28983/* #__PURE__ */
28984Object(factory["a" /* factory */])(rightLogShift_name, rightLogShift_dependencies, function (_ref) {
28985 var typed = _ref.typed,
28986 matrix = _ref.matrix,
28987 equalScalar = _ref.equalScalar,
28988 zeros = _ref.zeros,
28989 DenseMatrix = _ref.DenseMatrix;
28990 var algorithm01 = createAlgorithm01({
28991 typed: typed
28992 });
28993 var algorithm02 = createAlgorithm02({
28994 typed: typed,
28995 equalScalar: equalScalar
28996 });
28997 var algorithm08 = createAlgorithm08({
28998 typed: typed,
28999 equalScalar: equalScalar
29000 });
29001 var algorithm10 = createAlgorithm10({
29002 typed: typed,
29003 DenseMatrix: DenseMatrix
29004 });
29005 var algorithm11 = createAlgorithm11({
29006 typed: typed,
29007 equalScalar: equalScalar
29008 });
29009 var algorithm13 = createAlgorithm13({
29010 typed: typed
29011 });
29012 var algorithm14 = createAlgorithm14({
29013 typed: typed
29014 });
29015 /**
29016 * Bitwise right logical shift of value x by y number of bits, `x >>> y`.
29017 * For matrices, the function is evaluated element wise.
29018 * For units, the function is evaluated on the best prefix base.
29019 *
29020 * Syntax:
29021 *
29022 * math.rightLogShift(x, y)
29023 *
29024 * Examples:
29025 *
29026 * math.rightLogShift(4, 2) // returns number 1
29027 *
29028 * math.rightLogShift([16, -32, 64], 4) // returns Array [1, 2, 3]
29029 *
29030 * See also:
29031 *
29032 * bitAnd, bitNot, bitOr, bitXor, leftShift, rightLogShift
29033 *
29034 * @param {number | Array | Matrix} x Value to be shifted
29035 * @param {number} y Amount of shifts
29036 * @return {number | Array | Matrix} `x` zero-filled shifted right `y` times
29037 */
29038
29039 var rightLogShift = typed(rightLogShift_name, {
29040 'number, number': rightLogShiftNumber,
29041 // 'BigNumber, BigNumber': ..., // TODO: implement BigNumber support for rightLogShift
29042 'SparseMatrix, SparseMatrix': function SparseMatrixSparseMatrix(x, y) {
29043 return algorithm08(x, y, rightLogShift, false);
29044 },
29045 'SparseMatrix, DenseMatrix': function SparseMatrixDenseMatrix(x, y) {
29046 return algorithm02(y, x, rightLogShift, true);
29047 },
29048 'DenseMatrix, SparseMatrix': function DenseMatrixSparseMatrix(x, y) {
29049 return algorithm01(x, y, rightLogShift, false);
29050 },
29051 'DenseMatrix, DenseMatrix': function DenseMatrixDenseMatrix(x, y) {
29052 return algorithm13(x, y, rightLogShift);
29053 },
29054 'Array, Array': function ArrayArray(x, y) {
29055 // use matrix implementation
29056 return rightLogShift(matrix(x), matrix(y)).valueOf();
29057 },
29058 'Array, Matrix': function ArrayMatrix(x, y) {
29059 // use matrix implementation
29060 return rightLogShift(matrix(x), y);
29061 },
29062 'Matrix, Array': function MatrixArray(x, y) {
29063 // use matrix implementation
29064 return rightLogShift(x, matrix(y));
29065 },
29066 'SparseMatrix, number | BigNumber': function SparseMatrixNumberBigNumber(x, y) {
29067 // check scalar
29068 if (equalScalar(y, 0)) {
29069 return x.clone();
29070 }
29071
29072 return algorithm11(x, y, rightLogShift, false);
29073 },
29074 'DenseMatrix, number | BigNumber': function DenseMatrixNumberBigNumber(x, y) {
29075 // check scalar
29076 if (equalScalar(y, 0)) {
29077 return x.clone();
29078 }
29079
29080 return algorithm14(x, y, rightLogShift, false);
29081 },
29082 'number | BigNumber, SparseMatrix': function numberBigNumberSparseMatrix(x, y) {
29083 // check scalar
29084 if (equalScalar(x, 0)) {
29085 return zeros(y.size(), y.storage());
29086 }
29087
29088 return algorithm10(y, x, rightLogShift, true);
29089 },
29090 'number | BigNumber, DenseMatrix': function numberBigNumberDenseMatrix(x, y) {
29091 // check scalar
29092 if (equalScalar(x, 0)) {
29093 return zeros(y.size(), y.storage());
29094 }
29095
29096 return algorithm14(y, x, rightLogShift, true);
29097 },
29098 'Array, number | BigNumber': function ArrayNumberBigNumber(x, y) {
29099 // use matrix implementation
29100 return rightLogShift(matrix(x), y).valueOf();
29101 },
29102 'number | BigNumber, Array': function numberBigNumberArray(x, y) {
29103 // use matrix implementation
29104 return rightLogShift(x, matrix(y)).valueOf();
29105 }
29106 });
29107 return rightLogShift;
29108});
29109// CONCATENATED MODULE: ./src/function/logical/and.js
29110
29111
29112
29113
29114
29115
29116
29117var and_name = 'and';
29118var and_dependencies = ['typed', 'matrix', 'equalScalar', 'zeros', 'not'];
29119var createAnd =
29120/* #__PURE__ */
29121Object(factory["a" /* factory */])(and_name, and_dependencies, function (_ref) {
29122 var typed = _ref.typed,
29123 matrix = _ref.matrix,
29124 equalScalar = _ref.equalScalar,
29125 zeros = _ref.zeros,
29126 not = _ref.not;
29127 var algorithm02 = createAlgorithm02({
29128 typed: typed,
29129 equalScalar: equalScalar
29130 });
29131 var algorithm06 = createAlgorithm06({
29132 typed: typed,
29133 equalScalar: equalScalar
29134 });
29135 var algorithm11 = createAlgorithm11({
29136 typed: typed,
29137 equalScalar: equalScalar
29138 });
29139 var algorithm13 = createAlgorithm13({
29140 typed: typed
29141 });
29142 var algorithm14 = createAlgorithm14({
29143 typed: typed
29144 });
29145 /**
29146 * Logical `and`. Test whether two values are both defined with a nonzero/nonempty value.
29147 * For matrices, the function is evaluated element wise.
29148 *
29149 * Syntax:
29150 *
29151 * math.and(x, y)
29152 *
29153 * Examples:
29154 *
29155 * math.and(2, 4) // returns true
29156 *
29157 * a = [2, 0, 0]
29158 * b = [3, 7, 0]
29159 * c = 0
29160 *
29161 * math.and(a, b) // returns [true, false, false]
29162 * math.and(a, c) // returns [false, false, false]
29163 *
29164 * See also:
29165 *
29166 * not, or, xor
29167 *
29168 * @param {number | BigNumber | Complex | Unit | Array | Matrix} x First value to check
29169 * @param {number | BigNumber | Complex | Unit | Array | Matrix} y Second value to check
29170 * @return {boolean | Array | Matrix}
29171 * Returns true when both inputs are defined with a nonzero/nonempty value.
29172 */
29173
29174 var and = typed(and_name, {
29175 'number, number': andNumber,
29176 'Complex, Complex': function ComplexComplex(x, y) {
29177 return (x.re !== 0 || x.im !== 0) && (y.re !== 0 || y.im !== 0);
29178 },
29179 'BigNumber, BigNumber': function BigNumberBigNumber(x, y) {
29180 return !x.isZero() && !y.isZero() && !x.isNaN() && !y.isNaN();
29181 },
29182 'Unit, Unit': function UnitUnit(x, y) {
29183 return and(x.value || 0, y.value || 0);
29184 },
29185 'SparseMatrix, SparseMatrix': function SparseMatrixSparseMatrix(x, y) {
29186 return algorithm06(x, y, and, false);
29187 },
29188 'SparseMatrix, DenseMatrix': function SparseMatrixDenseMatrix(x, y) {
29189 return algorithm02(y, x, and, true);
29190 },
29191 'DenseMatrix, SparseMatrix': function DenseMatrixSparseMatrix(x, y) {
29192 return algorithm02(x, y, and, false);
29193 },
29194 'DenseMatrix, DenseMatrix': function DenseMatrixDenseMatrix(x, y) {
29195 return algorithm13(x, y, and);
29196 },
29197 'Array, Array': function ArrayArray(x, y) {
29198 // use matrix implementation
29199 return and(matrix(x), matrix(y)).valueOf();
29200 },
29201 'Array, Matrix': function ArrayMatrix(x, y) {
29202 // use matrix implementation
29203 return and(matrix(x), y);
29204 },
29205 'Matrix, Array': function MatrixArray(x, y) {
29206 // use matrix implementation
29207 return and(x, matrix(y));
29208 },
29209 'SparseMatrix, any': function SparseMatrixAny(x, y) {
29210 // check scalar
29211 if (not(y)) {
29212 // return zero matrix
29213 return zeros(x.size(), x.storage());
29214 }
29215
29216 return algorithm11(x, y, and, false);
29217 },
29218 'DenseMatrix, any': function DenseMatrixAny(x, y) {
29219 // check scalar
29220 if (not(y)) {
29221 // return zero matrix
29222 return zeros(x.size(), x.storage());
29223 }
29224
29225 return algorithm14(x, y, and, false);
29226 },
29227 'any, SparseMatrix': function anySparseMatrix(x, y) {
29228 // check scalar
29229 if (not(x)) {
29230 // return zero matrix
29231 return zeros(x.size(), x.storage());
29232 }
29233
29234 return algorithm11(y, x, and, true);
29235 },
29236 'any, DenseMatrix': function anyDenseMatrix(x, y) {
29237 // check scalar
29238 if (not(x)) {
29239 // return zero matrix
29240 return zeros(x.size(), x.storage());
29241 }
29242
29243 return algorithm14(y, x, and, true);
29244 },
29245 'Array, any': function ArrayAny(x, y) {
29246 // use matrix implementation
29247 return and(matrix(x), y).valueOf();
29248 },
29249 'any, Array': function anyArray(x, y) {
29250 // use matrix implementation
29251 return and(x, matrix(y)).valueOf();
29252 }
29253 });
29254 return and;
29255});
29256// CONCATENATED MODULE: ./src/function/relational/compare.js
29257
29258
29259
29260
29261
29262
29263
29264
29265var compare_name = 'compare';
29266var compare_dependencies = ['typed', 'config', 'matrix', 'equalScalar', 'BigNumber', 'Fraction', 'DenseMatrix'];
29267var createCompare =
29268/* #__PURE__ */
29269Object(factory["a" /* factory */])(compare_name, compare_dependencies, function (_ref) {
29270 var typed = _ref.typed,
29271 config = _ref.config,
29272 equalScalar = _ref.equalScalar,
29273 matrix = _ref.matrix,
29274 BigNumber = _ref.BigNumber,
29275 Fraction = _ref.Fraction,
29276 DenseMatrix = _ref.DenseMatrix;
29277 var algorithm03 = createAlgorithm03({
29278 typed: typed
29279 });
29280 var algorithm05 = createAlgorithm05({
29281 typed: typed,
29282 equalScalar: equalScalar
29283 });
29284 var algorithm12 = createAlgorithm12({
29285 typed: typed,
29286 DenseMatrix: DenseMatrix
29287 });
29288 var algorithm13 = createAlgorithm13({
29289 typed: typed
29290 });
29291 var algorithm14 = createAlgorithm14({
29292 typed: typed
29293 });
29294 /**
29295 * Compare two values. Returns 1 when x > y, -1 when x < y, and 0 when x == y.
29296 *
29297 * x and y are considered equal when the relative difference between x and y
29298 * is smaller than the configured epsilon. The function cannot be used to
29299 * compare values smaller than approximately 2.22e-16.
29300 *
29301 * For matrices, the function is evaluated element wise.
29302 * Strings are compared by their numerical value.
29303 *
29304 * Syntax:
29305 *
29306 * math.compare(x, y)
29307 *
29308 * Examples:
29309 *
29310 * math.compare(6, 1) // returns 1
29311 * math.compare(2, 3) // returns -1
29312 * math.compare(7, 7) // returns 0
29313 * math.compare('10', '2') // returns 1
29314 * math.compare('1000', '1e3') // returns 0
29315 *
29316 * const a = math.unit('5 cm')
29317 * const b = math.unit('40 mm')
29318 * math.compare(a, b) // returns 1
29319 *
29320 * math.compare(2, [1, 2, 3]) // returns [1, 0, -1]
29321 *
29322 * See also:
29323 *
29324 * equal, unequal, smaller, smallerEq, larger, largerEq, compareNatural, compareText
29325 *
29326 * @param {number | BigNumber | Fraction | Unit | string | Array | Matrix} x First value to compare
29327 * @param {number | BigNumber | Fraction | Unit | string | Array | Matrix} y Second value to compare
29328 * @return {number | BigNumber | Fraction | Array | Matrix} Returns the result of the comparison:
29329 * 1 when x > y, -1 when x < y, and 0 when x == y.
29330 */
29331
29332 var compare = typed(compare_name, {
29333 'boolean, boolean': function booleanBoolean(x, y) {
29334 return x === y ? 0 : x > y ? 1 : -1;
29335 },
29336 'number, number': function numberNumber(x, y) {
29337 return Object(utils_number["m" /* nearlyEqual */])(x, y, config.epsilon) ? 0 : x > y ? 1 : -1;
29338 },
29339 'BigNumber, BigNumber': function BigNumberBigNumber(x, y) {
29340 return nearlyEqual(x, y, config.epsilon) ? new BigNumber(0) : new BigNumber(x.cmp(y));
29341 },
29342 'Fraction, Fraction': function FractionFraction(x, y) {
29343 return new Fraction(x.compare(y));
29344 },
29345 'Complex, Complex': function ComplexComplex() {
29346 throw new TypeError('No ordering relation is defined for complex numbers');
29347 },
29348 'Unit, Unit': function UnitUnit(x, y) {
29349 if (!x.equalBase(y)) {
29350 throw new Error('Cannot compare units with different base');
29351 }
29352
29353 return compare(x.value, y.value);
29354 },
29355 'SparseMatrix, SparseMatrix': function SparseMatrixSparseMatrix(x, y) {
29356 return algorithm05(x, y, compare);
29357 },
29358 'SparseMatrix, DenseMatrix': function SparseMatrixDenseMatrix(x, y) {
29359 return algorithm03(y, x, compare, true);
29360 },
29361 'DenseMatrix, SparseMatrix': function DenseMatrixSparseMatrix(x, y) {
29362 return algorithm03(x, y, compare, false);
29363 },
29364 'DenseMatrix, DenseMatrix': function DenseMatrixDenseMatrix(x, y) {
29365 return algorithm13(x, y, compare);
29366 },
29367 'Array, Array': function ArrayArray(x, y) {
29368 // use matrix implementation
29369 return compare(matrix(x), matrix(y)).valueOf();
29370 },
29371 'Array, Matrix': function ArrayMatrix(x, y) {
29372 // use matrix implementation
29373 return compare(matrix(x), y);
29374 },
29375 'Matrix, Array': function MatrixArray(x, y) {
29376 // use matrix implementation
29377 return compare(x, matrix(y));
29378 },
29379 'SparseMatrix, any': function SparseMatrixAny(x, y) {
29380 return algorithm12(x, y, compare, false);
29381 },
29382 'DenseMatrix, any': function DenseMatrixAny(x, y) {
29383 return algorithm14(x, y, compare, false);
29384 },
29385 'any, SparseMatrix': function anySparseMatrix(x, y) {
29386 return algorithm12(y, x, compare, true);
29387 },
29388 'any, DenseMatrix': function anyDenseMatrix(x, y) {
29389 return algorithm14(y, x, compare, true);
29390 },
29391 'Array, any': function ArrayAny(x, y) {
29392 // use matrix implementation
29393 return algorithm14(matrix(x), y, compare, false).valueOf();
29394 },
29395 'any, Array': function anyArray(x, y) {
29396 // use matrix implementation
29397 return algorithm14(matrix(y), x, compare, true).valueOf();
29398 }
29399 });
29400 return compare;
29401});
29402var createCompareNumber =
29403/* #__PURE__ */
29404Object(factory["a" /* factory */])(compare_name, ['typed', 'config'], function (_ref2) {
29405 var typed = _ref2.typed,
29406 config = _ref2.config;
29407 return typed(compare_name, {
29408 'number, number': function numberNumber(x, y) {
29409 return Object(utils_number["m" /* nearlyEqual */])(x, y, config.epsilon) ? 0 : x > y ? 1 : -1;
29410 }
29411 });
29412});
29413// EXTERNAL MODULE: ./node_modules/javascript-natural-sort/naturalSort.js
29414var naturalSort = __webpack_require__(12);
29415var naturalSort_default = /*#__PURE__*/__webpack_require__.n(naturalSort);
29416
29417// CONCATENATED MODULE: ./src/function/relational/compareNatural.js
29418
29419
29420
29421var compareNatural_name = 'compareNatural';
29422var compareNatural_dependencies = ['typed', 'compare'];
29423var createCompareNatural =
29424/* #__PURE__ */
29425Object(factory["a" /* factory */])(compareNatural_name, compareNatural_dependencies, function (_ref) {
29426 var typed = _ref.typed,
29427 compare = _ref.compare;
29428 var compareBooleans = compare.signatures['boolean,boolean'];
29429 /**
29430 * Compare two values of any type in a deterministic, natural way.
29431 *
29432 * For numeric values, the function works the same as `math.compare`.
29433 * For types of values that can't be compared mathematically,
29434 * the function compares in a natural way.
29435 *
29436 * For numeric values, x and y are considered equal when the relative
29437 * difference between x and y is smaller than the configured epsilon.
29438 * The function cannot be used to compare values smaller than
29439 * approximately 2.22e-16.
29440 *
29441 * For Complex numbers, first the real parts are compared. If equal,
29442 * the imaginary parts are compared.
29443 *
29444 * Strings are compared with a natural sorting algorithm, which
29445 * orders strings in a "logic" way following some heuristics.
29446 * This differs from the function `compare`, which converts the string
29447 * into a numeric value and compares that. The function `compareText`
29448 * on the other hand compares text lexically.
29449 *
29450 * Arrays and Matrices are compared value by value until there is an
29451 * unequal pair of values encountered. Objects are compared by sorted
29452 * keys until the keys or their values are unequal.
29453 *
29454 * Syntax:
29455 *
29456 * math.compareNatural(x, y)
29457 *
29458 * Examples:
29459 *
29460 * math.compareNatural(6, 1) // returns 1
29461 * math.compareNatural(2, 3) // returns -1
29462 * math.compareNatural(7, 7) // returns 0
29463 *
29464 * math.compareNatural('10', '2') // returns 1
29465 * math.compareText('10', '2') // returns -1
29466 * math.compare('10', '2') // returns 1
29467 *
29468 * math.compareNatural('Answer: 10', 'Answer: 2') // returns 1
29469 * math.compareText('Answer: 10', 'Answer: 2') // returns -1
29470 * math.compare('Answer: 10', 'Answer: 2')
29471 * // Error: Cannot convert "Answer: 10" to a number
29472 *
29473 * const a = math.unit('5 cm')
29474 * const b = math.unit('40 mm')
29475 * math.compareNatural(a, b) // returns 1
29476 *
29477 * const c = math.complex('2 + 3i')
29478 * const d = math.complex('2 + 4i')
29479 * math.compareNatural(c, d) // returns -1
29480 *
29481 * math.compareNatural([1, 2, 4], [1, 2, 3]) // returns 1
29482 * math.compareNatural([1, 2, 3], [1, 2]) // returns 1
29483 * math.compareNatural([1, 5], [1, 2, 3]) // returns 1
29484 * math.compareNatural([1, 2], [1, 2]) // returns 0
29485 *
29486 * math.compareNatural({a: 2}, {a: 4}) // returns -1
29487 *
29488 * See also:
29489 *
29490 * compare, compareText
29491 *
29492 * @param {*} x First value to compare
29493 * @param {*} y Second value to compare
29494 * @return {number} Returns the result of the comparison:
29495 * 1 when x > y, -1 when x < y, and 0 when x == y.
29496 */
29497
29498 var compareNatural = typed(compareNatural_name, {
29499 'any, any': function anyAny(x, y) {
29500 var typeX = Object(is["M" /* typeOf */])(x);
29501 var typeY = Object(is["M" /* typeOf */])(y);
29502 var c; // numeric types
29503
29504 if ((typeX === 'number' || typeX === 'BigNumber' || typeX === 'Fraction') && (typeY === 'number' || typeY === 'BigNumber' || typeY === 'Fraction')) {
29505 c = compare(x, y);
29506
29507 if (c.toString() !== '0') {
29508 // c can be number, BigNumber, or Fraction
29509 return c > 0 ? 1 : -1; // return a number
29510 } else {
29511 return naturalSort_default()(typeX, typeY);
29512 }
29513 } // matrix types
29514
29515
29516 if (typeX === 'Array' || typeX === 'Matrix' || typeY === 'Array' || typeY === 'Matrix') {
29517 c = compareMatricesAndArrays(x, y);
29518
29519 if (c !== 0) {
29520 return c;
29521 } else {
29522 return naturalSort_default()(typeX, typeY);
29523 }
29524 } // in case of different types, order by name of type, i.e. 'BigNumber' < 'Complex'
29525
29526
29527 if (typeX !== typeY) {
29528 return naturalSort_default()(typeX, typeY);
29529 }
29530
29531 if (typeX === 'Complex') {
29532 return compareComplexNumbers(x, y);
29533 }
29534
29535 if (typeX === 'Unit') {
29536 if (x.equalBase(y)) {
29537 return compareNatural(x.value, y.value);
29538 } // compare by units
29539
29540
29541 return compareArrays(x.formatUnits(), y.formatUnits());
29542 }
29543
29544 if (typeX === 'boolean') {
29545 return compareBooleans(x, y);
29546 }
29547
29548 if (typeX === 'string') {
29549 return naturalSort_default()(x, y);
29550 }
29551
29552 if (typeX === 'Object') {
29553 return compareObjects(x, y);
29554 }
29555
29556 if (typeX === 'null') {
29557 return 0;
29558 }
29559
29560 if (typeX === 'undefined') {
29561 return 0;
29562 } // this should not occur...
29563
29564
29565 throw new TypeError('Unsupported type of value "' + typeX + '"');
29566 }
29567 });
29568 /**
29569 * Compare mixed matrix/array types, by converting to same-shaped array.
29570 * This comparator is non-deterministic regarding input types.
29571 * @param {Array | SparseMatrix | DenseMatrix | *} x
29572 * @param {Array | SparseMatrix | DenseMatrix | *} y
29573 * @returns {number} Returns the comparison result: -1, 0, or 1
29574 */
29575
29576 function compareMatricesAndArrays(x, y) {
29577 if (Object(is["H" /* isSparseMatrix */])(x) && Object(is["H" /* isSparseMatrix */])(y)) {
29578 return compareArrays(x.toJSON().values, y.toJSON().values);
29579 }
29580
29581 if (Object(is["H" /* isSparseMatrix */])(x)) {
29582 // note: convert to array is expensive
29583 return compareMatricesAndArrays(x.toArray(), y);
29584 }
29585
29586 if (Object(is["H" /* isSparseMatrix */])(y)) {
29587 // note: convert to array is expensive
29588 return compareMatricesAndArrays(x, y.toArray());
29589 } // convert DenseArray into Array
29590
29591
29592 if (Object(is["n" /* isDenseMatrix */])(x)) {
29593 return compareMatricesAndArrays(x.toJSON().data, y);
29594 }
29595
29596 if (Object(is["n" /* isDenseMatrix */])(y)) {
29597 return compareMatricesAndArrays(x, y.toJSON().data);
29598 } // convert scalars to array
29599
29600
29601 if (!Array.isArray(x)) {
29602 return compareMatricesAndArrays([x], y);
29603 }
29604
29605 if (!Array.isArray(y)) {
29606 return compareMatricesAndArrays(x, [y]);
29607 }
29608
29609 return compareArrays(x, y);
29610 }
29611 /**
29612 * Compare two Arrays
29613 *
29614 * - First, compares value by value
29615 * - Next, if all corresponding values are equal,
29616 * look at the length: longest array will be considered largest
29617 *
29618 * @param {Array} x
29619 * @param {Array} y
29620 * @returns {number} Returns the comparison result: -1, 0, or 1
29621 */
29622
29623
29624 function compareArrays(x, y) {
29625 // compare each value
29626 for (var i = 0, ii = Math.min(x.length, y.length); i < ii; i++) {
29627 var v = compareNatural(x[i], y[i]);
29628
29629 if (v !== 0) {
29630 return v;
29631 }
29632 } // compare the size of the arrays
29633
29634
29635 if (x.length > y.length) {
29636 return 1;
29637 }
29638
29639 if (x.length < y.length) {
29640 return -1;
29641 } // both Arrays have equal size and content
29642
29643
29644 return 0;
29645 }
29646 /**
29647 * Compare two objects
29648 *
29649 * - First, compare sorted property names
29650 * - Next, compare the property values
29651 *
29652 * @param {Object} x
29653 * @param {Object} y
29654 * @returns {number} Returns the comparison result: -1, 0, or 1
29655 */
29656
29657
29658 function compareObjects(x, y) {
29659 var keysX = Object.keys(x);
29660 var keysY = Object.keys(y); // compare keys
29661
29662 keysX.sort(naturalSort_default.a);
29663 keysY.sort(naturalSort_default.a);
29664 var c = compareArrays(keysX, keysY);
29665
29666 if (c !== 0) {
29667 return c;
29668 } // compare values
29669
29670
29671 for (var i = 0; i < keysX.length; i++) {
29672 var v = compareNatural(x[keysX[i]], y[keysY[i]]);
29673
29674 if (v !== 0) {
29675 return v;
29676 }
29677 }
29678
29679 return 0;
29680 }
29681
29682 return compareNatural;
29683});
29684/**
29685 * Compare two complex numbers, `x` and `y`:
29686 *
29687 * - First, compare the real values of `x` and `y`
29688 * - If equal, compare the imaginary values of `x` and `y`
29689 *
29690 * @params {Complex} x
29691 * @params {Complex} y
29692 * @returns {number} Returns the comparison result: -1, 0, or 1
29693 */
29694
29695function compareComplexNumbers(x, y) {
29696 if (x.re > y.re) {
29697 return 1;
29698 }
29699
29700 if (x.re < y.re) {
29701 return -1;
29702 }
29703
29704 if (x.im > y.im) {
29705 return 1;
29706 }
29707
29708 if (x.im < y.im) {
29709 return -1;
29710 }
29711
29712 return 0;
29713}
29714// CONCATENATED MODULE: ./src/function/relational/compareText.js
29715
29716
29717
29718
29719var compareText_name = 'compareText';
29720var compareText_dependencies = ['typed', 'matrix'];
29721var createCompareText =
29722/* #__PURE__ */
29723Object(factory["a" /* factory */])(compareText_name, compareText_dependencies, function (_ref) {
29724 var typed = _ref.typed,
29725 matrix = _ref.matrix;
29726 var algorithm13 = createAlgorithm13({
29727 typed: typed
29728 });
29729 var algorithm14 = createAlgorithm14({
29730 typed: typed
29731 });
29732 /**
29733 * Compare two strings lexically. Comparison is case sensitive.
29734 * Returns 1 when x > y, -1 when x < y, and 0 when x == y.
29735 *
29736 * For matrices, the function is evaluated element wise.
29737 *
29738 * Syntax:
29739 *
29740 * math.compareText(x, y)
29741 *
29742 * Examples:
29743 *
29744 * math.compareText('B', 'A') // returns 1
29745 * math.compareText('2', '10') // returns 1
29746 * math.compare('2', '10') // returns -1
29747 * math.compareNatural('2', '10') // returns -1
29748 *
29749 * math.compareText('B', ['A', 'B', 'C']) // returns [1, 0, -1]
29750 *
29751 * See also:
29752 *
29753 * equal, equalText, compare, compareNatural
29754 *
29755 * @param {string | Array | DenseMatrix} x First string to compare
29756 * @param {string | Array | DenseMatrix} y Second string to compare
29757 * @return {number | Array | DenseMatrix} Returns the result of the comparison:
29758 * 1 when x > y, -1 when x < y, and 0 when x == y.
29759 */
29760
29761 var compareText = typed(compareText_name, {
29762 'any, any': utils_string["a" /* compareText */],
29763 'DenseMatrix, DenseMatrix': function DenseMatrixDenseMatrix(x, y) {
29764 return algorithm13(x, y, utils_string["a" /* compareText */]);
29765 },
29766 'Array, Array': function ArrayArray(x, y) {
29767 // use matrix implementation
29768 return compareText(matrix(x), matrix(y)).valueOf();
29769 },
29770 'Array, Matrix': function ArrayMatrix(x, y) {
29771 // use matrix implementation
29772 return compareText(matrix(x), y);
29773 },
29774 'Matrix, Array': function MatrixArray(x, y) {
29775 // use matrix implementation
29776 return compareText(x, matrix(y));
29777 },
29778 'DenseMatrix, any': function DenseMatrixAny(x, y) {
29779 return algorithm14(x, y, utils_string["a" /* compareText */], false);
29780 },
29781 'any, DenseMatrix': function anyDenseMatrix(x, y) {
29782 return algorithm14(y, x, utils_string["a" /* compareText */], true);
29783 },
29784 'Array, any': function ArrayAny(x, y) {
29785 // use matrix implementation
29786 return algorithm14(matrix(x), y, utils_string["a" /* compareText */], false).valueOf();
29787 },
29788 'any, Array': function anyArray(x, y) {
29789 // use matrix implementation
29790 return algorithm14(matrix(y), x, utils_string["a" /* compareText */], true).valueOf();
29791 }
29792 });
29793 return compareText;
29794});
29795var createCompareTextNumber =
29796/* #__PURE__ */
29797Object(factory["a" /* factory */])(compareText_name, ['typed'], function (_ref2) {
29798 var typed = _ref2.typed;
29799 return typed(compareText_name, {
29800 'any, any': utils_string["a" /* compareText */]
29801 });
29802});
29803// CONCATENATED MODULE: ./src/function/relational/equal.js
29804
29805
29806
29807
29808
29809
29810var equal_name = 'equal';
29811var equal_dependencies = ['typed', 'matrix', 'equalScalar', 'DenseMatrix'];
29812var createEqual =
29813/* #__PURE__ */
29814Object(factory["a" /* factory */])(equal_name, equal_dependencies, function (_ref) {
29815 var typed = _ref.typed,
29816 matrix = _ref.matrix,
29817 equalScalar = _ref.equalScalar,
29818 DenseMatrix = _ref.DenseMatrix;
29819 var algorithm03 = createAlgorithm03({
29820 typed: typed
29821 });
29822 var algorithm07 = createAlgorithm07({
29823 typed: typed,
29824 DenseMatrix: DenseMatrix
29825 });
29826 var algorithm12 = createAlgorithm12({
29827 typed: typed,
29828 DenseMatrix: DenseMatrix
29829 });
29830 var algorithm13 = createAlgorithm13({
29831 typed: typed
29832 });
29833 var algorithm14 = createAlgorithm14({
29834 typed: typed
29835 });
29836 /**
29837 * Test whether two values are equal.
29838 *
29839 * The function tests whether the relative difference between x and y is
29840 * smaller than the configured epsilon. The function cannot be used to
29841 * compare values smaller than approximately 2.22e-16.
29842 *
29843 * For matrices, the function is evaluated element wise.
29844 * In case of complex numbers, x.re must equal y.re, and x.im must equal y.im.
29845 *
29846 * Values `null` and `undefined` are compared strictly, thus `null` is only
29847 * equal to `null` and nothing else, and `undefined` is only equal to
29848 * `undefined` and nothing else. Strings are compared by their numerical value.
29849 *
29850 * Syntax:
29851 *
29852 * math.equal(x, y)
29853 *
29854 * Examples:
29855 *
29856 * math.equal(2 + 2, 3) // returns false
29857 * math.equal(2 + 2, 4) // returns true
29858 *
29859 * const a = math.unit('50 cm')
29860 * const b = math.unit('5 m')
29861 * math.equal(a, b) // returns true
29862 *
29863 * const c = [2, 5, 1]
29864 * const d = [2, 7, 1]
29865 *
29866 * math.equal(c, d) // returns [true, false, true]
29867 * math.deepEqual(c, d) // returns false
29868 *
29869 * math.equal("1000", "1e3") // returns true
29870 * math.equal(0, null) // returns false
29871 *
29872 * See also:
29873 *
29874 * unequal, smaller, smallerEq, larger, largerEq, compare, deepEqual, equalText
29875 *
29876 * @param {number | BigNumber | boolean | Complex | Unit | string | Array | Matrix} x First value to compare
29877 * @param {number | BigNumber | boolean | Complex | Unit | string | Array | Matrix} y Second value to compare
29878 * @return {boolean | Array | Matrix} Returns true when the compared values are equal, else returns false
29879 */
29880
29881 var equal = typed(equal_name, {
29882 'any, any': function anyAny(x, y) {
29883 // strict equality for null and undefined?
29884 if (x === null) {
29885 return y === null;
29886 }
29887
29888 if (y === null) {
29889 return x === null;
29890 }
29891
29892 if (x === undefined) {
29893 return y === undefined;
29894 }
29895
29896 if (y === undefined) {
29897 return x === undefined;
29898 }
29899
29900 return equalScalar(x, y);
29901 },
29902 'SparseMatrix, SparseMatrix': function SparseMatrixSparseMatrix(x, y) {
29903 return algorithm07(x, y, equalScalar);
29904 },
29905 'SparseMatrix, DenseMatrix': function SparseMatrixDenseMatrix(x, y) {
29906 return algorithm03(y, x, equalScalar, true);
29907 },
29908 'DenseMatrix, SparseMatrix': function DenseMatrixSparseMatrix(x, y) {
29909 return algorithm03(x, y, equalScalar, false);
29910 },
29911 'DenseMatrix, DenseMatrix': function DenseMatrixDenseMatrix(x, y) {
29912 return algorithm13(x, y, equalScalar);
29913 },
29914 'Array, Array': function ArrayArray(x, y) {
29915 // use matrix implementation
29916 return equal(matrix(x), matrix(y)).valueOf();
29917 },
29918 'Array, Matrix': function ArrayMatrix(x, y) {
29919 // use matrix implementation
29920 return equal(matrix(x), y);
29921 },
29922 'Matrix, Array': function MatrixArray(x, y) {
29923 // use matrix implementation
29924 return equal(x, matrix(y));
29925 },
29926 'SparseMatrix, any': function SparseMatrixAny(x, y) {
29927 return algorithm12(x, y, equalScalar, false);
29928 },
29929 'DenseMatrix, any': function DenseMatrixAny(x, y) {
29930 return algorithm14(x, y, equalScalar, false);
29931 },
29932 'any, SparseMatrix': function anySparseMatrix(x, y) {
29933 return algorithm12(y, x, equalScalar, true);
29934 },
29935 'any, DenseMatrix': function anyDenseMatrix(x, y) {
29936 return algorithm14(y, x, equalScalar, true);
29937 },
29938 'Array, any': function ArrayAny(x, y) {
29939 // use matrix implementation
29940 return algorithm14(matrix(x), y, equalScalar, false).valueOf();
29941 },
29942 'any, Array': function anyArray(x, y) {
29943 // use matrix implementation
29944 return algorithm14(matrix(y), x, equalScalar, true).valueOf();
29945 }
29946 });
29947 return equal;
29948});
29949var createEqualNumber = Object(factory["a" /* factory */])(equal_name, ['typed', 'equalScalar'], function (_ref2) {
29950 var typed = _ref2.typed,
29951 equalScalar = _ref2.equalScalar;
29952 return typed(equal_name, {
29953 'any, any': function anyAny(x, y) {
29954 // strict equality for null and undefined?
29955 if (x === null) {
29956 return y === null;
29957 }
29958
29959 if (y === null) {
29960 return x === null;
29961 }
29962
29963 if (x === undefined) {
29964 return y === undefined;
29965 }
29966
29967 if (y === undefined) {
29968 return x === undefined;
29969 }
29970
29971 return equalScalar(x, y);
29972 }
29973 });
29974});
29975// CONCATENATED MODULE: ./src/function/relational/equalText.js
29976
29977var equalText_name = 'equalText';
29978var equalText_dependencies = ['typed', 'compareText', 'isZero'];
29979var createEqualText =
29980/* #__PURE__ */
29981Object(factory["a" /* factory */])(equalText_name, equalText_dependencies, function (_ref) {
29982 var typed = _ref.typed,
29983 compareText = _ref.compareText,
29984 isZero = _ref.isZero;
29985
29986 /**
29987 * Check equality of two strings. Comparison is case sensitive.
29988 *
29989 * For matrices, the function is evaluated element wise.
29990 *
29991 * Syntax:
29992 *
29993 * math.equalText(x, y)
29994 *
29995 * Examples:
29996 *
29997 * math.equalText('Hello', 'Hello') // returns true
29998 * math.equalText('a', 'A') // returns false
29999 * math.equal('2e3', '2000') // returns true
30000 * math.equalText('2e3', '2000') // returns false
30001 *
30002 * math.equalText('B', ['A', 'B', 'C']) // returns [false, true, false]
30003 *
30004 * See also:
30005 *
30006 * equal, compareText, compare, compareNatural
30007 *
30008 * @param {string | Array | DenseMatrix} x First string to compare
30009 * @param {string | Array | DenseMatrix} y Second string to compare
30010 * @return {number | Array | DenseMatrix} Returns true if the values are equal, and false if not.
30011 */
30012 return typed(equalText_name, {
30013 'any, any': function anyAny(x, y) {
30014 return isZero(compareText(x, y));
30015 }
30016 });
30017});
30018// CONCATENATED MODULE: ./src/function/relational/smaller.js
30019
30020
30021
30022
30023
30024
30025
30026
30027var smaller_name = 'smaller';
30028var smaller_dependencies = ['typed', 'config', 'matrix', 'DenseMatrix'];
30029var createSmaller =
30030/* #__PURE__ */
30031Object(factory["a" /* factory */])(smaller_name, smaller_dependencies, function (_ref) {
30032 var typed = _ref.typed,
30033 config = _ref.config,
30034 matrix = _ref.matrix,
30035 DenseMatrix = _ref.DenseMatrix;
30036 var algorithm03 = createAlgorithm03({
30037 typed: typed
30038 });
30039 var algorithm07 = createAlgorithm07({
30040 typed: typed,
30041 DenseMatrix: DenseMatrix
30042 });
30043 var algorithm12 = createAlgorithm12({
30044 typed: typed,
30045 DenseMatrix: DenseMatrix
30046 });
30047 var algorithm13 = createAlgorithm13({
30048 typed: typed
30049 });
30050 var algorithm14 = createAlgorithm14({
30051 typed: typed
30052 });
30053 /**
30054 * Test whether value x is smaller than y.
30055 *
30056 * The function returns true when x is smaller than y and the relative
30057 * difference between x and y is smaller than the configured epsilon. The
30058 * function cannot be used to compare values smaller than approximately 2.22e-16.
30059 *
30060 * For matrices, the function is evaluated element wise.
30061 * Strings are compared by their numerical value.
30062 *
30063 * Syntax:
30064 *
30065 * math.smaller(x, y)
30066 *
30067 * Examples:
30068 *
30069 * math.smaller(2, 3) // returns true
30070 * math.smaller(5, 2 * 2) // returns false
30071 *
30072 * const a = math.unit('5 cm')
30073 * const b = math.unit('2 inch')
30074 * math.smaller(a, b) // returns true
30075 *
30076 * See also:
30077 *
30078 * equal, unequal, smallerEq, smaller, smallerEq, compare
30079 *
30080 * @param {number | BigNumber | Fraction | boolean | Unit | string | Array | Matrix} x First value to compare
30081 * @param {number | BigNumber | Fraction | boolean | Unit | string | Array | Matrix} y Second value to compare
30082 * @return {boolean | Array | Matrix} Returns true when the x is smaller than y, else returns false
30083 */
30084
30085 var smaller = typed(smaller_name, {
30086 'boolean, boolean': function booleanBoolean(x, y) {
30087 return x < y;
30088 },
30089 'number, number': function numberNumber(x, y) {
30090 return x < y && !Object(utils_number["m" /* nearlyEqual */])(x, y, config.epsilon);
30091 },
30092 'BigNumber, BigNumber': function BigNumberBigNumber(x, y) {
30093 return x.lt(y) && !nearlyEqual(x, y, config.epsilon);
30094 },
30095 'Fraction, Fraction': function FractionFraction(x, y) {
30096 return x.compare(y) === -1;
30097 },
30098 'Complex, Complex': function ComplexComplex(x, y) {
30099 throw new TypeError('No ordering relation is defined for complex numbers');
30100 },
30101 'Unit, Unit': function UnitUnit(x, y) {
30102 if (!x.equalBase(y)) {
30103 throw new Error('Cannot compare units with different base');
30104 }
30105
30106 return smaller(x.value, y.value);
30107 },
30108 'SparseMatrix, SparseMatrix': function SparseMatrixSparseMatrix(x, y) {
30109 return algorithm07(x, y, smaller);
30110 },
30111 'SparseMatrix, DenseMatrix': function SparseMatrixDenseMatrix(x, y) {
30112 return algorithm03(y, x, smaller, true);
30113 },
30114 'DenseMatrix, SparseMatrix': function DenseMatrixSparseMatrix(x, y) {
30115 return algorithm03(x, y, smaller, false);
30116 },
30117 'DenseMatrix, DenseMatrix': function DenseMatrixDenseMatrix(x, y) {
30118 return algorithm13(x, y, smaller);
30119 },
30120 'Array, Array': function ArrayArray(x, y) {
30121 // use matrix implementation
30122 return smaller(matrix(x), matrix(y)).valueOf();
30123 },
30124 'Array, Matrix': function ArrayMatrix(x, y) {
30125 // use matrix implementation
30126 return smaller(matrix(x), y);
30127 },
30128 'Matrix, Array': function MatrixArray(x, y) {
30129 // use matrix implementation
30130 return smaller(x, matrix(y));
30131 },
30132 'SparseMatrix, any': function SparseMatrixAny(x, y) {
30133 return algorithm12(x, y, smaller, false);
30134 },
30135 'DenseMatrix, any': function DenseMatrixAny(x, y) {
30136 return algorithm14(x, y, smaller, false);
30137 },
30138 'any, SparseMatrix': function anySparseMatrix(x, y) {
30139 return algorithm12(y, x, smaller, true);
30140 },
30141 'any, DenseMatrix': function anyDenseMatrix(x, y) {
30142 return algorithm14(y, x, smaller, true);
30143 },
30144 'Array, any': function ArrayAny(x, y) {
30145 // use matrix implementation
30146 return algorithm14(matrix(x), y, smaller, false).valueOf();
30147 },
30148 'any, Array': function anyArray(x, y) {
30149 // use matrix implementation
30150 return algorithm14(matrix(y), x, smaller, true).valueOf();
30151 }
30152 });
30153 return smaller;
30154});
30155var createSmallerNumber =
30156/* #__PURE__ */
30157Object(factory["a" /* factory */])(smaller_name, ['typed', 'config'], function (_ref2) {
30158 var typed = _ref2.typed,
30159 config = _ref2.config;
30160 return typed(smaller_name, {
30161 'number, number': function numberNumber(x, y) {
30162 return x < y && !Object(utils_number["m" /* nearlyEqual */])(x, y, config.epsilon);
30163 }
30164 });
30165});
30166// CONCATENATED MODULE: ./src/function/relational/smallerEq.js
30167
30168
30169
30170
30171
30172
30173
30174
30175var smallerEq_name = 'smallerEq';
30176var smallerEq_dependencies = ['typed', 'config', 'matrix', 'DenseMatrix'];
30177var createSmallerEq =
30178/* #__PURE__ */
30179Object(factory["a" /* factory */])(smallerEq_name, smallerEq_dependencies, function (_ref) {
30180 var typed = _ref.typed,
30181 config = _ref.config,
30182 matrix = _ref.matrix,
30183 DenseMatrix = _ref.DenseMatrix;
30184 var algorithm03 = createAlgorithm03({
30185 typed: typed
30186 });
30187 var algorithm07 = createAlgorithm07({
30188 typed: typed,
30189 DenseMatrix: DenseMatrix
30190 });
30191 var algorithm12 = createAlgorithm12({
30192 typed: typed,
30193 DenseMatrix: DenseMatrix
30194 });
30195 var algorithm13 = createAlgorithm13({
30196 typed: typed
30197 });
30198 var algorithm14 = createAlgorithm14({
30199 typed: typed
30200 });
30201 /**
30202 * Test whether value x is smaller or equal to y.
30203 *
30204 * The function returns true when x is smaller than y or the relative
30205 * difference between x and y is smaller than the configured epsilon. The
30206 * function cannot be used to compare values smaller than approximately 2.22e-16.
30207 *
30208 * For matrices, the function is evaluated element wise.
30209 * Strings are compared by their numerical value.
30210 *
30211 * Syntax:
30212 *
30213 * math.smallerEq(x, y)
30214 *
30215 * Examples:
30216 *
30217 * math.smaller(1 + 2, 3) // returns false
30218 * math.smallerEq(1 + 2, 3) // returns true
30219 *
30220 * See also:
30221 *
30222 * equal, unequal, smaller, larger, largerEq, compare
30223 *
30224 * @param {number | BigNumber | Fraction | boolean | Unit | string | Array | Matrix} x First value to compare
30225 * @param {number | BigNumber | Fraction | boolean | Unit | string | Array | Matrix} y Second value to compare
30226 * @return {boolean | Array | Matrix} Returns true when the x is smaller than y, else returns false
30227 */
30228
30229 var smallerEq = typed(smallerEq_name, {
30230 'boolean, boolean': function booleanBoolean(x, y) {
30231 return x <= y;
30232 },
30233 'number, number': function numberNumber(x, y) {
30234 return x <= y || Object(utils_number["m" /* nearlyEqual */])(x, y, config.epsilon);
30235 },
30236 'BigNumber, BigNumber': function BigNumberBigNumber(x, y) {
30237 return x.lte(y) || nearlyEqual(x, y, config.epsilon);
30238 },
30239 'Fraction, Fraction': function FractionFraction(x, y) {
30240 return x.compare(y) !== 1;
30241 },
30242 'Complex, Complex': function ComplexComplex() {
30243 throw new TypeError('No ordering relation is defined for complex numbers');
30244 },
30245 'Unit, Unit': function UnitUnit(x, y) {
30246 if (!x.equalBase(y)) {
30247 throw new Error('Cannot compare units with different base');
30248 }
30249
30250 return smallerEq(x.value, y.value);
30251 },
30252 'SparseMatrix, SparseMatrix': function SparseMatrixSparseMatrix(x, y) {
30253 return algorithm07(x, y, smallerEq);
30254 },
30255 'SparseMatrix, DenseMatrix': function SparseMatrixDenseMatrix(x, y) {
30256 return algorithm03(y, x, smallerEq, true);
30257 },
30258 'DenseMatrix, SparseMatrix': function DenseMatrixSparseMatrix(x, y) {
30259 return algorithm03(x, y, smallerEq, false);
30260 },
30261 'DenseMatrix, DenseMatrix': function DenseMatrixDenseMatrix(x, y) {
30262 return algorithm13(x, y, smallerEq);
30263 },
30264 'Array, Array': function ArrayArray(x, y) {
30265 // use matrix implementation
30266 return smallerEq(matrix(x), matrix(y)).valueOf();
30267 },
30268 'Array, Matrix': function ArrayMatrix(x, y) {
30269 // use matrix implementation
30270 return smallerEq(matrix(x), y);
30271 },
30272 'Matrix, Array': function MatrixArray(x, y) {
30273 // use matrix implementation
30274 return smallerEq(x, matrix(y));
30275 },
30276 'SparseMatrix, any': function SparseMatrixAny(x, y) {
30277 return algorithm12(x, y, smallerEq, false);
30278 },
30279 'DenseMatrix, any': function DenseMatrixAny(x, y) {
30280 return algorithm14(x, y, smallerEq, false);
30281 },
30282 'any, SparseMatrix': function anySparseMatrix(x, y) {
30283 return algorithm12(y, x, smallerEq, true);
30284 },
30285 'any, DenseMatrix': function anyDenseMatrix(x, y) {
30286 return algorithm14(y, x, smallerEq, true);
30287 },
30288 'Array, any': function ArrayAny(x, y) {
30289 // use matrix implementation
30290 return algorithm14(matrix(x), y, smallerEq, false).valueOf();
30291 },
30292 'any, Array': function anyArray(x, y) {
30293 // use matrix implementation
30294 return algorithm14(matrix(y), x, smallerEq, true).valueOf();
30295 }
30296 });
30297 return smallerEq;
30298});
30299var createSmallerEqNumber =
30300/* #__PURE__ */
30301Object(factory["a" /* factory */])(smallerEq_name, ['typed', 'config'], function (_ref2) {
30302 var typed = _ref2.typed,
30303 config = _ref2.config;
30304 return typed(smallerEq_name, {
30305 'number, number': function numberNumber(x, y) {
30306 return x <= y || Object(utils_number["m" /* nearlyEqual */])(x, y, config.epsilon);
30307 }
30308 });
30309});
30310// CONCATENATED MODULE: ./src/function/relational/larger.js
30311
30312
30313
30314
30315
30316
30317
30318
30319var larger_name = 'larger';
30320var larger_dependencies = ['typed', 'config', 'matrix', 'DenseMatrix'];
30321var createLarger =
30322/* #__PURE__ */
30323Object(factory["a" /* factory */])(larger_name, larger_dependencies, function (_ref) {
30324 var typed = _ref.typed,
30325 config = _ref.config,
30326 matrix = _ref.matrix,
30327 DenseMatrix = _ref.DenseMatrix;
30328 var algorithm03 = createAlgorithm03({
30329 typed: typed
30330 });
30331 var algorithm07 = createAlgorithm07({
30332 typed: typed,
30333 DenseMatrix: DenseMatrix
30334 });
30335 var algorithm12 = createAlgorithm12({
30336 typed: typed,
30337 DenseMatrix: DenseMatrix
30338 });
30339 var algorithm13 = createAlgorithm13({
30340 typed: typed
30341 });
30342 var algorithm14 = createAlgorithm14({
30343 typed: typed
30344 });
30345 /**
30346 * Test whether value x is larger than y.
30347 *
30348 * The function returns true when x is larger than y and the relative
30349 * difference between x and y is larger than the configured epsilon. The
30350 * function cannot be used to compare values smaller than approximately 2.22e-16.
30351 *
30352 * For matrices, the function is evaluated element wise.
30353 * Strings are compared by their numerical value.
30354 *
30355 * Syntax:
30356 *
30357 * math.larger(x, y)
30358 *
30359 * Examples:
30360 *
30361 * math.larger(2, 3) // returns false
30362 * math.larger(5, 2 + 2) // returns true
30363 *
30364 * const a = math.unit('5 cm')
30365 * const b = math.unit('2 inch')
30366 * math.larger(a, b) // returns false
30367 *
30368 * See also:
30369 *
30370 * equal, unequal, smaller, smallerEq, largerEq, compare
30371 *
30372 * @param {number | BigNumber | Fraction | boolean | Unit | string | Array | Matrix} x First value to compare
30373 * @param {number | BigNumber | Fraction | boolean | Unit | string | Array | Matrix} y Second value to compare
30374 * @return {boolean | Array | Matrix} Returns true when the x is larger than y, else returns false
30375 */
30376
30377 var larger = typed(larger_name, {
30378 'boolean, boolean': function booleanBoolean(x, y) {
30379 return x > y;
30380 },
30381 'number, number': function numberNumber(x, y) {
30382 return x > y && !Object(utils_number["m" /* nearlyEqual */])(x, y, config.epsilon);
30383 },
30384 'BigNumber, BigNumber': function BigNumberBigNumber(x, y) {
30385 return x.gt(y) && !nearlyEqual(x, y, config.epsilon);
30386 },
30387 'Fraction, Fraction': function FractionFraction(x, y) {
30388 return x.compare(y) === 1;
30389 },
30390 'Complex, Complex': function ComplexComplex() {
30391 throw new TypeError('No ordering relation is defined for complex numbers');
30392 },
30393 'Unit, Unit': function UnitUnit(x, y) {
30394 if (!x.equalBase(y)) {
30395 throw new Error('Cannot compare units with different base');
30396 }
30397
30398 return larger(x.value, y.value);
30399 },
30400 'SparseMatrix, SparseMatrix': function SparseMatrixSparseMatrix(x, y) {
30401 return algorithm07(x, y, larger);
30402 },
30403 'SparseMatrix, DenseMatrix': function SparseMatrixDenseMatrix(x, y) {
30404 return algorithm03(y, x, larger, true);
30405 },
30406 'DenseMatrix, SparseMatrix': function DenseMatrixSparseMatrix(x, y) {
30407 return algorithm03(x, y, larger, false);
30408 },
30409 'DenseMatrix, DenseMatrix': function DenseMatrixDenseMatrix(x, y) {
30410 return algorithm13(x, y, larger);
30411 },
30412 'Array, Array': function ArrayArray(x, y) {
30413 // use matrix implementation
30414 return larger(matrix(x), matrix(y)).valueOf();
30415 },
30416 'Array, Matrix': function ArrayMatrix(x, y) {
30417 // use matrix implementation
30418 return larger(matrix(x), y);
30419 },
30420 'Matrix, Array': function MatrixArray(x, y) {
30421 // use matrix implementation
30422 return larger(x, matrix(y));
30423 },
30424 'SparseMatrix, any': function SparseMatrixAny(x, y) {
30425 return algorithm12(x, y, larger, false);
30426 },
30427 'DenseMatrix, any': function DenseMatrixAny(x, y) {
30428 return algorithm14(x, y, larger, false);
30429 },
30430 'any, SparseMatrix': function anySparseMatrix(x, y) {
30431 return algorithm12(y, x, larger, true);
30432 },
30433 'any, DenseMatrix': function anyDenseMatrix(x, y) {
30434 return algorithm14(y, x, larger, true);
30435 },
30436 'Array, any': function ArrayAny(x, y) {
30437 // use matrix implementation
30438 return algorithm14(matrix(x), y, larger, false).valueOf();
30439 },
30440 'any, Array': function anyArray(x, y) {
30441 // use matrix implementation
30442 return algorithm14(matrix(y), x, larger, true).valueOf();
30443 }
30444 });
30445 return larger;
30446});
30447var createLargerNumber =
30448/* #__PURE__ */
30449Object(factory["a" /* factory */])(larger_name, ['typed', 'config'], function (_ref2) {
30450 var typed = _ref2.typed,
30451 config = _ref2.config;
30452 return typed(larger_name, {
30453 'number, number': function numberNumber(x, y) {
30454 return x > y && !Object(utils_number["m" /* nearlyEqual */])(x, y, config.epsilon);
30455 }
30456 });
30457});
30458// CONCATENATED MODULE: ./src/function/relational/largerEq.js
30459
30460
30461
30462
30463
30464
30465
30466
30467var largerEq_name = 'largerEq';
30468var largerEq_dependencies = ['typed', 'config', 'matrix', 'DenseMatrix'];
30469var createLargerEq =
30470/* #__PURE__ */
30471Object(factory["a" /* factory */])(largerEq_name, largerEq_dependencies, function (_ref) {
30472 var typed = _ref.typed,
30473 config = _ref.config,
30474 matrix = _ref.matrix,
30475 DenseMatrix = _ref.DenseMatrix;
30476 var algorithm03 = createAlgorithm03({
30477 typed: typed
30478 });
30479 var algorithm07 = createAlgorithm07({
30480 typed: typed,
30481 DenseMatrix: DenseMatrix
30482 });
30483 var algorithm12 = createAlgorithm12({
30484 typed: typed,
30485 DenseMatrix: DenseMatrix
30486 });
30487 var algorithm13 = createAlgorithm13({
30488 typed: typed
30489 });
30490 var algorithm14 = createAlgorithm14({
30491 typed: typed
30492 });
30493 /**
30494 * Test whether value x is larger or equal to y.
30495 *
30496 * The function returns true when x is larger than y or the relative
30497 * difference between x and y is smaller than the configured epsilon. The
30498 * function cannot be used to compare values smaller than approximately 2.22e-16.
30499 *
30500 * For matrices, the function is evaluated element wise.
30501 * Strings are compared by their numerical value.
30502 *
30503 * Syntax:
30504 *
30505 * math.largerEq(x, y)
30506 *
30507 * Examples:
30508 *
30509 * math.larger(2, 1 + 1) // returns false
30510 * math.largerEq(2, 1 + 1) // returns true
30511 *
30512 * See also:
30513 *
30514 * equal, unequal, smaller, smallerEq, larger, compare
30515 *
30516 * @param {number | BigNumber | Fraction | boolean | Unit | string | Array | Matrix} x First value to compare
30517 * @param {number | BigNumber | Fraction | boolean | Unit | string | Array | Matrix} y Second value to compare
30518 * @return {boolean | Array | Matrix} Returns true when the x is larger or equal to y, else returns false
30519 */
30520
30521 var largerEq = typed(largerEq_name, {
30522 'boolean, boolean': function booleanBoolean(x, y) {
30523 return x >= y;
30524 },
30525 'number, number': function numberNumber(x, y) {
30526 return x >= y || Object(utils_number["m" /* nearlyEqual */])(x, y, config.epsilon);
30527 },
30528 'BigNumber, BigNumber': function BigNumberBigNumber(x, y) {
30529 return x.gte(y) || nearlyEqual(x, y, config.epsilon);
30530 },
30531 'Fraction, Fraction': function FractionFraction(x, y) {
30532 return x.compare(y) !== -1;
30533 },
30534 'Complex, Complex': function ComplexComplex() {
30535 throw new TypeError('No ordering relation is defined for complex numbers');
30536 },
30537 'Unit, Unit': function UnitUnit(x, y) {
30538 if (!x.equalBase(y)) {
30539 throw new Error('Cannot compare units with different base');
30540 }
30541
30542 return largerEq(x.value, y.value);
30543 },
30544 'SparseMatrix, SparseMatrix': function SparseMatrixSparseMatrix(x, y) {
30545 return algorithm07(x, y, largerEq);
30546 },
30547 'SparseMatrix, DenseMatrix': function SparseMatrixDenseMatrix(x, y) {
30548 return algorithm03(y, x, largerEq, true);
30549 },
30550 'DenseMatrix, SparseMatrix': function DenseMatrixSparseMatrix(x, y) {
30551 return algorithm03(x, y, largerEq, false);
30552 },
30553 'DenseMatrix, DenseMatrix': function DenseMatrixDenseMatrix(x, y) {
30554 return algorithm13(x, y, largerEq);
30555 },
30556 'Array, Array': function ArrayArray(x, y) {
30557 // use matrix implementation
30558 return largerEq(matrix(x), matrix(y)).valueOf();
30559 },
30560 'Array, Matrix': function ArrayMatrix(x, y) {
30561 // use matrix implementation
30562 return largerEq(matrix(x), y);
30563 },
30564 'Matrix, Array': function MatrixArray(x, y) {
30565 // use matrix implementation
30566 return largerEq(x, matrix(y));
30567 },
30568 'SparseMatrix, any': function SparseMatrixAny(x, y) {
30569 return algorithm12(x, y, largerEq, false);
30570 },
30571 'DenseMatrix, any': function DenseMatrixAny(x, y) {
30572 return algorithm14(x, y, largerEq, false);
30573 },
30574 'any, SparseMatrix': function anySparseMatrix(x, y) {
30575 return algorithm12(y, x, largerEq, true);
30576 },
30577 'any, DenseMatrix': function anyDenseMatrix(x, y) {
30578 return algorithm14(y, x, largerEq, true);
30579 },
30580 'Array, any': function ArrayAny(x, y) {
30581 // use matrix implementation
30582 return algorithm14(matrix(x), y, largerEq, false).valueOf();
30583 },
30584 'any, Array': function anyArray(x, y) {
30585 // use matrix implementation
30586 return algorithm14(matrix(y), x, largerEq, true).valueOf();
30587 }
30588 });
30589 return largerEq;
30590});
30591var createLargerEqNumber =
30592/* #__PURE__ */
30593Object(factory["a" /* factory */])(largerEq_name, ['typed', 'config'], function (_ref2) {
30594 var typed = _ref2.typed,
30595 config = _ref2.config;
30596 return typed(largerEq_name, {
30597 'number, number': function numberNumber(x, y) {
30598 return x >= y || Object(utils_number["m" /* nearlyEqual */])(x, y, config.epsilon);
30599 }
30600 });
30601});
30602// CONCATENATED MODULE: ./src/function/relational/deepEqual.js
30603
30604var deepEqual_name = 'deepEqual';
30605var deepEqual_dependencies = ['typed', 'equal'];
30606var createDeepEqual =
30607/* #__PURE__ */
30608Object(factory["a" /* factory */])(deepEqual_name, deepEqual_dependencies, function (_ref) {
30609 var typed = _ref.typed,
30610 equal = _ref.equal;
30611
30612 /**
30613 * Test element wise whether two matrices are equal.
30614 * The function accepts both matrices and scalar values.
30615 *
30616 * Strings are compared by their numerical value.
30617 *
30618 * Syntax:
30619 *
30620 * math.deepEqual(x, y)
30621 *
30622 * Examples:
30623 *
30624 * math.deepEqual(2, 4) // returns false
30625 *
30626 * a = [2, 5, 1]
30627 * b = [2, 7, 1]
30628 *
30629 * math.deepEqual(a, b) // returns false
30630 * math.equal(a, b) // returns [true, false, true]
30631 *
30632 * See also:
30633 *
30634 * equal, unequal
30635 *
30636 * @param {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} x First matrix to compare
30637 * @param {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} y Second matrix to compare
30638 * @return {number | BigNumber | Fraction | Complex | Unit | Array | Matrix}
30639 * Returns true when the input matrices have the same size and each of their elements is equal.
30640 */
30641 return typed(deepEqual_name, {
30642 'any, any': function anyAny(x, y) {
30643 return _deepEqual(x.valueOf(), y.valueOf());
30644 }
30645 });
30646 /**
30647 * Test whether two arrays have the same size and all elements are equal
30648 * @param {Array | *} x
30649 * @param {Array | *} y
30650 * @return {boolean} Returns true if both arrays are deep equal
30651 */
30652
30653 function _deepEqual(x, y) {
30654 if (Array.isArray(x)) {
30655 if (Array.isArray(y)) {
30656 var len = x.length;
30657
30658 if (len !== y.length) {
30659 return false;
30660 }
30661
30662 for (var i = 0; i < len; i++) {
30663 if (!_deepEqual(x[i], y[i])) {
30664 return false;
30665 }
30666 }
30667
30668 return true;
30669 } else {
30670 return false;
30671 }
30672 } else {
30673 if (Array.isArray(y)) {
30674 return false;
30675 } else {
30676 return equal(x, y);
30677 }
30678 }
30679 }
30680});
30681// CONCATENATED MODULE: ./src/function/relational/unequal.js
30682
30683
30684
30685
30686
30687
30688var unequal_name = 'unequal';
30689var unequal_dependencies = ['typed', 'config', 'equalScalar', 'matrix', 'DenseMatrix'];
30690var createUnequal =
30691/* #__PURE__ */
30692Object(factory["a" /* factory */])(unequal_name, unequal_dependencies, function (_ref) {
30693 var typed = _ref.typed,
30694 config = _ref.config,
30695 equalScalar = _ref.equalScalar,
30696 matrix = _ref.matrix,
30697 DenseMatrix = _ref.DenseMatrix;
30698 var algorithm03 = createAlgorithm03({
30699 typed: typed
30700 });
30701 var algorithm07 = createAlgorithm07({
30702 typed: typed,
30703 DenseMatrix: DenseMatrix
30704 });
30705 var algorithm12 = createAlgorithm12({
30706 typed: typed,
30707 DenseMatrix: DenseMatrix
30708 });
30709 var algorithm13 = createAlgorithm13({
30710 typed: typed
30711 });
30712 var algorithm14 = createAlgorithm14({
30713 typed: typed
30714 });
30715 /**
30716 * Test whether two values are unequal.
30717 *
30718 * The function tests whether the relative difference between x and y is
30719 * larger than the configured epsilon. The function cannot be used to compare
30720 * values smaller than approximately 2.22e-16.
30721 *
30722 * For matrices, the function is evaluated element wise.
30723 * In case of complex numbers, x.re must unequal y.re, or x.im must unequal y.im.
30724 * Strings are compared by their numerical value.
30725 *
30726 * Values `null` and `undefined` are compared strictly, thus `null` is unequal
30727 * with everything except `null`, and `undefined` is unequal with everything
30728 * except `undefined`.
30729 *
30730 * Syntax:
30731 *
30732 * math.unequal(x, y)
30733 *
30734 * Examples:
30735 *
30736 * math.unequal(2 + 2, 3) // returns true
30737 * math.unequal(2 + 2, 4) // returns false
30738 *
30739 * const a = math.unit('50 cm')
30740 * const b = math.unit('5 m')
30741 * math.unequal(a, b) // returns false
30742 *
30743 * const c = [2, 5, 1]
30744 * const d = [2, 7, 1]
30745 *
30746 * math.unequal(c, d) // returns [false, true, false]
30747 * math.deepEqual(c, d) // returns false
30748 *
30749 * math.unequal(0, null) // returns true
30750 * See also:
30751 *
30752 * equal, deepEqual, smaller, smallerEq, larger, largerEq, compare
30753 *
30754 * @param {number | BigNumber | Fraction | boolean | Complex | Unit | string | Array | Matrix | undefined} x First value to compare
30755 * @param {number | BigNumber | Fraction | boolean | Complex | Unit | string | Array | Matrix | undefined} y Second value to compare
30756 * @return {boolean | Array | Matrix} Returns true when the compared values are unequal, else returns false
30757 */
30758
30759 var unequal = typed('unequal', {
30760 'any, any': function anyAny(x, y) {
30761 // strict equality for null and undefined?
30762 if (x === null) {
30763 return y !== null;
30764 }
30765
30766 if (y === null) {
30767 return x !== null;
30768 }
30769
30770 if (x === undefined) {
30771 return y !== undefined;
30772 }
30773
30774 if (y === undefined) {
30775 return x !== undefined;
30776 }
30777
30778 return _unequal(x, y);
30779 },
30780 'SparseMatrix, SparseMatrix': function SparseMatrixSparseMatrix(x, y) {
30781 return algorithm07(x, y, _unequal);
30782 },
30783 'SparseMatrix, DenseMatrix': function SparseMatrixDenseMatrix(x, y) {
30784 return algorithm03(y, x, _unequal, true);
30785 },
30786 'DenseMatrix, SparseMatrix': function DenseMatrixSparseMatrix(x, y) {
30787 return algorithm03(x, y, _unequal, false);
30788 },
30789 'DenseMatrix, DenseMatrix': function DenseMatrixDenseMatrix(x, y) {
30790 return algorithm13(x, y, _unequal);
30791 },
30792 'Array, Array': function ArrayArray(x, y) {
30793 // use matrix implementation
30794 return unequal(matrix(x), matrix(y)).valueOf();
30795 },
30796 'Array, Matrix': function ArrayMatrix(x, y) {
30797 // use matrix implementation
30798 return unequal(matrix(x), y);
30799 },
30800 'Matrix, Array': function MatrixArray(x, y) {
30801 // use matrix implementation
30802 return unequal(x, matrix(y));
30803 },
30804 'SparseMatrix, any': function SparseMatrixAny(x, y) {
30805 return algorithm12(x, y, _unequal, false);
30806 },
30807 'DenseMatrix, any': function DenseMatrixAny(x, y) {
30808 return algorithm14(x, y, _unequal, false);
30809 },
30810 'any, SparseMatrix': function anySparseMatrix(x, y) {
30811 return algorithm12(y, x, _unequal, true);
30812 },
30813 'any, DenseMatrix': function anyDenseMatrix(x, y) {
30814 return algorithm14(y, x, _unequal, true);
30815 },
30816 'Array, any': function ArrayAny(x, y) {
30817 // use matrix implementation
30818 return algorithm14(matrix(x), y, _unequal, false).valueOf();
30819 },
30820 'any, Array': function anyArray(x, y) {
30821 // use matrix implementation
30822 return algorithm14(matrix(y), x, _unequal, true).valueOf();
30823 }
30824 });
30825
30826 function _unequal(x, y) {
30827 return !equalScalar(x, y);
30828 }
30829
30830 return unequal;
30831});
30832var createUnequalNumber = Object(factory["a" /* factory */])(unequal_name, ['typed', 'equalScalar'], function (_ref2) {
30833 var typed = _ref2.typed,
30834 equalScalar = _ref2.equalScalar;
30835 return typed(unequal_name, {
30836 'any, any': function anyAny(x, y) {
30837 // strict equality for null and undefined?
30838 if (x === null) {
30839 return y !== null;
30840 }
30841
30842 if (y === null) {
30843 return x !== null;
30844 }
30845
30846 if (x === undefined) {
30847 return y !== undefined;
30848 }
30849
30850 if (y === undefined) {
30851 return x !== undefined;
30852 }
30853
30854 return !equalScalar(x, y);
30855 }
30856 });
30857});
30858// CONCATENATED MODULE: ./src/function/matrix/partitionSelect.js
30859
30860
30861
30862var partitionSelect_name = 'partitionSelect';
30863var partitionSelect_dependencies = ['typed', 'isNumeric', 'isNaN', 'compare'];
30864var createPartitionSelect =
30865/* #__PURE__ */
30866Object(factory["a" /* factory */])(partitionSelect_name, partitionSelect_dependencies, function (_ref) {
30867 var typed = _ref.typed,
30868 isNumeric = _ref.isNumeric,
30869 isNaN = _ref.isNaN,
30870 compare = _ref.compare;
30871 var asc = compare;
30872
30873 var desc = function desc(a, b) {
30874 return -compare(a, b);
30875 };
30876 /**
30877 * Partition-based selection of an array or 1D matrix.
30878 * Will find the kth smallest value, and mutates the input array.
30879 * Uses Quickselect.
30880 *
30881 * Syntax:
30882 *
30883 * math.partitionSelect(x, k)
30884 * math.partitionSelect(x, k, compare)
30885 *
30886 * Examples:
30887 *
30888 * math.partitionSelect([5, 10, 1], 2) // returns 10
30889 * math.partitionSelect(['C', 'B', 'A', 'D'], 1) // returns 'B'
30890 *
30891 * function sortByLength (a, b) {
30892 * return a.length - b.length
30893 * }
30894 * math.partitionSelect(['Langdon', 'Tom', 'Sara'], 2, sortByLength) // returns 'Langdon'
30895 *
30896 * See also:
30897 *
30898 * sort
30899 *
30900 * @param {Matrix | Array} x A one dimensional matrix or array to sort
30901 * @param {Number} k The kth smallest value to be retrieved zero-based index
30902 * @param {Function | 'asc' | 'desc'} [compare='asc']
30903 * An optional comparator function. The function is called as
30904 * `compare(a, b)`, and must return 1 when a > b, -1 when a < b,
30905 * and 0 when a == b.
30906 * @return {*} Returns the kth lowest value.
30907 */
30908
30909
30910 return typed(partitionSelect_name, {
30911 'Array | Matrix, number': function ArrayMatrixNumber(x, k) {
30912 return _partitionSelect(x, k, asc);
30913 },
30914 'Array | Matrix, number, string': function ArrayMatrixNumberString(x, k, compare) {
30915 if (compare === 'asc') {
30916 return _partitionSelect(x, k, asc);
30917 } else if (compare === 'desc') {
30918 return _partitionSelect(x, k, desc);
30919 } else {
30920 throw new Error('Compare string must be "asc" or "desc"');
30921 }
30922 },
30923 'Array | Matrix, number, function': _partitionSelect
30924 });
30925
30926 function _partitionSelect(x, k, compare) {
30927 if (!Object(utils_number["i" /* isInteger */])(k) || k < 0) {
30928 throw new Error('k must be a non-negative integer');
30929 }
30930
30931 if (Object(is["v" /* isMatrix */])(x)) {
30932 var size = x.size();
30933
30934 if (size.length > 1) {
30935 throw new Error('Only one dimensional matrices supported');
30936 }
30937
30938 return quickSelect(x.valueOf(), k, compare);
30939 }
30940
30941 if (Array.isArray(x)) {
30942 return quickSelect(x, k, compare);
30943 }
30944 }
30945 /**
30946 * Quickselect algorithm.
30947 * Code adapted from:
30948 * https://blog.teamleadnet.com/2012/07/quick-select-algorithm-find-kth-element.html
30949 *
30950 * @param {Array} arr
30951 * @param {Number} k
30952 * @param {Function} compare
30953 * @private
30954 */
30955
30956
30957 function quickSelect(arr, k, compare) {
30958 if (k >= arr.length) {
30959 throw new Error('k out of bounds');
30960 } // check for NaN values since these can cause an infinite while loop
30961
30962
30963 for (var i = 0; i < arr.length; i++) {
30964 if (isNumeric(arr[i]) && isNaN(arr[i])) {
30965 return arr[i]; // return NaN
30966 }
30967 }
30968
30969 var from = 0;
30970 var to = arr.length - 1; // if from == to we reached the kth element
30971
30972 while (from < to) {
30973 var r = from;
30974 var w = to;
30975 var pivot = arr[Math.floor(Math.random() * (to - from + 1)) + from]; // stop if the reader and writer meets
30976
30977 while (r < w) {
30978 // arr[r] >= pivot
30979 if (compare(arr[r], pivot) >= 0) {
30980 // put the large values at the end
30981 var tmp = arr[w];
30982 arr[w] = arr[r];
30983 arr[r] = tmp;
30984 --w;
30985 } else {
30986 // the value is smaller than the pivot, skip
30987 ++r;
30988 }
30989 } // if we stepped up (r++) we need to step one down (arr[r] > pivot)
30990
30991
30992 if (compare(arr[r], pivot) > 0) {
30993 --r;
30994 } // the r pointer is on the end of the first k elements
30995
30996
30997 if (k <= r) {
30998 to = r;
30999 } else {
31000 from = r + 1;
31001 }
31002 }
31003
31004 return arr[k];
31005 }
31006});
31007// CONCATENATED MODULE: ./src/function/matrix/sort.js
31008
31009
31010var sort_name = 'sort';
31011var sort_dependencies = ['typed', 'matrix', 'compare', 'compareNatural'];
31012var createSort =
31013/* #__PURE__ */
31014Object(factory["a" /* factory */])(sort_name, sort_dependencies, function (_ref) {
31015 var typed = _ref.typed,
31016 matrix = _ref.matrix,
31017 compare = _ref.compare,
31018 compareNatural = _ref.compareNatural;
31019 var compareAsc = compare;
31020
31021 var compareDesc = function compareDesc(a, b) {
31022 return -compare(a, b);
31023 };
31024 /**
31025 * Sort the items in a matrix.
31026 *
31027 * Syntax:
31028 *
31029 * math.sort(x)
31030 * math.sort(x, compare)
31031 *
31032 * Examples:
31033 *
31034 * math.sort([5, 10, 1]) // returns [1, 5, 10]
31035 * math.sort(['C', 'B', 'A', 'D'], math.compareNatural)
31036 * // returns ['A', 'B', 'C', 'D']
31037 *
31038 * function sortByLength (a, b) {
31039 * return a.length - b.length
31040 * }
31041 * math.sort(['Langdon', 'Tom', 'Sara'], sortByLength)
31042 * // returns ['Tom', 'Sara', 'Langdon']
31043 *
31044 * See also:
31045 *
31046 * filter, forEach, map, compare, compareNatural
31047 *
31048 * @param {Matrix | Array} x A one dimensional matrix or array to sort
31049 * @param {Function | 'asc' | 'desc' | 'natural'} [compare='asc']
31050 * An optional _comparator function or name. The function is called as
31051 * `compare(a, b)`, and must return 1 when a > b, -1 when a < b,
31052 * and 0 when a == b.
31053 * @return {Matrix | Array} Returns the sorted matrix.
31054 */
31055
31056
31057 return typed(sort_name, {
31058 Array: function Array(x) {
31059 _arrayIsVector(x);
31060
31061 return x.sort(compareAsc);
31062 },
31063 Matrix: function Matrix(x) {
31064 _matrixIsVector(x);
31065
31066 return matrix(x.toArray().sort(compareAsc), x.storage());
31067 },
31068 'Array, function': function ArrayFunction(x, _comparator) {
31069 _arrayIsVector(x);
31070
31071 return x.sort(_comparator);
31072 },
31073 'Matrix, function': function MatrixFunction(x, _comparator) {
31074 _matrixIsVector(x);
31075
31076 return matrix(x.toArray().sort(_comparator), x.storage());
31077 },
31078 'Array, string': function ArrayString(x, order) {
31079 _arrayIsVector(x);
31080
31081 return x.sort(_comparator(order));
31082 },
31083 'Matrix, string': function MatrixString(x, order) {
31084 _matrixIsVector(x);
31085
31086 return matrix(x.toArray().sort(_comparator(order)), x.storage());
31087 }
31088 });
31089 /**
31090 * Get the comparator for given order ('asc', 'desc', 'natural')
31091 * @param {'asc' | 'desc' | 'natural'} order
31092 * @return {Function} Returns a _comparator function
31093 */
31094
31095 function _comparator(order) {
31096 if (order === 'asc') {
31097 return compareAsc;
31098 } else if (order === 'desc') {
31099 return compareDesc;
31100 } else if (order === 'natural') {
31101 return compareNatural;
31102 } else {
31103 throw new Error('String "asc", "desc", or "natural" expected');
31104 }
31105 }
31106 /**
31107 * Validate whether an array is one dimensional
31108 * Throws an error when this is not the case
31109 * @param {Array} array
31110 * @private
31111 */
31112
31113
31114 function _arrayIsVector(array) {
31115 if (Object(utils_array["a" /* arraySize */])(array).length !== 1) {
31116 throw new Error('One dimensional array expected');
31117 }
31118 }
31119 /**
31120 * Validate whether a matrix is one dimensional
31121 * Throws an error when this is not the case
31122 * @param {Matrix} matrix
31123 * @private
31124 */
31125
31126
31127 function _matrixIsVector(matrix) {
31128 if (matrix.size().length !== 1) {
31129 throw new Error('One dimensional matrix expected');
31130 }
31131 }
31132});
31133// CONCATENATED MODULE: ./src/function/statistics/max.js
31134
31135
31136
31137var max_name = 'max';
31138var max_dependencies = ['typed', 'larger'];
31139var createMax =
31140/* #__PURE__ */
31141Object(factory["a" /* factory */])(max_name, max_dependencies, function (_ref) {
31142 var typed = _ref.typed,
31143 larger = _ref.larger;
31144
31145 /**
31146 * Compute the maximum value of a matrix or a list with values.
31147 * In case of a multi dimensional array, the maximum of the flattened array
31148 * will be calculated. When `dim` is provided, the maximum over the selected
31149 * dimension will be calculated. Parameter `dim` is zero-based.
31150 *
31151 * Syntax:
31152 *
31153 * math.max(a, b, c, ...)
31154 * math.max(A)
31155 * math.max(A, dim)
31156 *
31157 * Examples:
31158 *
31159 * math.max(2, 1, 4, 3) // returns 4
31160 * math.max([2, 1, 4, 3]) // returns 4
31161 *
31162 * // maximum over a specified dimension (zero-based)
31163 * math.max([[2, 5], [4, 3], [1, 7]], 0) // returns [4, 7]
31164 * math.max([[2, 5], [4, 3]], [1, 7], 1) // returns [5, 4, 7]
31165 *
31166 * math.max(2.7, 7.1, -4.5, 2.0, 4.1) // returns 7.1
31167 * math.min(2.7, 7.1, -4.5, 2.0, 4.1) // returns -4.5
31168 *
31169 * See also:
31170 *
31171 * mean, median, min, prod, std, sum, variance
31172 *
31173 * @param {... *} args A single matrix or or multiple scalar values
31174 * @return {*} The maximum value
31175 */
31176 return typed(max_name, {
31177 // max([a, b, c, d, ...])
31178 'Array | Matrix': _max,
31179 // max([a, b, c, d, ...], dim)
31180 'Array | Matrix, number | BigNumber': function ArrayMatrixNumberBigNumber(array, dim) {
31181 return reduce(array, dim.valueOf(), _largest);
31182 },
31183 // max(a, b, c, d, ...)
31184 '...': function _(args) {
31185 if (containsCollections(args)) {
31186 throw new TypeError('Scalar values expected in function max');
31187 }
31188
31189 return _max(args);
31190 }
31191 });
31192 /**
31193 * Return the largest of two values
31194 * @param {*} x
31195 * @param {*} y
31196 * @returns {*} Returns x when x is largest, or y when y is largest
31197 * @private
31198 */
31199
31200 function _largest(x, y) {
31201 try {
31202 return larger(x, y) ? x : y;
31203 } catch (err) {
31204 throw improveErrorMessage(err, 'max', y);
31205 }
31206 }
31207 /**
31208 * Recursively calculate the maximum value in an n-dimensional array
31209 * @param {Array} array
31210 * @return {number} max
31211 * @private
31212 */
31213
31214
31215 function _max(array) {
31216 var res;
31217 deepForEach(array, function (value) {
31218 try {
31219 if (isNaN(value) && typeof value === 'number') {
31220 res = NaN;
31221 } else if (res === undefined || larger(value, res)) {
31222 res = value;
31223 }
31224 } catch (err) {
31225 throw improveErrorMessage(err, 'max', value);
31226 }
31227 });
31228
31229 if (res === undefined) {
31230 throw new Error('Cannot calculate max of an empty array');
31231 }
31232
31233 return res;
31234 }
31235});
31236// CONCATENATED MODULE: ./src/function/statistics/min.js
31237
31238
31239
31240var min_name = 'min';
31241var min_dependencies = ['typed', 'smaller'];
31242var createMin =
31243/* #__PURE__ */
31244Object(factory["a" /* factory */])(min_name, min_dependencies, function (_ref) {
31245 var typed = _ref.typed,
31246 smaller = _ref.smaller;
31247
31248 /**
31249 * Compute the minimum value of a matrix or a list of values.
31250 * In case of a multi dimensional array, the minimum of the flattened array
31251 * will be calculated. When `dim` is provided, the minimum over the selected
31252 * dimension will be calculated. Parameter `dim` is zero-based.
31253 *
31254 * Syntax:
31255 *
31256 * math.min(a, b, c, ...)
31257 * math.min(A)
31258 * math.min(A, dim)
31259 *
31260 * Examples:
31261 *
31262 * math.min(2, 1, 4, 3) // returns 1
31263 * math.min([2, 1, 4, 3]) // returns 1
31264 *
31265 * // minimum over a specified dimension (zero-based)
31266 * math.min([[2, 5], [4, 3], [1, 7]], 0) // returns [1, 3]
31267 * math.min([[2, 5], [4, 3], [1, 7]], 1) // returns [2, 3, 1]
31268 *
31269 * math.max(2.7, 7.1, -4.5, 2.0, 4.1) // returns 7.1
31270 * math.min(2.7, 7.1, -4.5, 2.0, 4.1) // returns -4.5
31271 *
31272 * See also:
31273 *
31274 * mean, median, max, prod, std, sum, variance
31275 *
31276 * @param {... *} args A single matrix or or multiple scalar values
31277 * @return {*} The minimum value
31278 */
31279 return typed(min_name, {
31280 // min([a, b, c, d, ...])
31281 'Array | Matrix': _min,
31282 // min([a, b, c, d, ...], dim)
31283 'Array | Matrix, number | BigNumber': function ArrayMatrixNumberBigNumber(array, dim) {
31284 return reduce(array, dim.valueOf(), _smallest);
31285 },
31286 // min(a, b, c, d, ...)
31287 '...': function _(args) {
31288 if (containsCollections(args)) {
31289 throw new TypeError('Scalar values expected in function min');
31290 }
31291
31292 return _min(args);
31293 }
31294 });
31295 /**
31296 * Return the smallest of two values
31297 * @param {*} x
31298 * @param {*} y
31299 * @returns {*} Returns x when x is smallest, or y when y is smallest
31300 * @private
31301 */
31302
31303 function _smallest(x, y) {
31304 try {
31305 return smaller(x, y) ? x : y;
31306 } catch (err) {
31307 throw improveErrorMessage(err, 'min', y);
31308 }
31309 }
31310 /**
31311 * Recursively calculate the minimum value in an n-dimensional array
31312 * @param {Array} array
31313 * @return {number} min
31314 * @private
31315 */
31316
31317
31318 function _min(array) {
31319 var min;
31320 deepForEach(array, function (value) {
31321 try {
31322 if (isNaN(value) && typeof value === 'number') {
31323 min = NaN;
31324 } else if (min === undefined || smaller(value, min)) {
31325 min = value;
31326 }
31327 } catch (err) {
31328 throw improveErrorMessage(err, 'min', value);
31329 }
31330 });
31331
31332 if (min === undefined) {
31333 throw new Error('Cannot calculate min of an empty array');
31334 }
31335
31336 return min;
31337 }
31338});
31339// CONCATENATED MODULE: ./src/type/matrix/ImmutableDenseMatrix.js
31340
31341
31342
31343var ImmutableDenseMatrix_name = 'ImmutableDenseMatrix';
31344var ImmutableDenseMatrix_dependencies = ['smaller', 'DenseMatrix'];
31345var createImmutableDenseMatrixClass =
31346/* #__PURE__ */
31347Object(factory["a" /* factory */])(ImmutableDenseMatrix_name, ImmutableDenseMatrix_dependencies, function (_ref) {
31348 var smaller = _ref.smaller,
31349 DenseMatrix = _ref.DenseMatrix;
31350
31351 function ImmutableDenseMatrix(data, datatype) {
31352 if (!(this instanceof ImmutableDenseMatrix)) {
31353 throw new SyntaxError('Constructor must be called with the new operator');
31354 }
31355
31356 if (datatype && !Object(is["I" /* isString */])(datatype)) {
31357 throw new Error('Invalid datatype: ' + datatype);
31358 }
31359
31360 if (Object(is["v" /* isMatrix */])(data) || Object(is["b" /* isArray */])(data)) {
31361 // use DenseMatrix implementation
31362 var matrix = new DenseMatrix(data, datatype); // internal structures
31363
31364 this._data = matrix._data;
31365 this._size = matrix._size;
31366 this._datatype = matrix._datatype;
31367 this._min = null;
31368 this._max = null;
31369 } else if (data && Object(is["b" /* isArray */])(data.data) && Object(is["b" /* isArray */])(data.size)) {
31370 // initialize fields from JSON representation
31371 this._data = data.data;
31372 this._size = data.size;
31373 this._datatype = data.datatype;
31374 this._min = typeof data.min !== 'undefined' ? data.min : null;
31375 this._max = typeof data.max !== 'undefined' ? data.max : null;
31376 } else if (data) {
31377 // unsupported type
31378 throw new TypeError('Unsupported type of data (' + Object(is["M" /* typeOf */])(data) + ')');
31379 } else {
31380 // nothing provided
31381 this._data = [];
31382 this._size = [0];
31383 this._datatype = datatype;
31384 this._min = null;
31385 this._max = null;
31386 }
31387 }
31388
31389 ImmutableDenseMatrix.prototype = new DenseMatrix();
31390 /**
31391 * Attach type information
31392 */
31393
31394 ImmutableDenseMatrix.prototype.type = 'ImmutableDenseMatrix';
31395 ImmutableDenseMatrix.prototype.isImmutableDenseMatrix = true;
31396 /**
31397 * Get a subset of the matrix, or replace a subset of the matrix.
31398 *
31399 * Usage:
31400 * const subset = matrix.subset(index) // retrieve subset
31401 * const value = matrix.subset(index, replacement) // replace subset
31402 *
31403 * @param {Index} index
31404 * @param {Array | ImmutableDenseMatrix | *} [replacement]
31405 * @param {*} [defaultValue=0] Default value, filled in on new entries when
31406 * the matrix is resized. If not provided,
31407 * new matrix elements will be filled with zeros.
31408 */
31409
31410 ImmutableDenseMatrix.prototype.subset = function (index) {
31411 switch (arguments.length) {
31412 case 1:
31413 {
31414 // use base implementation
31415 var m = DenseMatrix.prototype.subset.call(this, index); // check result is a matrix
31416
31417 if (Object(is["v" /* isMatrix */])(m)) {
31418 // return immutable matrix
31419 return new ImmutableDenseMatrix({
31420 data: m._data,
31421 size: m._size,
31422 datatype: m._datatype
31423 });
31424 }
31425
31426 return m;
31427 }
31428 // intentional fall through
31429
31430 case 2:
31431 case 3:
31432 throw new Error('Cannot invoke set subset on an Immutable Matrix instance');
31433
31434 default:
31435 throw new SyntaxError('Wrong number of arguments');
31436 }
31437 };
31438 /**
31439 * Replace a single element in the matrix.
31440 * @param {Number[]} index Zero-based index
31441 * @param {*} value
31442 * @param {*} [defaultValue] Default value, filled in on new entries when
31443 * the matrix is resized. If not provided,
31444 * new matrix elements will be left undefined.
31445 * @return {ImmutableDenseMatrix} self
31446 */
31447
31448
31449 ImmutableDenseMatrix.prototype.set = function () {
31450 throw new Error('Cannot invoke set on an Immutable Matrix instance');
31451 };
31452 /**
31453 * Resize the matrix to the given size. Returns a copy of the matrix when
31454 * `copy=true`, otherwise return the matrix itself (resize in place).
31455 *
31456 * @param {Number[]} size The new size the matrix should have.
31457 * @param {*} [defaultValue=0] Default value, filled in on new entries.
31458 * If not provided, the matrix elements will
31459 * be filled with zeros.
31460 * @param {boolean} [copy] Return a resized copy of the matrix
31461 *
31462 * @return {Matrix} The resized matrix
31463 */
31464
31465
31466 ImmutableDenseMatrix.prototype.resize = function () {
31467 throw new Error('Cannot invoke resize on an Immutable Matrix instance');
31468 };
31469 /**
31470 * Disallows reshaping in favor of immutability.
31471 *
31472 * @throws {Error} Operation not allowed
31473 */
31474
31475
31476 ImmutableDenseMatrix.prototype.reshape = function () {
31477 throw new Error('Cannot invoke reshape on an Immutable Matrix instance');
31478 };
31479 /**
31480 * Create a clone of the matrix
31481 * @return {ImmutableDenseMatrix} clone
31482 */
31483
31484
31485 ImmutableDenseMatrix.prototype.clone = function () {
31486 return new ImmutableDenseMatrix({
31487 data: Object(utils_object["a" /* clone */])(this._data),
31488 size: Object(utils_object["a" /* clone */])(this._size),
31489 datatype: this._datatype
31490 });
31491 };
31492 /**
31493 * Get a JSON representation of the matrix
31494 * @returns {Object}
31495 */
31496
31497
31498 ImmutableDenseMatrix.prototype.toJSON = function () {
31499 return {
31500 mathjs: 'ImmutableDenseMatrix',
31501 data: this._data,
31502 size: this._size,
31503 datatype: this._datatype
31504 };
31505 };
31506 /**
31507 * Generate a matrix from a JSON object
31508 * @param {Object} json An object structured like
31509 * `{"mathjs": "ImmutableDenseMatrix", data: [], size: []}`,
31510 * where mathjs is optional
31511 * @returns {ImmutableDenseMatrix}
31512 */
31513
31514
31515 ImmutableDenseMatrix.fromJSON = function (json) {
31516 return new ImmutableDenseMatrix(json);
31517 };
31518 /**
31519 * Swap rows i and j in Matrix.
31520 *
31521 * @param {Number} i Matrix row index 1
31522 * @param {Number} j Matrix row index 2
31523 *
31524 * @return {Matrix} The matrix reference
31525 */
31526
31527
31528 ImmutableDenseMatrix.prototype.swapRows = function () {
31529 throw new Error('Cannot invoke swapRows on an Immutable Matrix instance');
31530 };
31531 /**
31532 * Calculate the minimum value in the set
31533 * @return {Number | undefined} min
31534 */
31535
31536
31537 ImmutableDenseMatrix.prototype.min = function () {
31538 // check min has been calculated before
31539 if (this._min === null) {
31540 // minimum
31541 var m = null; // compute min
31542
31543 this.forEach(function (v) {
31544 if (m === null || smaller(v, m)) {
31545 m = v;
31546 }
31547 });
31548 this._min = m !== null ? m : undefined;
31549 }
31550
31551 return this._min;
31552 };
31553 /**
31554 * Calculate the maximum value in the set
31555 * @return {Number | undefined} max
31556 */
31557
31558
31559 ImmutableDenseMatrix.prototype.max = function () {
31560 // check max has been calculated before
31561 if (this._max === null) {
31562 // maximum
31563 var m = null; // compute max
31564
31565 this.forEach(function (v) {
31566 if (m === null || smaller(m, v)) {
31567 m = v;
31568 }
31569 });
31570 this._max = m !== null ? m : undefined;
31571 }
31572
31573 return this._max;
31574 };
31575
31576 return ImmutableDenseMatrix;
31577}, {
31578 isClass: true
31579});
31580// CONCATENATED MODULE: ./src/type/matrix/MatrixIndex.js
31581
31582
31583
31584
31585var MatrixIndex_name = 'Index';
31586var MatrixIndex_dependencies = ['ImmutableDenseMatrix'];
31587var createIndexClass =
31588/* #__PURE__ */
31589Object(factory["a" /* factory */])(MatrixIndex_name, MatrixIndex_dependencies, function (_ref) {
31590 var ImmutableDenseMatrix = _ref.ImmutableDenseMatrix;
31591
31592 /**
31593 * Create an index. An Index can store ranges and sets for multiple dimensions.
31594 * Matrix.get, Matrix.set, and math.subset accept an Index as input.
31595 *
31596 * Usage:
31597 * const index = new Index(range1, range2, matrix1, array1, ...)
31598 *
31599 * Where each parameter can be any of:
31600 * A number
31601 * A string (containing a name of an object property)
31602 * An instance of Range
31603 * An Array with the Set values
31604 * A Matrix with the Set values
31605 *
31606 * The parameters start, end, and step must be integer numbers.
31607 *
31608 * @class Index
31609 * @Constructor Index
31610 * @param {...*} ranges
31611 */
31612 function Index(ranges) {
31613 if (!(this instanceof Index)) {
31614 throw new SyntaxError('Constructor must be called with the new operator');
31615 }
31616
31617 this._dimensions = [];
31618 this._isScalar = true;
31619
31620 for (var i = 0, ii = arguments.length; i < ii; i++) {
31621 var arg = arguments[i];
31622
31623 if (Object(is["D" /* isRange */])(arg)) {
31624 this._dimensions.push(arg);
31625
31626 this._isScalar = false;
31627 } else if (Array.isArray(arg) || Object(is["v" /* isMatrix */])(arg)) {
31628 // create matrix
31629 var m = _createImmutableMatrix(arg.valueOf());
31630
31631 this._dimensions.push(m); // size
31632
31633
31634 var size = m.size(); // scalar
31635
31636 if (size.length !== 1 || size[0] !== 1) {
31637 this._isScalar = false;
31638 }
31639 } else if (typeof arg === 'number') {
31640 this._dimensions.push(_createImmutableMatrix([arg]));
31641 } else if (typeof arg === 'string') {
31642 // object property (arguments.count should be 1)
31643 this._dimensions.push(arg);
31644 } else {
31645 throw new TypeError('Dimension must be an Array, Matrix, number, string, or Range');
31646 } // TODO: implement support for wildcard '*'
31647
31648 }
31649 }
31650 /**
31651 * Attach type information
31652 */
31653
31654
31655 Index.prototype.type = 'Index';
31656 Index.prototype.isIndex = true;
31657
31658 function _createImmutableMatrix(arg) {
31659 // loop array elements
31660 for (var i = 0, l = arg.length; i < l; i++) {
31661 if (typeof arg[i] !== 'number' || !Object(utils_number["i" /* isInteger */])(arg[i])) {
31662 throw new TypeError('Index parameters must be positive integer numbers');
31663 }
31664 } // create matrix
31665
31666
31667 return new ImmutableDenseMatrix(arg);
31668 }
31669 /**
31670 * Create a clone of the index
31671 * @memberof Index
31672 * @return {Index} clone
31673 */
31674
31675
31676 Index.prototype.clone = function () {
31677 var index = new Index();
31678 index._dimensions = Object(utils_object["a" /* clone */])(this._dimensions);
31679 index._isScalar = this._isScalar;
31680 return index;
31681 };
31682 /**
31683 * Create an index from an array with ranges/numbers
31684 * @memberof Index
31685 * @param {Array.<Array | number>} ranges
31686 * @return {Index} index
31687 * @private
31688 */
31689
31690
31691 Index.create = function (ranges) {
31692 var index = new Index();
31693 Index.apply(index, ranges);
31694 return index;
31695 };
31696 /**
31697 * Retrieve the size of the index, the number of elements for each dimension.
31698 * @memberof Index
31699 * @returns {number[]} size
31700 */
31701
31702
31703 Index.prototype.size = function () {
31704 var size = [];
31705
31706 for (var i = 0, ii = this._dimensions.length; i < ii; i++) {
31707 var d = this._dimensions[i];
31708 size[i] = typeof d === 'string' ? 1 : d.size()[0];
31709 }
31710
31711 return size;
31712 };
31713 /**
31714 * Get the maximum value for each of the indexes ranges.
31715 * @memberof Index
31716 * @returns {number[]} max
31717 */
31718
31719
31720 Index.prototype.max = function () {
31721 var values = [];
31722
31723 for (var i = 0, ii = this._dimensions.length; i < ii; i++) {
31724 var range = this._dimensions[i];
31725 values[i] = typeof range === 'string' ? range : range.max();
31726 }
31727
31728 return values;
31729 };
31730 /**
31731 * Get the minimum value for each of the indexes ranges.
31732 * @memberof Index
31733 * @returns {number[]} min
31734 */
31735
31736
31737 Index.prototype.min = function () {
31738 var values = [];
31739
31740 for (var i = 0, ii = this._dimensions.length; i < ii; i++) {
31741 var range = this._dimensions[i];
31742 values[i] = typeof range === 'string' ? range : range.min();
31743 }
31744
31745 return values;
31746 };
31747 /**
31748 * Loop over each of the ranges of the index
31749 * @memberof Index
31750 * @param {Function} callback Called for each range with a Range as first
31751 * argument, the dimension as second, and the
31752 * index object as third.
31753 */
31754
31755
31756 Index.prototype.forEach = function (callback) {
31757 for (var i = 0, ii = this._dimensions.length; i < ii; i++) {
31758 callback(this._dimensions[i], i, this);
31759 }
31760 };
31761 /**
31762 * Retrieve the dimension for the given index
31763 * @memberof Index
31764 * @param {Number} dim Number of the dimension
31765 * @returns {Range | null} range
31766 */
31767
31768
31769 Index.prototype.dimension = function (dim) {
31770 return this._dimensions[dim] || null;
31771 };
31772 /**
31773 * Test whether this index contains an object property
31774 * @returns {boolean} Returns true if the index is an object property
31775 */
31776
31777
31778 Index.prototype.isObjectProperty = function () {
31779 return this._dimensions.length === 1 && typeof this._dimensions[0] === 'string';
31780 };
31781 /**
31782 * Returns the object property name when the Index holds a single object property,
31783 * else returns null
31784 * @returns {string | null}
31785 */
31786
31787
31788 Index.prototype.getObjectProperty = function () {
31789 return this.isObjectProperty() ? this._dimensions[0] : null;
31790 };
31791 /**
31792 * Test whether this index contains only a single value.
31793 *
31794 * This is the case when the index is created with only scalar values as ranges,
31795 * not for ranges resolving into a single value.
31796 * @memberof Index
31797 * @return {boolean} isScalar
31798 */
31799
31800
31801 Index.prototype.isScalar = function () {
31802 return this._isScalar;
31803 };
31804 /**
31805 * Expand the Index into an array.
31806 * For example new Index([0,3], [2,7]) returns [[0,1,2], [2,3,4,5,6]]
31807 * @memberof Index
31808 * @returns {Array} array
31809 */
31810
31811
31812 Index.prototype.toArray = function () {
31813 var array = [];
31814
31815 for (var i = 0, ii = this._dimensions.length; i < ii; i++) {
31816 var dimension = this._dimensions[i];
31817 array.push(typeof dimension === 'string' ? dimension : dimension.toArray());
31818 }
31819
31820 return array;
31821 };
31822 /**
31823 * Get the primitive value of the Index, a two dimensional array.
31824 * Equivalent to Index.toArray().
31825 * @memberof Index
31826 * @returns {Array} array
31827 */
31828
31829
31830 Index.prototype.valueOf = Index.prototype.toArray;
31831 /**
31832 * Get the string representation of the index, for example '[2:6]' or '[0:2:10, 4:7, [1,2,3]]'
31833 * @memberof Index
31834 * @returns {String} str
31835 */
31836
31837 Index.prototype.toString = function () {
31838 var strings = [];
31839
31840 for (var i = 0, ii = this._dimensions.length; i < ii; i++) {
31841 var dimension = this._dimensions[i];
31842
31843 if (typeof dimension === 'string') {
31844 strings.push(JSON.stringify(dimension));
31845 } else {
31846 strings.push(dimension.toString());
31847 }
31848 }
31849
31850 return '[' + strings.join(', ') + ']';
31851 };
31852 /**
31853 * Get a JSON representation of the Index
31854 * @memberof Index
31855 * @returns {Object} Returns a JSON object structured as:
31856 * `{"mathjs": "Index", "ranges": [{"mathjs": "Range", start: 0, end: 10, step:1}, ...]}`
31857 */
31858
31859
31860 Index.prototype.toJSON = function () {
31861 return {
31862 mathjs: 'Index',
31863 dimensions: this._dimensions
31864 };
31865 };
31866 /**
31867 * Instantiate an Index from a JSON object
31868 * @memberof Index
31869 * @param {Object} json A JSON object structured as:
31870 * `{"mathjs": "Index", "dimensions": [{"mathjs": "Range", start: 0, end: 10, step:1}, ...]}`
31871 * @return {Index}
31872 */
31873
31874
31875 Index.fromJSON = function (json) {
31876 return Index.create(json.dimensions);
31877 };
31878
31879 return Index;
31880}, {
31881 isClass: true
31882});
31883// CONCATENATED MODULE: ./src/type/matrix/FibonacciHeap.js
31884
31885var FibonacciHeap_name = 'FibonacciHeap';
31886var FibonacciHeap_dependencies = ['smaller', 'larger'];
31887var createFibonacciHeapClass =
31888/* #__PURE__ */
31889Object(factory["a" /* factory */])(FibonacciHeap_name, FibonacciHeap_dependencies, function (_ref) {
31890 var smaller = _ref.smaller,
31891 larger = _ref.larger;
31892 var oneOverLogPhi = 1.0 / Math.log((1.0 + Math.sqrt(5.0)) / 2.0);
31893 /**
31894 * Fibonacci Heap implementation, used interally for Matrix math.
31895 * @class FibonacciHeap
31896 * @constructor FibonacciHeap
31897 */
31898
31899 function FibonacciHeap() {
31900 if (!(this instanceof FibonacciHeap)) {
31901 throw new SyntaxError('Constructor must be called with the new operator');
31902 } // initialize fields
31903
31904
31905 this._minimum = null;
31906 this._size = 0;
31907 }
31908 /**
31909 * Attach type information
31910 */
31911
31912
31913 FibonacciHeap.prototype.type = 'FibonacciHeap';
31914 FibonacciHeap.prototype.isFibonacciHeap = true;
31915 /**
31916 * Inserts a new data element into the heap. No heap consolidation is
31917 * performed at this time, the new node is simply inserted into the root
31918 * list of this heap. Running time: O(1) actual.
31919 * @memberof FibonacciHeap
31920 */
31921
31922 FibonacciHeap.prototype.insert = function (key, value) {
31923 // create node
31924 var node = {
31925 key: key,
31926 value: value,
31927 degree: 0
31928 }; // check we have a node in the minimum
31929
31930 if (this._minimum) {
31931 // minimum node
31932 var minimum = this._minimum; // update left & right of node
31933
31934 node.left = minimum;
31935 node.right = minimum.right;
31936 minimum.right = node;
31937 node.right.left = node; // update minimum node in heap if needed
31938
31939 if (smaller(key, minimum.key)) {
31940 // node has a smaller key, use it as minimum
31941 this._minimum = node;
31942 }
31943 } else {
31944 // set left & right
31945 node.left = node;
31946 node.right = node; // this is the first node
31947
31948 this._minimum = node;
31949 } // increment number of nodes in heap
31950
31951
31952 this._size++; // return node
31953
31954 return node;
31955 };
31956 /**
31957 * Returns the number of nodes in heap. Running time: O(1) actual.
31958 * @memberof FibonacciHeap
31959 */
31960
31961
31962 FibonacciHeap.prototype.size = function () {
31963 return this._size;
31964 };
31965 /**
31966 * Removes all elements from this heap.
31967 * @memberof FibonacciHeap
31968 */
31969
31970
31971 FibonacciHeap.prototype.clear = function () {
31972 this._minimum = null;
31973 this._size = 0;
31974 };
31975 /**
31976 * Returns true if the heap is empty, otherwise false.
31977 * @memberof FibonacciHeap
31978 */
31979
31980
31981 FibonacciHeap.prototype.isEmpty = function () {
31982 return this._size === 0;
31983 };
31984 /**
31985 * Extracts the node with minimum key from heap. Amortized running
31986 * time: O(log n).
31987 * @memberof FibonacciHeap
31988 */
31989
31990
31991 FibonacciHeap.prototype.extractMinimum = function () {
31992 // node to remove
31993 var node = this._minimum; // check we have a minimum
31994
31995 if (node === null) {
31996 return node;
31997 } // current minimum
31998
31999
32000 var minimum = this._minimum; // get number of children
32001
32002 var numberOfChildren = node.degree; // pointer to the first child
32003
32004 var x = node.child; // for each child of node do...
32005
32006 while (numberOfChildren > 0) {
32007 // store node in right side
32008 var tempRight = x.right; // remove x from child list
32009
32010 x.left.right = x.right;
32011 x.right.left = x.left; // add x to root list of heap
32012
32013 x.left = minimum;
32014 x.right = minimum.right;
32015 minimum.right = x;
32016 x.right.left = x; // set Parent[x] to null
32017
32018 x.parent = null;
32019 x = tempRight;
32020 numberOfChildren--;
32021 } // remove node from root list of heap
32022
32023
32024 node.left.right = node.right;
32025 node.right.left = node.left; // update minimum
32026
32027 if (node === node.right) {
32028 // empty
32029 minimum = null;
32030 } else {
32031 // update minimum
32032 minimum = node.right; // we need to update the pointer to the root with minimum key
32033
32034 minimum = _findMinimumNode(minimum, this._size);
32035 } // decrement size of heap
32036
32037
32038 this._size--; // update minimum
32039
32040 this._minimum = minimum; // return node
32041
32042 return node;
32043 };
32044 /**
32045 * Removes a node from the heap given the reference to the node. The trees
32046 * in the heap will be consolidated, if necessary. This operation may fail
32047 * to remove the correct element if there are nodes with key value -Infinity.
32048 * Running time: O(log n) amortized.
32049 * @memberof FibonacciHeap
32050 */
32051
32052
32053 FibonacciHeap.prototype.remove = function (node) {
32054 // decrease key value
32055 this._minimum = _decreaseKey(this._minimum, node, -1); // remove the smallest
32056
32057 this.extractMinimum();
32058 };
32059 /**
32060 * Decreases the key value for a heap node, given the new value to take on.
32061 * The structure of the heap may be changed and will not be consolidated.
32062 * Running time: O(1) amortized.
32063 * @memberof FibonacciHeap
32064 */
32065
32066
32067 function _decreaseKey(minimum, node, key) {
32068 // set node key
32069 node.key = key; // get parent node
32070
32071 var parent = node.parent;
32072
32073 if (parent && smaller(node.key, parent.key)) {
32074 // remove node from parent
32075 _cut(minimum, node, parent); // remove all nodes from parent to the root parent
32076
32077
32078 _cascadingCut(minimum, parent);
32079 } // update minimum node if needed
32080
32081
32082 if (smaller(node.key, minimum.key)) {
32083 minimum = node;
32084 } // return minimum
32085
32086
32087 return minimum;
32088 }
32089 /**
32090 * The reverse of the link operation: removes node from the child list of parent.
32091 * This method assumes that min is non-null. Running time: O(1).
32092 * @memberof FibonacciHeap
32093 */
32094
32095
32096 function _cut(minimum, node, parent) {
32097 // remove node from parent children and decrement Degree[parent]
32098 node.left.right = node.right;
32099 node.right.left = node.left;
32100 parent.degree--; // reset y.child if necessary
32101
32102 if (parent.child === node) {
32103 parent.child = node.right;
32104 } // remove child if degree is 0
32105
32106
32107 if (parent.degree === 0) {
32108 parent.child = null;
32109 } // add node to root list of heap
32110
32111
32112 node.left = minimum;
32113 node.right = minimum.right;
32114 minimum.right = node;
32115 node.right.left = node; // set parent[node] to null
32116
32117 node.parent = null; // set mark[node] to false
32118
32119 node.mark = false;
32120 }
32121 /**
32122 * Performs a cascading cut operation. This cuts node from its parent and then
32123 * does the same for its parent, and so on up the tree.
32124 * Running time: O(log n); O(1) excluding the recursion.
32125 * @memberof FibonacciHeap
32126 */
32127
32128
32129 function _cascadingCut(minimum, node) {
32130 // store parent node
32131 var parent = node.parent; // if there's a parent...
32132
32133 if (!parent) {
32134 return;
32135 } // if node is unmarked, set it marked
32136
32137
32138 if (!node.mark) {
32139 node.mark = true;
32140 } else {
32141 // it's marked, cut it from parent
32142 _cut(minimum, node, parent); // cut its parent as well
32143
32144
32145 _cascadingCut(parent);
32146 }
32147 }
32148 /**
32149 * Make the first node a child of the second one. Running time: O(1) actual.
32150 * @memberof FibonacciHeap
32151 */
32152
32153
32154 var _linkNodes = function _linkNodes(node, parent) {
32155 // remove node from root list of heap
32156 node.left.right = node.right;
32157 node.right.left = node.left; // make node a Child of parent
32158
32159 node.parent = parent;
32160
32161 if (!parent.child) {
32162 parent.child = node;
32163 node.right = node;
32164 node.left = node;
32165 } else {
32166 node.left = parent.child;
32167 node.right = parent.child.right;
32168 parent.child.right = node;
32169 node.right.left = node;
32170 } // increase degree[parent]
32171
32172
32173 parent.degree++; // set mark[node] false
32174
32175 node.mark = false;
32176 };
32177
32178 function _findMinimumNode(minimum, size) {
32179 // 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
32180 var arraySize = Math.floor(Math.log(size) * oneOverLogPhi) + 1; // create list with initial capacity
32181
32182 var array = new Array(arraySize); // find the number of root nodes.
32183
32184 var numRoots = 0;
32185 var x = minimum;
32186
32187 if (x) {
32188 numRoots++;
32189 x = x.right;
32190
32191 while (x !== minimum) {
32192 numRoots++;
32193 x = x.right;
32194 }
32195 } // vars
32196
32197
32198 var y; // For each node in root list do...
32199
32200 while (numRoots > 0) {
32201 // access this node's degree..
32202 var d = x.degree; // get next node
32203
32204 var next = x.right; // check if there is a node already in array with the same degree
32205
32206 while (true) {
32207 // get node with the same degree is any
32208 y = array[d];
32209
32210 if (!y) {
32211 break;
32212 } // make one node with the same degree a child of the other, do this based on the key value.
32213
32214
32215 if (larger(x.key, y.key)) {
32216 var temp = y;
32217 y = x;
32218 x = temp;
32219 } // make y a child of x
32220
32221
32222 _linkNodes(y, x); // we have handled this degree, go to next one.
32223
32224
32225 array[d] = null;
32226 d++;
32227 } // save this node for later when we might encounter another of the same degree.
32228
32229
32230 array[d] = x; // move forward through list.
32231
32232 x = next;
32233 numRoots--;
32234 } // Set min to null (effectively losing the root list) and reconstruct the root list from the array entries in array[].
32235
32236
32237 minimum = null; // loop nodes in array
32238
32239 for (var i = 0; i < arraySize; i++) {
32240 // get current node
32241 y = array[i];
32242
32243 if (!y) {
32244 continue;
32245 } // check if we have a linked list
32246
32247
32248 if (minimum) {
32249 // First remove node from root list.
32250 y.left.right = y.right;
32251 y.right.left = y.left; // now add to root list, again.
32252
32253 y.left = minimum;
32254 y.right = minimum.right;
32255 minimum.right = y;
32256 y.right.left = y; // check if this is a new min.
32257
32258 if (smaller(y.key, minimum.key)) {
32259 minimum = y;
32260 }
32261 } else {
32262 minimum = y;
32263 }
32264 }
32265
32266 return minimum;
32267 }
32268
32269 return FibonacciHeap;
32270}, {
32271 isClass: true
32272});
32273// CONCATENATED MODULE: ./src/type/matrix/Spa.js
32274
32275var Spa_name = 'Spa';
32276var Spa_dependencies = ['addScalar', 'equalScalar', 'FibonacciHeap'];
32277var createSpaClass =
32278/* #__PURE__ */
32279Object(factory["a" /* factory */])(Spa_name, Spa_dependencies, function (_ref) {
32280 var addScalar = _ref.addScalar,
32281 equalScalar = _ref.equalScalar,
32282 FibonacciHeap = _ref.FibonacciHeap;
32283
32284 /**
32285 * An ordered Sparse Accumulator is a representation for a sparse vector that includes a dense array
32286 * of the vector elements and an ordered list of non-zero elements.
32287 */
32288 function Spa() {
32289 if (!(this instanceof Spa)) {
32290 throw new SyntaxError('Constructor must be called with the new operator');
32291 } // allocate vector, TODO use typed arrays
32292
32293
32294 this._values = [];
32295 this._heap = new FibonacciHeap();
32296 }
32297 /**
32298 * Attach type information
32299 */
32300
32301
32302 Spa.prototype.type = 'Spa';
32303 Spa.prototype.isSpa = true;
32304 /**
32305 * Set the value for index i.
32306 *
32307 * @param {number} i The index
32308 * @param {number | BigNumber | Complex} The value at index i
32309 */
32310
32311 Spa.prototype.set = function (i, v) {
32312 // check we have a value @ i
32313 if (!this._values[i]) {
32314 // insert in heap
32315 var node = this._heap.insert(i, v); // set the value @ i
32316
32317
32318 this._values[i] = node;
32319 } else {
32320 // update the value @ i
32321 this._values[i].value = v;
32322 }
32323 };
32324
32325 Spa.prototype.get = function (i) {
32326 var node = this._values[i];
32327
32328 if (node) {
32329 return node.value;
32330 }
32331
32332 return 0;
32333 };
32334
32335 Spa.prototype.accumulate = function (i, v) {
32336 // node @ i
32337 var node = this._values[i];
32338
32339 if (!node) {
32340 // insert in heap
32341 node = this._heap.insert(i, v); // initialize value
32342
32343 this._values[i] = node;
32344 } else {
32345 // accumulate value
32346 node.value = addScalar(node.value, v);
32347 }
32348 };
32349
32350 Spa.prototype.forEach = function (from, to, callback) {
32351 // references
32352 var heap = this._heap;
32353 var values = this._values; // nodes
32354
32355 var nodes = []; // node with minimum key, save it
32356
32357 var node = heap.extractMinimum();
32358
32359 if (node) {
32360 nodes.push(node);
32361 } // extract nodes from heap (ordered)
32362
32363
32364 while (node && node.key <= to) {
32365 // check it is in range
32366 if (node.key >= from) {
32367 // check value is not zero
32368 if (!equalScalar(node.value, 0)) {
32369 // invoke callback
32370 callback(node.key, node.value, this);
32371 }
32372 } // extract next node, save it
32373
32374
32375 node = heap.extractMinimum();
32376
32377 if (node) {
32378 nodes.push(node);
32379 }
32380 } // reinsert all nodes in heap
32381
32382
32383 for (var i = 0; i < nodes.length; i++) {
32384 // current node
32385 var n = nodes[i]; // insert node in heap
32386
32387 node = heap.insert(n.key, n.value); // update values
32388
32389 values[node.key] = node;
32390 }
32391 };
32392
32393 Spa.prototype.swap = function (i, j) {
32394 // node @ i and j
32395 var nodei = this._values[i];
32396 var nodej = this._values[j]; // check we need to insert indeces
32397
32398 if (!nodei && nodej) {
32399 // insert in heap
32400 nodei = this._heap.insert(i, nodej.value); // remove from heap
32401
32402 this._heap.remove(nodej); // set values
32403
32404
32405 this._values[i] = nodei;
32406 this._values[j] = undefined;
32407 } else if (nodei && !nodej) {
32408 // insert in heap
32409 nodej = this._heap.insert(j, nodei.value); // remove from heap
32410
32411 this._heap.remove(nodei); // set values
32412
32413
32414 this._values[j] = nodej;
32415 this._values[i] = undefined;
32416 } else if (nodei && nodej) {
32417 // swap values
32418 var v = nodei.value;
32419 nodei.value = nodej.value;
32420 nodej.value = v;
32421 }
32422 };
32423
32424 return Spa;
32425}, {
32426 isClass: true
32427});
32428// CONCATENATED MODULE: ./src/utils/bignumber/constants.js
32429
32430/**
32431 * Calculate BigNumber e
32432 * @param {function} BigNumber BigNumber constructor
32433 * @returns {BigNumber} Returns e
32434 */
32435
32436var createBigNumberE = memoize(function (BigNumber) {
32437 return new BigNumber(1).exp();
32438}, hasher);
32439/**
32440 * Calculate BigNumber golden ratio, phi = (1+sqrt(5))/2
32441 * @param {function} BigNumber BigNumber constructor
32442 * @returns {BigNumber} Returns phi
32443 */
32444
32445var createBigNumberPhi = memoize(function (BigNumber) {
32446 return new BigNumber(1).plus(new BigNumber(5).sqrt()).div(2);
32447}, hasher);
32448/**
32449 * Calculate BigNumber pi.
32450 * @param {function} BigNumber BigNumber constructor
32451 * @returns {BigNumber} Returns pi
32452 */
32453
32454var createBigNumberPi = memoize(function (BigNumber) {
32455 return BigNumber.acos(-1);
32456}, hasher);
32457/**
32458 * Calculate BigNumber tau, tau = 2 * pi
32459 * @param {function} BigNumber BigNumber constructor
32460 * @returns {BigNumber} Returns tau
32461 */
32462
32463var createBigNumberTau = memoize(function (BigNumber) {
32464 return createBigNumberPi(BigNumber).times(2);
32465}, hasher);
32466/**
32467 * Create a hash for a BigNumber constructor function. The created has is
32468 * the configured precision
32469 * @param {Array} args Supposed to contain a single entry with
32470 * a BigNumber constructor
32471 * @return {number} precision
32472 * @private
32473 */
32474
32475function hasher(args) {
32476 return args[0].precision;
32477}
32478// CONCATENATED MODULE: ./src/type/unit/Unit.js
32479function Unit_typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { Unit_typeof = function _typeof(obj) { return typeof obj; }; } else { Unit_typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return Unit_typeof(obj); }
32480
32481function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
32482
32483
32484
32485
32486
32487
32488var Unit_name = 'Unit';
32489var Unit_dependencies = ['?on', 'config', 'addScalar', 'subtract', 'multiplyScalar', 'divideScalar', 'pow', 'abs', 'fix', 'round', 'equal', 'isNumeric', 'format', 'number', 'Complex', 'BigNumber', 'Fraction'];
32490var createUnitClass =
32491/* #__PURE__ */
32492Object(factory["a" /* factory */])(Unit_name, Unit_dependencies, function (_ref) {
32493 var on = _ref.on,
32494 config = _ref.config,
32495 addScalar = _ref.addScalar,
32496 subtract = _ref.subtract,
32497 multiplyScalar = _ref.multiplyScalar,
32498 divideScalar = _ref.divideScalar,
32499 pow = _ref.pow,
32500 abs = _ref.abs,
32501 fix = _ref.fix,
32502 round = _ref.round,
32503 equal = _ref.equal,
32504 isNumeric = _ref.isNumeric,
32505 format = _ref.format,
32506 number = _ref.number,
32507 Complex = _ref.Complex,
32508 _BigNumber = _ref.BigNumber,
32509 _Fraction = _ref.Fraction;
32510 var toNumber = number;
32511 /**
32512 * A unit can be constructed in the following ways:
32513 *
32514 * const a = new Unit(value, name)
32515 * const b = new Unit(null, name)
32516 * const c = Unit.parse(str)
32517 *
32518 * Example usage:
32519 *
32520 * const a = new Unit(5, 'cm') // 50 mm
32521 * const b = Unit.parse('23 kg') // 23 kg
32522 * const c = math.in(a, new Unit(null, 'm') // 0.05 m
32523 * const d = new Unit(9.81, "m/s^2") // 9.81 m/s^2
32524 *
32525 * @class Unit
32526 * @constructor Unit
32527 * @param {number | BigNumber | Fraction | Complex | boolean} [value] A value like 5.2
32528 * @param {string} [name] A unit name like "cm" or "inch", or a derived unit of the form: "u1[^ex1] [u2[^ex2] ...] [/ u3[^ex3] [u4[^ex4]]]", such as "kg m^2/s^2", where each unit appearing after the forward slash is taken to be in the denominator. "kg m^2 s^-2" is a synonym and is also acceptable. Any of the units can include a prefix.
32529 */
32530
32531 function Unit(value, name) {
32532 if (!(this instanceof Unit)) {
32533 throw new Error('Constructor must be called with the new operator');
32534 }
32535
32536 if (!(value === null || value === undefined || isNumeric(value) || Object(is["j" /* isComplex */])(value))) {
32537 throw new TypeError('First parameter in Unit constructor must be number, BigNumber, Fraction, Complex, or undefined');
32538 }
32539
32540 if (name !== undefined && (typeof name !== 'string' || name === '')) {
32541 throw new TypeError('Second parameter in Unit constructor must be a string');
32542 }
32543
32544 if (name !== undefined) {
32545 var u = Unit.parse(name);
32546 this.units = u.units;
32547 this.dimensions = u.dimensions;
32548 } else {
32549 this.units = [{
32550 unit: UNIT_NONE,
32551 prefix: PREFIXES.NONE,
32552 // link to a list with supported prefixes
32553 power: 0
32554 }];
32555 this.dimensions = [];
32556
32557 for (var i = 0; i < BASE_DIMENSIONS.length; i++) {
32558 this.dimensions[i] = 0;
32559 }
32560 }
32561
32562 this.value = value !== undefined && value !== null ? this._normalize(value) : null;
32563 this.fixPrefix = false; // if true, function format will not search for the
32564 // best prefix but leave it as initially provided.
32565 // fixPrefix is set true by the method Unit.to
32566 // The justification behind this is that if the constructor is explicitly called,
32567 // the caller wishes the units to be returned exactly as he supplied.
32568
32569 this.skipAutomaticSimplification = true;
32570 }
32571 /**
32572 * Attach type information
32573 */
32574
32575
32576 Unit.prototype.type = 'Unit';
32577 Unit.prototype.isUnit = true; // private variables and functions for the Unit parser
32578
32579 var text, index, c;
32580
32581 function skipWhitespace() {
32582 while (c === ' ' || c === '\t') {
32583 next();
32584 }
32585 }
32586
32587 function isDigitDot(c) {
32588 return c >= '0' && c <= '9' || c === '.';
32589 }
32590
32591 function isDigit(c) {
32592 return c >= '0' && c <= '9';
32593 }
32594
32595 function next() {
32596 index++;
32597 c = text.charAt(index);
32598 }
32599
32600 function revert(oldIndex) {
32601 index = oldIndex;
32602 c = text.charAt(index);
32603 }
32604
32605 function parseNumber() {
32606 var number = '';
32607 var oldIndex = index;
32608
32609 if (c === '+') {
32610 next();
32611 } else if (c === '-') {
32612 number += c;
32613 next();
32614 }
32615
32616 if (!isDigitDot(c)) {
32617 // a + or - must be followed by a digit
32618 revert(oldIndex);
32619 return null;
32620 } // get number, can have a single dot
32621
32622
32623 if (c === '.') {
32624 number += c;
32625 next();
32626
32627 if (!isDigit(c)) {
32628 // this is no legal number, it is just a dot
32629 revert(oldIndex);
32630 return null;
32631 }
32632 } else {
32633 while (isDigit(c)) {
32634 number += c;
32635 next();
32636 }
32637
32638 if (c === '.') {
32639 number += c;
32640 next();
32641 }
32642 }
32643
32644 while (isDigit(c)) {
32645 number += c;
32646 next();
32647 } // check for exponential notation like "2.3e-4" or "1.23e50"
32648
32649
32650 if (c === 'E' || c === 'e') {
32651 // The grammar branches here. This could either be part of an exponent or the start of a unit that begins with the letter e, such as "4exabytes"
32652 var tentativeNumber = '';
32653 var tentativeIndex = index;
32654 tentativeNumber += c;
32655 next();
32656
32657 if (c === '+' || c === '-') {
32658 tentativeNumber += c;
32659 next();
32660 } // Scientific notation MUST be followed by an exponent (otherwise we assume it is not scientific notation)
32661
32662
32663 if (!isDigit(c)) {
32664 // The e or E must belong to something else, so return the number without the e or E.
32665 revert(tentativeIndex);
32666 return number;
32667 } // We can now safely say that this is scientific notation.
32668
32669
32670 number = number + tentativeNumber;
32671
32672 while (isDigit(c)) {
32673 number += c;
32674 next();
32675 }
32676 }
32677
32678 return number;
32679 }
32680
32681 function parseUnit() {
32682 var unitName = ''; // Alphanumeric characters only; matches [a-zA-Z0-9]
32683
32684 var code = text.charCodeAt(index);
32685
32686 while (code >= 48 && code <= 57 || code >= 65 && code <= 90 || code >= 97 && code <= 122) {
32687 unitName += c;
32688 next();
32689 code = text.charCodeAt(index);
32690 } // Must begin with [a-zA-Z]
32691
32692
32693 code = unitName.charCodeAt(0);
32694
32695 if (code >= 65 && code <= 90 || code >= 97 && code <= 122) {
32696 return unitName || null;
32697 } else {
32698 return null;
32699 }
32700 }
32701
32702 function parseCharacter(toFind) {
32703 if (c === toFind) {
32704 next();
32705 return toFind;
32706 } else {
32707 return null;
32708 }
32709 }
32710 /**
32711 * Parse a string into a unit. The value of the unit is parsed as number,
32712 * BigNumber, or Fraction depending on the math.js config setting `number`.
32713 *
32714 * Throws an exception if the provided string does not contain a valid unit or
32715 * cannot be parsed.
32716 * @memberof Unit
32717 * @param {string} str A string like "5.2 inch", "4e2 cm/s^2"
32718 * @return {Unit} unit
32719 */
32720
32721
32722 Unit.parse = function (str, options) {
32723 options = options || {};
32724 text = str;
32725 index = -1;
32726 c = '';
32727
32728 if (typeof text !== 'string') {
32729 throw new TypeError('Invalid argument in Unit.parse, string expected');
32730 }
32731
32732 var unit = new Unit();
32733 unit.units = [];
32734 var powerMultiplierCurrent = 1;
32735 var expectingUnit = false; // A unit should follow this pattern:
32736 // [number] ...[ [*/] unit[^number] ]
32737 // unit[^number] ... [ [*/] unit[^number] ]
32738 // Rules:
32739 // number is any floating point number.
32740 // unit is any alphanumeric string beginning with an alpha. Units with names like e3 should be avoided because they look like the exponent of a floating point number!
32741 // The string may optionally begin with a number.
32742 // Each unit may optionally be followed by ^number.
32743 // Whitespace or a forward slash is recommended between consecutive units, although the following technically is parseable:
32744 // 2m^2kg/s^2
32745 // it is not good form. If a unit starts with e, then it could be confused as a floating point number:
32746 // 4erg
32747
32748 next();
32749 skipWhitespace(); // Optional number at the start of the string
32750
32751 var valueStr = parseNumber();
32752 var value = null;
32753
32754 if (valueStr) {
32755 if (config.number === 'BigNumber') {
32756 value = new _BigNumber(valueStr);
32757 } else if (config.number === 'Fraction') {
32758 try {
32759 // not all numbers can be turned in Fractions, for example very small numbers not
32760 value = new _Fraction(valueStr);
32761 } catch (err) {
32762 value = parseFloat(valueStr);
32763 }
32764 } else {
32765 // number
32766 value = parseFloat(valueStr);
32767 }
32768
32769 skipWhitespace(); // Whitespace is not required here
32770 // handle multiplication or division right after the value, like '1/s'
32771
32772 if (parseCharacter('*')) {
32773 powerMultiplierCurrent = 1;
32774 expectingUnit = true;
32775 } else if (parseCharacter('/')) {
32776 powerMultiplierCurrent = -1;
32777 expectingUnit = true;
32778 }
32779 } // Stack to keep track of powerMultipliers applied to each parentheses group
32780
32781
32782 var powerMultiplierStack = []; // Running product of all elements in powerMultiplierStack
32783
32784 var powerMultiplierStackProduct = 1;
32785
32786 while (true) {
32787 skipWhitespace(); // Check for and consume opening parentheses, pushing powerMultiplierCurrent to the stack
32788 // A '(' will always appear directly before a unit.
32789
32790 while (c === '(') {
32791 powerMultiplierStack.push(powerMultiplierCurrent);
32792 powerMultiplierStackProduct *= powerMultiplierCurrent;
32793 powerMultiplierCurrent = 1;
32794 next();
32795 skipWhitespace();
32796 } // Is there something here?
32797
32798
32799 var uStr = void 0;
32800
32801 if (c) {
32802 var oldC = c;
32803 uStr = parseUnit();
32804
32805 if (uStr === null) {
32806 throw new SyntaxError('Unexpected "' + oldC + '" in "' + text + '" at index ' + index.toString());
32807 }
32808 } else {
32809 // End of input.
32810 break;
32811 } // Verify the unit exists and get the prefix (if any)
32812
32813
32814 var res = _findUnit(uStr);
32815
32816 if (res === null) {
32817 // Unit not found.
32818 throw new SyntaxError('Unit "' + uStr + '" not found.');
32819 }
32820
32821 var power = powerMultiplierCurrent * powerMultiplierStackProduct; // Is there a "^ number"?
32822
32823 skipWhitespace();
32824
32825 if (parseCharacter('^')) {
32826 skipWhitespace();
32827 var p = parseNumber();
32828
32829 if (p === null) {
32830 // No valid number found for the power!
32831 throw new SyntaxError('In "' + str + '", "^" must be followed by a floating-point number');
32832 }
32833
32834 power *= p;
32835 } // Add the unit to the list
32836
32837
32838 unit.units.push({
32839 unit: res.unit,
32840 prefix: res.prefix,
32841 power: power
32842 });
32843
32844 for (var i = 0; i < BASE_DIMENSIONS.length; i++) {
32845 unit.dimensions[i] += (res.unit.dimensions[i] || 0) * power;
32846 } // Check for and consume closing parentheses, popping from the stack.
32847 // A ')' will always follow a unit.
32848
32849
32850 skipWhitespace();
32851
32852 while (c === ')') {
32853 if (powerMultiplierStack.length === 0) {
32854 throw new SyntaxError('Unmatched ")" in "' + text + '" at index ' + index.toString());
32855 }
32856
32857 powerMultiplierStackProduct /= powerMultiplierStack.pop();
32858 next();
32859 skipWhitespace();
32860 } // "*" and "/" should mean we are expecting something to come next.
32861 // Is there a forward slash? If so, negate powerMultiplierCurrent. The next unit or paren group is in the denominator.
32862
32863
32864 expectingUnit = false;
32865
32866 if (parseCharacter('*')) {
32867 // explicit multiplication
32868 powerMultiplierCurrent = 1;
32869 expectingUnit = true;
32870 } else if (parseCharacter('/')) {
32871 // division
32872 powerMultiplierCurrent = -1;
32873 expectingUnit = true;
32874 } else {
32875 // implicit multiplication
32876 powerMultiplierCurrent = 1;
32877 } // Replace the unit into the auto unit system
32878
32879
32880 if (res.unit.base) {
32881 var baseDim = res.unit.base.key;
32882 UNIT_SYSTEMS.auto[baseDim] = {
32883 unit: res.unit,
32884 prefix: res.prefix
32885 };
32886 }
32887 } // Has the string been entirely consumed?
32888
32889
32890 skipWhitespace();
32891
32892 if (c) {
32893 throw new SyntaxError('Could not parse: "' + str + '"');
32894 } // Is there a trailing slash?
32895
32896
32897 if (expectingUnit) {
32898 throw new SyntaxError('Trailing characters: "' + str + '"');
32899 } // Is the parentheses stack empty?
32900
32901
32902 if (powerMultiplierStack.length !== 0) {
32903 throw new SyntaxError('Unmatched "(" in "' + text + '"');
32904 } // Are there any units at all?
32905
32906
32907 if (unit.units.length === 0 && !options.allowNoUnits) {
32908 throw new SyntaxError('"' + str + '" contains no units');
32909 }
32910
32911 unit.value = value !== undefined ? unit._normalize(value) : null;
32912 return unit;
32913 };
32914 /**
32915 * create a copy of this unit
32916 * @memberof Unit
32917 * @return {Unit} Returns a cloned version of the unit
32918 */
32919
32920
32921 Unit.prototype.clone = function () {
32922 var unit = new Unit();
32923 unit.fixPrefix = this.fixPrefix;
32924 unit.skipAutomaticSimplification = this.skipAutomaticSimplification;
32925 unit.value = Object(utils_object["a" /* clone */])(this.value);
32926 unit.dimensions = this.dimensions.slice(0);
32927 unit.units = [];
32928
32929 for (var i = 0; i < this.units.length; i++) {
32930 unit.units[i] = {};
32931
32932 for (var p in this.units[i]) {
32933 if (Object(utils_object["f" /* hasOwnProperty */])(this.units[i], p)) {
32934 unit.units[i][p] = this.units[i][p];
32935 }
32936 }
32937 }
32938
32939 return unit;
32940 };
32941 /**
32942 * Return whether the unit is derived (such as m/s, or cm^2, but not N)
32943 * @memberof Unit
32944 * @return {boolean} True if the unit is derived
32945 */
32946
32947
32948 Unit.prototype._isDerived = function () {
32949 if (this.units.length === 0) {
32950 return false;
32951 }
32952
32953 return this.units.length > 1 || Math.abs(this.units[0].power - 1.0) > 1e-15;
32954 };
32955 /**
32956 * Normalize a value, based on its currently set unit(s)
32957 * @memberof Unit
32958 * @param {number | BigNumber | Fraction | boolean} value
32959 * @return {number | BigNumber | Fraction | boolean} normalized value
32960 * @private
32961 */
32962
32963
32964 Unit.prototype._normalize = function (value) {
32965 var unitValue, unitOffset, unitPower, unitPrefixValue;
32966 var convert;
32967
32968 if (value === null || value === undefined || this.units.length === 0) {
32969 return value;
32970 } else if (this._isDerived()) {
32971 // This is a derived unit, so do not apply offsets.
32972 // For example, with J kg^-1 degC^-1 you would NOT want to apply the offset.
32973 var res = value;
32974 convert = Unit._getNumberConverter(Object(is["M" /* typeOf */])(value)); // convert to Fraction or BigNumber if needed
32975
32976 for (var i = 0; i < this.units.length; i++) {
32977 unitValue = convert(this.units[i].unit.value);
32978 unitPrefixValue = convert(this.units[i].prefix.value);
32979 unitPower = convert(this.units[i].power);
32980 res = multiplyScalar(res, pow(multiplyScalar(unitValue, unitPrefixValue), unitPower));
32981 }
32982
32983 return res;
32984 } else {
32985 // This is a single unit of power 1, like kg or degC
32986 convert = Unit._getNumberConverter(Object(is["M" /* typeOf */])(value)); // convert to Fraction or BigNumber if needed
32987
32988 unitValue = convert(this.units[0].unit.value);
32989 unitOffset = convert(this.units[0].unit.offset);
32990 unitPrefixValue = convert(this.units[0].prefix.value);
32991 return multiplyScalar(addScalar(value, unitOffset), multiplyScalar(unitValue, unitPrefixValue));
32992 }
32993 };
32994 /**
32995 * Denormalize a value, based on its currently set unit(s)
32996 * @memberof Unit
32997 * @param {number} value
32998 * @param {number} [prefixValue] Optional prefix value to be used (ignored if this is a derived unit)
32999 * @return {number} denormalized value
33000 * @private
33001 */
33002
33003
33004 Unit.prototype._denormalize = function (value, prefixValue) {
33005 var unitValue, unitOffset, unitPower, unitPrefixValue;
33006 var convert;
33007
33008 if (value === null || value === undefined || this.units.length === 0) {
33009 return value;
33010 } else if (this._isDerived()) {
33011 // This is a derived unit, so do not apply offsets.
33012 // For example, with J kg^-1 degC^-1 you would NOT want to apply the offset.
33013 // Also, prefixValue is ignored--but we will still use the prefix value stored in each unit, since kg is usually preferable to g unless the user decides otherwise.
33014 var res = value;
33015 convert = Unit._getNumberConverter(Object(is["M" /* typeOf */])(value)); // convert to Fraction or BigNumber if needed
33016
33017 for (var i = 0; i < this.units.length; i++) {
33018 unitValue = convert(this.units[i].unit.value);
33019 unitPrefixValue = convert(this.units[i].prefix.value);
33020 unitPower = convert(this.units[i].power);
33021 res = divideScalar(res, pow(multiplyScalar(unitValue, unitPrefixValue), unitPower));
33022 }
33023
33024 return res;
33025 } else {
33026 // This is a single unit of power 1, like kg or degC
33027 convert = Unit._getNumberConverter(Object(is["M" /* typeOf */])(value)); // convert to Fraction or BigNumber if needed
33028
33029 unitValue = convert(this.units[0].unit.value);
33030 unitPrefixValue = convert(this.units[0].prefix.value);
33031 unitOffset = convert(this.units[0].unit.offset);
33032
33033 if (prefixValue === undefined || prefixValue === null) {
33034 return subtract(divideScalar(divideScalar(value, unitValue), unitPrefixValue), unitOffset);
33035 } else {
33036 return subtract(divideScalar(divideScalar(value, unitValue), prefixValue), unitOffset);
33037 }
33038 }
33039 };
33040 /**
33041 * Find a unit from a string
33042 * @memberof Unit
33043 * @param {string} str A string like 'cm' or 'inch'
33044 * @returns {Object | null} result When found, an object with fields unit and
33045 * prefix is returned. Else, null is returned.
33046 * @private
33047 */
33048
33049
33050 function _findUnit(str) {
33051 // 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.
33052 if (Object(utils_object["f" /* hasOwnProperty */])(UNITS, str)) {
33053 var unit = UNITS[str];
33054 var prefix = unit.prefixes[''];
33055 return {
33056 unit: unit,
33057 prefix: prefix
33058 };
33059 }
33060
33061 for (var _name in UNITS) {
33062 if (Object(utils_object["f" /* hasOwnProperty */])(UNITS, _name)) {
33063 if (Object(utils_string["b" /* endsWith */])(str, _name)) {
33064 var _unit = UNITS[_name];
33065 var prefixLen = str.length - _name.length;
33066 var prefixName = str.substring(0, prefixLen);
33067
33068 var _prefix = Object(utils_object["f" /* hasOwnProperty */])(_unit.prefixes, prefixName) ? _unit.prefixes[prefixName] : undefined;
33069
33070 if (_prefix !== undefined) {
33071 // store unit, prefix, and value
33072 return {
33073 unit: _unit,
33074 prefix: _prefix
33075 };
33076 }
33077 }
33078 }
33079 }
33080
33081 return null;
33082 }
33083 /**
33084 * Test if the given expression is a unit.
33085 * The unit can have a prefix but cannot have a value.
33086 * @memberof Unit
33087 * @param {string} name A string to be tested whether it is a value less unit.
33088 * The unit can have prefix, like "cm"
33089 * @return {boolean} true if the given string is a unit
33090 */
33091
33092
33093 Unit.isValuelessUnit = function (name) {
33094 return _findUnit(name) !== null;
33095 };
33096 /**
33097 * check if this unit has given base unit
33098 * If this unit is a derived unit, this will ALWAYS return false, since by definition base units are not derived.
33099 * @memberof Unit
33100 * @param {BASE_UNITS | string | undefined} base
33101 */
33102
33103
33104 Unit.prototype.hasBase = function (base) {
33105 if (typeof base === 'string') {
33106 base = BASE_UNITS[base];
33107 }
33108
33109 if (!base) {
33110 return false;
33111 } // All dimensions must be the same
33112
33113
33114 for (var i = 0; i < BASE_DIMENSIONS.length; i++) {
33115 if (Math.abs((this.dimensions[i] || 0) - (base.dimensions[i] || 0)) > 1e-12) {
33116 return false;
33117 }
33118 }
33119
33120 return true;
33121 };
33122 /**
33123 * Check if this unit has a base or bases equal to another base or bases
33124 * For derived units, the exponent on each base also must match
33125 * @memberof Unit
33126 * @param {Unit} other
33127 * @return {boolean} true if equal base
33128 */
33129
33130
33131 Unit.prototype.equalBase = function (other) {
33132 // All dimensions must be the same
33133 for (var i = 0; i < BASE_DIMENSIONS.length; i++) {
33134 if (Math.abs((this.dimensions[i] || 0) - (other.dimensions[i] || 0)) > 1e-12) {
33135 return false;
33136 }
33137 }
33138
33139 return true;
33140 };
33141 /**
33142 * Check if this unit equals another unit
33143 * @memberof Unit
33144 * @param {Unit} other
33145 * @return {boolean} true if both units are equal
33146 */
33147
33148
33149 Unit.prototype.equals = function (other) {
33150 return this.equalBase(other) && equal(this.value, other.value);
33151 };
33152 /**
33153 * Multiply this unit with another one
33154 * @memberof Unit
33155 * @param {Unit} other
33156 * @return {Unit} product of this unit and the other unit
33157 */
33158
33159
33160 Unit.prototype.multiply = function (other) {
33161 var res = this.clone();
33162
33163 for (var i = 0; i < BASE_DIMENSIONS.length; i++) {
33164 // Dimensions arrays may be of different lengths. Default to 0.
33165 res.dimensions[i] = (this.dimensions[i] || 0) + (other.dimensions[i] || 0);
33166 } // Append other's units list onto res
33167
33168
33169 for (var _i = 0; _i < other.units.length; _i++) {
33170 // Make a deep copy
33171 var inverted = {};
33172
33173 for (var key in other.units[_i]) {
33174 inverted[key] = other.units[_i][key];
33175 }
33176
33177 res.units.push(inverted);
33178 } // If at least one operand has a value, then the result should also have a value
33179
33180
33181 if (this.value !== null || other.value !== null) {
33182 var valThis = this.value === null ? this._normalize(1) : this.value;
33183 var valOther = other.value === null ? other._normalize(1) : other.value;
33184 res.value = multiplyScalar(valThis, valOther);
33185 } else {
33186 res.value = null;
33187 }
33188
33189 res.skipAutomaticSimplification = false;
33190 return getNumericIfUnitless(res);
33191 };
33192 /**
33193 * Divide this unit by another one
33194 * @memberof Unit
33195 * @param {Unit} other
33196 * @return {Unit} result of dividing this unit by the other unit
33197 */
33198
33199
33200 Unit.prototype.divide = function (other) {
33201 var res = this.clone();
33202
33203 for (var i = 0; i < BASE_DIMENSIONS.length; i++) {
33204 // Dimensions arrays may be of different lengths. Default to 0.
33205 res.dimensions[i] = (this.dimensions[i] || 0) - (other.dimensions[i] || 0);
33206 } // Invert and append other's units list onto res
33207
33208
33209 for (var _i2 = 0; _i2 < other.units.length; _i2++) {
33210 // Make a deep copy
33211 var inverted = {};
33212
33213 for (var key in other.units[_i2]) {
33214 inverted[key] = other.units[_i2][key];
33215 }
33216
33217 inverted.power = -inverted.power;
33218 res.units.push(inverted);
33219 } // If at least one operand has a value, the result should have a value
33220
33221
33222 if (this.value !== null || other.value !== null) {
33223 var valThis = this.value === null ? this._normalize(1) : this.value;
33224 var valOther = other.value === null ? other._normalize(1) : other.value;
33225 res.value = divideScalar(valThis, valOther);
33226 } else {
33227 res.value = null;
33228 }
33229
33230 res.skipAutomaticSimplification = false;
33231 return getNumericIfUnitless(res);
33232 };
33233 /**
33234 * Calculate the power of a unit
33235 * @memberof Unit
33236 * @param {number | Fraction | BigNumber} p
33237 * @returns {Unit} The result: this^p
33238 */
33239
33240
33241 Unit.prototype.pow = function (p) {
33242 var res = this.clone();
33243
33244 for (var i = 0; i < BASE_DIMENSIONS.length; i++) {
33245 // Dimensions arrays may be of different lengths. Default to 0.
33246 res.dimensions[i] = (this.dimensions[i] || 0) * p;
33247 } // Adjust the power of each unit in the list
33248
33249
33250 for (var _i3 = 0; _i3 < res.units.length; _i3++) {
33251 res.units[_i3].power *= p;
33252 }
33253
33254 if (res.value !== null) {
33255 res.value = pow(res.value, p); // only allow numeric output, we don't want to return a Complex number
33256 // if (!isNumeric(res.value)) {
33257 // res.value = NaN
33258 // }
33259 // Update: Complex supported now
33260 } else {
33261 res.value = null;
33262 }
33263
33264 res.skipAutomaticSimplification = false;
33265 return getNumericIfUnitless(res);
33266 };
33267 /**
33268 * Return the numeric value of this unit if it is dimensionless, has a value, and config.predictable == false; or the original unit otherwise
33269 * @param {Unit} unit
33270 * @returns {number | Fraction | BigNumber | Unit} The numeric value of the unit if conditions are met, or the original unit otherwise
33271 */
33272
33273
33274 function getNumericIfUnitless(unit) {
33275 if (unit.equalBase(BASE_UNITS.NONE) && unit.value !== null && !config.predictable) {
33276 return unit.value;
33277 } else {
33278 return unit;
33279 }
33280 }
33281 /**
33282 * Calculate the absolute value of a unit
33283 * @memberof Unit
33284 * @param {number | Fraction | BigNumber} x
33285 * @returns {Unit} The result: |x|, absolute value of x
33286 */
33287
33288
33289 Unit.prototype.abs = function () {
33290 // This gives correct, but unexpected, results for units with an offset.
33291 // For example, abs(-283.15 degC) = -263.15 degC !!!
33292 var ret = this.clone();
33293 ret.value = ret.value !== null ? abs(ret.value) : null;
33294
33295 for (var i in ret.units) {
33296 if (ret.units[i].unit.name === 'VA' || ret.units[i].unit.name === 'VAR') {
33297 ret.units[i].unit = UNITS.W;
33298 }
33299 }
33300
33301 return ret;
33302 };
33303 /**
33304 * Convert the unit to a specific unit name.
33305 * @memberof Unit
33306 * @param {string | Unit} valuelessUnit A unit without value. Can have prefix, like "cm"
33307 * @returns {Unit} Returns a clone of the unit with a fixed prefix and unit.
33308 */
33309
33310
33311 Unit.prototype.to = function (valuelessUnit) {
33312 var other;
33313 var value = this.value === null ? this._normalize(1) : this.value;
33314
33315 if (typeof valuelessUnit === 'string') {
33316 // other = new Unit(null, valuelessUnit)
33317 other = Unit.parse(valuelessUnit);
33318
33319 if (!this.equalBase(other)) {
33320 throw new Error("Units do not match ('".concat(other.toString(), "' != '").concat(this.toString(), "')"));
33321 }
33322
33323 if (other.value !== null) {
33324 throw new Error('Cannot convert to a unit with a value');
33325 }
33326
33327 other.value = Object(utils_object["a" /* clone */])(value);
33328 other.fixPrefix = true;
33329 other.skipAutomaticSimplification = true;
33330 return other;
33331 } else if (Object(is["L" /* isUnit */])(valuelessUnit)) {
33332 if (!this.equalBase(valuelessUnit)) {
33333 throw new Error("Units do not match ('".concat(valuelessUnit.toString(), "' != '").concat(this.toString(), "')"));
33334 }
33335
33336 if (valuelessUnit.value !== null) {
33337 throw new Error('Cannot convert to a unit with a value');
33338 }
33339
33340 other = valuelessUnit.clone();
33341 other.value = Object(utils_object["a" /* clone */])(value);
33342 other.fixPrefix = true;
33343 other.skipAutomaticSimplification = true;
33344 return other;
33345 } else {
33346 throw new Error('String or Unit expected as parameter');
33347 }
33348 };
33349 /**
33350 * Return the value of the unit when represented with given valueless unit
33351 * @memberof Unit
33352 * @param {string | Unit} valuelessUnit For example 'cm' or 'inch'
33353 * @return {number} Returns the unit value as number.
33354 */
33355 // TODO: deprecate Unit.toNumber? It's always better to use toNumeric
33356
33357
33358 Unit.prototype.toNumber = function (valuelessUnit) {
33359 return toNumber(this.toNumeric(valuelessUnit));
33360 };
33361 /**
33362 * Return the value of the unit in the original numeric type
33363 * @memberof Unit
33364 * @param {string | Unit} valuelessUnit For example 'cm' or 'inch'
33365 * @return {number | BigNumber | Fraction} Returns the unit value
33366 */
33367
33368
33369 Unit.prototype.toNumeric = function (valuelessUnit) {
33370 var other;
33371
33372 if (valuelessUnit) {
33373 // Allow getting the numeric value without converting to a different unit
33374 other = this.to(valuelessUnit);
33375 } else {
33376 other = this.clone();
33377 }
33378
33379 if (other._isDerived()) {
33380 return other._denormalize(other.value);
33381 } else {
33382 return other._denormalize(other.value, other.units[0].prefix.value);
33383 }
33384 };
33385 /**
33386 * Get a string representation of the unit.
33387 * @memberof Unit
33388 * @return {string}
33389 */
33390
33391
33392 Unit.prototype.toString = function () {
33393 return this.format();
33394 };
33395 /**
33396 * Get a JSON representation of the unit
33397 * @memberof Unit
33398 * @returns {Object} Returns a JSON object structured as:
33399 * `{"mathjs": "Unit", "value": 2, "unit": "cm", "fixPrefix": false}`
33400 */
33401
33402
33403 Unit.prototype.toJSON = function () {
33404 return {
33405 mathjs: 'Unit',
33406 value: this._denormalize(this.value),
33407 unit: this.formatUnits(),
33408 fixPrefix: this.fixPrefix
33409 };
33410 };
33411 /**
33412 * Instantiate a Unit from a JSON object
33413 * @memberof Unit
33414 * @param {Object} json A JSON object structured as:
33415 * `{"mathjs": "Unit", "value": 2, "unit": "cm", "fixPrefix": false}`
33416 * @return {Unit}
33417 */
33418
33419
33420 Unit.fromJSON = function (json) {
33421 var unit = new Unit(json.value, json.unit);
33422 unit.fixPrefix = json.fixPrefix || false;
33423 return unit;
33424 };
33425 /**
33426 * Returns the string representation of the unit.
33427 * @memberof Unit
33428 * @return {string}
33429 */
33430
33431
33432 Unit.prototype.valueOf = Unit.prototype.toString;
33433 /**
33434 * Simplify this Unit's unit list and return a new Unit with the simplified list.
33435 * The returned Unit will contain a list of the "best" units for formatting.
33436 */
33437
33438 Unit.prototype.simplify = function () {
33439 var ret = this.clone();
33440 var proposedUnitList = []; // Search for a matching base
33441
33442 var matchingBase;
33443
33444 for (var key in currentUnitSystem) {
33445 if (ret.hasBase(BASE_UNITS[key])) {
33446 matchingBase = key;
33447 break;
33448 }
33449 }
33450
33451 if (matchingBase === 'NONE') {
33452 ret.units = [];
33453 } else {
33454 var matchingUnit;
33455
33456 if (matchingBase) {
33457 // Does the unit system have a matching unit?
33458 if (Object(utils_object["f" /* hasOwnProperty */])(currentUnitSystem, matchingBase)) {
33459 matchingUnit = currentUnitSystem[matchingBase];
33460 }
33461 }
33462
33463 if (matchingUnit) {
33464 ret.units = [{
33465 unit: matchingUnit.unit,
33466 prefix: matchingUnit.prefix,
33467 power: 1.0
33468 }];
33469 } else {
33470 // Multiple units or units with powers are formatted like this:
33471 // 5 (kg m^2) / (s^3 mol)
33472 // Build an representation from the base units of the current unit system
33473 var missingBaseDim = false;
33474
33475 for (var i = 0; i < BASE_DIMENSIONS.length; i++) {
33476 var baseDim = BASE_DIMENSIONS[i];
33477
33478 if (Math.abs(ret.dimensions[i] || 0) > 1e-12) {
33479 if (Object(utils_object["f" /* hasOwnProperty */])(currentUnitSystem, baseDim)) {
33480 proposedUnitList.push({
33481 unit: currentUnitSystem[baseDim].unit,
33482 prefix: currentUnitSystem[baseDim].prefix,
33483 power: ret.dimensions[i] || 0
33484 });
33485 } else {
33486 missingBaseDim = true;
33487 }
33488 }
33489 } // Is the proposed unit list "simpler" than the existing one?
33490
33491
33492 if (proposedUnitList.length < ret.units.length && !missingBaseDim) {
33493 // Replace this unit list with the proposed list
33494 ret.units = proposedUnitList;
33495 }
33496 }
33497 }
33498
33499 return ret;
33500 };
33501 /**
33502 * Returns a new Unit in the SI system with the same value as this one
33503 */
33504
33505
33506 Unit.prototype.toSI = function () {
33507 var ret = this.clone();
33508 var proposedUnitList = []; // Multiple units or units with powers are formatted like this:
33509 // 5 (kg m^2) / (s^3 mol)
33510 // Build an representation from the base units of the SI unit system
33511
33512 for (var i = 0; i < BASE_DIMENSIONS.length; i++) {
33513 var baseDim = BASE_DIMENSIONS[i];
33514
33515 if (Math.abs(ret.dimensions[i] || 0) > 1e-12) {
33516 if (Object(utils_object["f" /* hasOwnProperty */])(UNIT_SYSTEMS.si, baseDim)) {
33517 proposedUnitList.push({
33518 unit: UNIT_SYSTEMS.si[baseDim].unit,
33519 prefix: UNIT_SYSTEMS.si[baseDim].prefix,
33520 power: ret.dimensions[i] || 0
33521 });
33522 } else {
33523 throw new Error('Cannot express custom unit ' + baseDim + ' in SI units');
33524 }
33525 }
33526 } // Replace this unit list with the proposed list
33527
33528
33529 ret.units = proposedUnitList;
33530 ret.fixPrefix = true;
33531 ret.skipAutomaticSimplification = true;
33532 return ret;
33533 };
33534 /**
33535 * Get a string representation of the units of this Unit, without the value. The unit list is formatted as-is without first being simplified.
33536 * @memberof Unit
33537 * @return {string}
33538 */
33539
33540
33541 Unit.prototype.formatUnits = function () {
33542 var strNum = '';
33543 var strDen = '';
33544 var nNum = 0;
33545 var nDen = 0;
33546
33547 for (var i = 0; i < this.units.length; i++) {
33548 if (this.units[i].power > 0) {
33549 nNum++;
33550 strNum += ' ' + this.units[i].prefix.name + this.units[i].unit.name;
33551
33552 if (Math.abs(this.units[i].power - 1.0) > 1e-15) {
33553 strNum += '^' + this.units[i].power;
33554 }
33555 } else if (this.units[i].power < 0) {
33556 nDen++;
33557 }
33558 }
33559
33560 if (nDen > 0) {
33561 for (var _i4 = 0; _i4 < this.units.length; _i4++) {
33562 if (this.units[_i4].power < 0) {
33563 if (nNum > 0) {
33564 strDen += ' ' + this.units[_i4].prefix.name + this.units[_i4].unit.name;
33565
33566 if (Math.abs(this.units[_i4].power + 1.0) > 1e-15) {
33567 strDen += '^' + -this.units[_i4].power;
33568 }
33569 } else {
33570 strDen += ' ' + this.units[_i4].prefix.name + this.units[_i4].unit.name;
33571 strDen += '^' + this.units[_i4].power;
33572 }
33573 }
33574 }
33575 } // Remove leading " "
33576
33577
33578 strNum = strNum.substr(1);
33579 strDen = strDen.substr(1); // Add parans for better copy/paste back into evaluate, for example, or for better pretty print formatting
33580
33581 if (nNum > 1 && nDen > 0) {
33582 strNum = '(' + strNum + ')';
33583 }
33584
33585 if (nDen > 1 && nNum > 0) {
33586 strDen = '(' + strDen + ')';
33587 }
33588
33589 var str = strNum;
33590
33591 if (nNum > 0 && nDen > 0) {
33592 str += ' / ';
33593 }
33594
33595 str += strDen;
33596 return str;
33597 };
33598 /**
33599 * Get a string representation of the Unit, with optional formatting options.
33600 * @memberof Unit
33601 * @param {Object | number | Function} [options] Formatting options. See
33602 * lib/utils/number:format for a
33603 * description of the available
33604 * options.
33605 * @return {string}
33606 */
33607
33608
33609 Unit.prototype.format = function (options) {
33610 // Simplfy the unit list, unless it is valueless or was created directly in the
33611 // constructor or as the result of to or toSI
33612 var simp = this.skipAutomaticSimplification || this.value === null ? this.clone() : this.simplify(); // Apply some custom logic for handling VA and VAR. The goal is to express the value of the unit as a real value, if possible. Otherwise, use a real-valued unit instead of a complex-valued one.
33613
33614 var isImaginary = false;
33615
33616 if (typeof simp.value !== 'undefined' && simp.value !== null && Object(is["j" /* isComplex */])(simp.value)) {
33617 // TODO: Make this better, for example, use relative magnitude of re and im rather than absolute
33618 isImaginary = Math.abs(simp.value.re) < 1e-14;
33619 }
33620
33621 for (var i in simp.units) {
33622 if (simp.units[i].unit) {
33623 if (simp.units[i].unit.name === 'VA' && isImaginary) {
33624 simp.units[i].unit = UNITS.VAR;
33625 } else if (simp.units[i].unit.name === 'VAR' && !isImaginary) {
33626 simp.units[i].unit = UNITS.VA;
33627 }
33628 }
33629 } // Now apply the best prefix
33630 // Units must have only one unit and not have the fixPrefix flag set
33631
33632
33633 if (simp.units.length === 1 && !simp.fixPrefix) {
33634 // Units must have integer powers, otherwise the prefix will change the
33635 // outputted value by not-an-integer-power-of-ten
33636 if (Math.abs(simp.units[0].power - Math.round(simp.units[0].power)) < 1e-14) {
33637 // Apply the best prefix
33638 simp.units[0].prefix = simp._bestPrefix();
33639 }
33640 }
33641
33642 var value = simp._denormalize(simp.value);
33643
33644 var str = simp.value !== null ? format(value, options || {}) : '';
33645 var unitStr = simp.formatUnits();
33646
33647 if (simp.value && Object(is["j" /* isComplex */])(simp.value)) {
33648 str = '(' + str + ')'; // Surround complex values with ( ) to enable better parsing
33649 }
33650
33651 if (unitStr.length > 0 && str.length > 0) {
33652 str += ' ';
33653 }
33654
33655 str += unitStr;
33656 return str;
33657 };
33658 /**
33659 * Calculate the best prefix using current value.
33660 * @memberof Unit
33661 * @returns {Object} prefix
33662 * @private
33663 */
33664
33665
33666 Unit.prototype._bestPrefix = function () {
33667 if (this.units.length !== 1) {
33668 throw new Error('Can only compute the best prefix for single units with integer powers, like kg, s^2, N^-1, and so forth!');
33669 }
33670
33671 if (Math.abs(this.units[0].power - Math.round(this.units[0].power)) >= 1e-14) {
33672 throw new Error('Can only compute the best prefix for single units with integer powers, like kg, s^2, N^-1, and so forth!');
33673 } // find the best prefix value (resulting in the value of which
33674 // the absolute value of the log10 is closest to zero,
33675 // though with a little offset of 1.2 for nicer values: you get a
33676 // sequence 1mm 100mm 500mm 0.6m 1m 10m 100m 500m 0.6km 1km ...
33677 // Note: the units value can be any numeric type, but to find the best
33678 // prefix it's enough to work with limited precision of a regular number
33679 // Update: using mathjs abs since we also allow complex numbers
33680
33681
33682 var absValue = this.value !== null ? abs(this.value) : 0;
33683 var absUnitValue = abs(this.units[0].unit.value);
33684 var bestPrefix = this.units[0].prefix;
33685
33686 if (absValue === 0) {
33687 return bestPrefix;
33688 }
33689
33690 var power = this.units[0].power;
33691 var bestDiff = Math.log(absValue / Math.pow(bestPrefix.value * absUnitValue, power)) / Math.LN10 - 1.2;
33692 if (bestDiff > -2.200001 && bestDiff < 1.800001) return bestPrefix; // Allow the original prefix
33693
33694 bestDiff = Math.abs(bestDiff);
33695 var prefixes = this.units[0].unit.prefixes;
33696
33697 for (var p in prefixes) {
33698 if (Object(utils_object["f" /* hasOwnProperty */])(prefixes, p)) {
33699 var prefix = prefixes[p];
33700
33701 if (prefix.scientific) {
33702 var diff = Math.abs(Math.log(absValue / Math.pow(prefix.value * absUnitValue, power)) / Math.LN10 - 1.2);
33703
33704 if (diff < bestDiff || diff === bestDiff && prefix.name.length < bestPrefix.name.length) {
33705 // choose the prefix with the smallest diff, or if equal, choose the one
33706 // with the shortest name (can happen with SHORTLONG for example)
33707 bestPrefix = prefix;
33708 bestDiff = diff;
33709 }
33710 }
33711 }
33712 }
33713
33714 return bestPrefix;
33715 };
33716 /**
33717 * Returns an array of units whose sum is equal to this unit
33718 * @memberof Unit
33719 * @param {Array} [parts] An array of strings or valueless units.
33720 *
33721 * Example:
33722 *
33723 * const u = new Unit(1, 'm')
33724 * u.splitUnit(['feet', 'inch'])
33725 * [ 3 feet, 3.3700787401575 inch ]
33726 *
33727 * @return {Array} An array of units.
33728 */
33729
33730
33731 Unit.prototype.splitUnit = function (parts) {
33732 var x = this.clone();
33733 var ret = [];
33734
33735 for (var i = 0; i < parts.length; i++) {
33736 // Convert x to the requested unit
33737 x = x.to(parts[i]);
33738 if (i === parts.length - 1) break; // Get the numeric value of this unit
33739
33740 var xNumeric = x.toNumeric(); // Check to see if xNumeric is nearly equal to an integer,
33741 // since fix can incorrectly round down if there is round-off error
33742
33743 var xRounded = round(xNumeric);
33744 var xFixed = void 0;
33745 var isNearlyEqual = equal(xRounded, xNumeric);
33746
33747 if (isNearlyEqual) {
33748 xFixed = xRounded;
33749 } else {
33750 xFixed = fix(x.toNumeric());
33751 }
33752
33753 var y = new Unit(xFixed, parts[i].toString());
33754 ret.push(y);
33755 x = subtract(x, y);
33756 } // This little bit fixes a bug where the remainder should be 0 but is a little bit off.
33757 // But instead of comparing x, the remainder, with zero--we will compare the sum of
33758 // all the parts so far with the original value. If they are nearly equal,
33759 // we set the remainder to 0.
33760
33761
33762 var testSum = 0;
33763
33764 for (var _i5 = 0; _i5 < ret.length; _i5++) {
33765 testSum = addScalar(testSum, ret[_i5].value);
33766 }
33767
33768 if (equal(testSum, this.value)) {
33769 x.value = 0;
33770 }
33771
33772 ret.push(x);
33773 return ret;
33774 };
33775
33776 var PREFIXES = {
33777 NONE: {
33778 '': {
33779 name: '',
33780 value: 1,
33781 scientific: true
33782 }
33783 },
33784 SHORT: {
33785 '': {
33786 name: '',
33787 value: 1,
33788 scientific: true
33789 },
33790 da: {
33791 name: 'da',
33792 value: 1e1,
33793 scientific: false
33794 },
33795 h: {
33796 name: 'h',
33797 value: 1e2,
33798 scientific: false
33799 },
33800 k: {
33801 name: 'k',
33802 value: 1e3,
33803 scientific: true
33804 },
33805 M: {
33806 name: 'M',
33807 value: 1e6,
33808 scientific: true
33809 },
33810 G: {
33811 name: 'G',
33812 value: 1e9,
33813 scientific: true
33814 },
33815 T: {
33816 name: 'T',
33817 value: 1e12,
33818 scientific: true
33819 },
33820 P: {
33821 name: 'P',
33822 value: 1e15,
33823 scientific: true
33824 },
33825 E: {
33826 name: 'E',
33827 value: 1e18,
33828 scientific: true
33829 },
33830 Z: {
33831 name: 'Z',
33832 value: 1e21,
33833 scientific: true
33834 },
33835 Y: {
33836 name: 'Y',
33837 value: 1e24,
33838 scientific: true
33839 },
33840 d: {
33841 name: 'd',
33842 value: 1e-1,
33843 scientific: false
33844 },
33845 c: {
33846 name: 'c',
33847 value: 1e-2,
33848 scientific: false
33849 },
33850 m: {
33851 name: 'm',
33852 value: 1e-3,
33853 scientific: true
33854 },
33855 u: {
33856 name: 'u',
33857 value: 1e-6,
33858 scientific: true
33859 },
33860 n: {
33861 name: 'n',
33862 value: 1e-9,
33863 scientific: true
33864 },
33865 p: {
33866 name: 'p',
33867 value: 1e-12,
33868 scientific: true
33869 },
33870 f: {
33871 name: 'f',
33872 value: 1e-15,
33873 scientific: true
33874 },
33875 a: {
33876 name: 'a',
33877 value: 1e-18,
33878 scientific: true
33879 },
33880 z: {
33881 name: 'z',
33882 value: 1e-21,
33883 scientific: true
33884 },
33885 y: {
33886 name: 'y',
33887 value: 1e-24,
33888 scientific: true
33889 }
33890 },
33891 LONG: {
33892 '': {
33893 name: '',
33894 value: 1,
33895 scientific: true
33896 },
33897 deca: {
33898 name: 'deca',
33899 value: 1e1,
33900 scientific: false
33901 },
33902 hecto: {
33903 name: 'hecto',
33904 value: 1e2,
33905 scientific: false
33906 },
33907 kilo: {
33908 name: 'kilo',
33909 value: 1e3,
33910 scientific: true
33911 },
33912 mega: {
33913 name: 'mega',
33914 value: 1e6,
33915 scientific: true
33916 },
33917 giga: {
33918 name: 'giga',
33919 value: 1e9,
33920 scientific: true
33921 },
33922 tera: {
33923 name: 'tera',
33924 value: 1e12,
33925 scientific: true
33926 },
33927 peta: {
33928 name: 'peta',
33929 value: 1e15,
33930 scientific: true
33931 },
33932 exa: {
33933 name: 'exa',
33934 value: 1e18,
33935 scientific: true
33936 },
33937 zetta: {
33938 name: 'zetta',
33939 value: 1e21,
33940 scientific: true
33941 },
33942 yotta: {
33943 name: 'yotta',
33944 value: 1e24,
33945 scientific: true
33946 },
33947 deci: {
33948 name: 'deci',
33949 value: 1e-1,
33950 scientific: false
33951 },
33952 centi: {
33953 name: 'centi',
33954 value: 1e-2,
33955 scientific: false
33956 },
33957 milli: {
33958 name: 'milli',
33959 value: 1e-3,
33960 scientific: true
33961 },
33962 micro: {
33963 name: 'micro',
33964 value: 1e-6,
33965 scientific: true
33966 },
33967 nano: {
33968 name: 'nano',
33969 value: 1e-9,
33970 scientific: true
33971 },
33972 pico: {
33973 name: 'pico',
33974 value: 1e-12,
33975 scientific: true
33976 },
33977 femto: {
33978 name: 'femto',
33979 value: 1e-15,
33980 scientific: true
33981 },
33982 atto: {
33983 name: 'atto',
33984 value: 1e-18,
33985 scientific: true
33986 },
33987 zepto: {
33988 name: 'zepto',
33989 value: 1e-21,
33990 scientific: true
33991 },
33992 yocto: {
33993 name: 'yocto',
33994 value: 1e-24,
33995 scientific: true
33996 }
33997 },
33998 SQUARED: {
33999 '': {
34000 name: '',
34001 value: 1,
34002 scientific: true
34003 },
34004 da: {
34005 name: 'da',
34006 value: 1e2,
34007 scientific: false
34008 },
34009 h: {
34010 name: 'h',
34011 value: 1e4,
34012 scientific: false
34013 },
34014 k: {
34015 name: 'k',
34016 value: 1e6,
34017 scientific: true
34018 },
34019 M: {
34020 name: 'M',
34021 value: 1e12,
34022 scientific: true
34023 },
34024 G: {
34025 name: 'G',
34026 value: 1e18,
34027 scientific: true
34028 },
34029 T: {
34030 name: 'T',
34031 value: 1e24,
34032 scientific: true
34033 },
34034 P: {
34035 name: 'P',
34036 value: 1e30,
34037 scientific: true
34038 },
34039 E: {
34040 name: 'E',
34041 value: 1e36,
34042 scientific: true
34043 },
34044 Z: {
34045 name: 'Z',
34046 value: 1e42,
34047 scientific: true
34048 },
34049 Y: {
34050 name: 'Y',
34051 value: 1e48,
34052 scientific: true
34053 },
34054 d: {
34055 name: 'd',
34056 value: 1e-2,
34057 scientific: false
34058 },
34059 c: {
34060 name: 'c',
34061 value: 1e-4,
34062 scientific: false
34063 },
34064 m: {
34065 name: 'm',
34066 value: 1e-6,
34067 scientific: true
34068 },
34069 u: {
34070 name: 'u',
34071 value: 1e-12,
34072 scientific: true
34073 },
34074 n: {
34075 name: 'n',
34076 value: 1e-18,
34077 scientific: true
34078 },
34079 p: {
34080 name: 'p',
34081 value: 1e-24,
34082 scientific: true
34083 },
34084 f: {
34085 name: 'f',
34086 value: 1e-30,
34087 scientific: true
34088 },
34089 a: {
34090 name: 'a',
34091 value: 1e-36,
34092 scientific: true
34093 },
34094 z: {
34095 name: 'z',
34096 value: 1e-42,
34097 scientific: true
34098 },
34099 y: {
34100 name: 'y',
34101 value: 1e-48,
34102 scientific: true
34103 }
34104 },
34105 CUBIC: {
34106 '': {
34107 name: '',
34108 value: 1,
34109 scientific: true
34110 },
34111 da: {
34112 name: 'da',
34113 value: 1e3,
34114 scientific: false
34115 },
34116 h: {
34117 name: 'h',
34118 value: 1e6,
34119 scientific: false
34120 },
34121 k: {
34122 name: 'k',
34123 value: 1e9,
34124 scientific: true
34125 },
34126 M: {
34127 name: 'M',
34128 value: 1e18,
34129 scientific: true
34130 },
34131 G: {
34132 name: 'G',
34133 value: 1e27,
34134 scientific: true
34135 },
34136 T: {
34137 name: 'T',
34138 value: 1e36,
34139 scientific: true
34140 },
34141 P: {
34142 name: 'P',
34143 value: 1e45,
34144 scientific: true
34145 },
34146 E: {
34147 name: 'E',
34148 value: 1e54,
34149 scientific: true
34150 },
34151 Z: {
34152 name: 'Z',
34153 value: 1e63,
34154 scientific: true
34155 },
34156 Y: {
34157 name: 'Y',
34158 value: 1e72,
34159 scientific: true
34160 },
34161 d: {
34162 name: 'd',
34163 value: 1e-3,
34164 scientific: false
34165 },
34166 c: {
34167 name: 'c',
34168 value: 1e-6,
34169 scientific: false
34170 },
34171 m: {
34172 name: 'm',
34173 value: 1e-9,
34174 scientific: true
34175 },
34176 u: {
34177 name: 'u',
34178 value: 1e-18,
34179 scientific: true
34180 },
34181 n: {
34182 name: 'n',
34183 value: 1e-27,
34184 scientific: true
34185 },
34186 p: {
34187 name: 'p',
34188 value: 1e-36,
34189 scientific: true
34190 },
34191 f: {
34192 name: 'f',
34193 value: 1e-45,
34194 scientific: true
34195 },
34196 a: {
34197 name: 'a',
34198 value: 1e-54,
34199 scientific: true
34200 },
34201 z: {
34202 name: 'z',
34203 value: 1e-63,
34204 scientific: true
34205 },
34206 y: {
34207 name: 'y',
34208 value: 1e-72,
34209 scientific: true
34210 }
34211 },
34212 BINARY_SHORT_SI: {
34213 '': {
34214 name: '',
34215 value: 1,
34216 scientific: true
34217 },
34218 k: {
34219 name: 'k',
34220 value: 1e3,
34221 scientific: true
34222 },
34223 M: {
34224 name: 'M',
34225 value: 1e6,
34226 scientific: true
34227 },
34228 G: {
34229 name: 'G',
34230 value: 1e9,
34231 scientific: true
34232 },
34233 T: {
34234 name: 'T',
34235 value: 1e12,
34236 scientific: true
34237 },
34238 P: {
34239 name: 'P',
34240 value: 1e15,
34241 scientific: true
34242 },
34243 E: {
34244 name: 'E',
34245 value: 1e18,
34246 scientific: true
34247 },
34248 Z: {
34249 name: 'Z',
34250 value: 1e21,
34251 scientific: true
34252 },
34253 Y: {
34254 name: 'Y',
34255 value: 1e24,
34256 scientific: true
34257 }
34258 },
34259 BINARY_SHORT_IEC: {
34260 '': {
34261 name: '',
34262 value: 1,
34263 scientific: true
34264 },
34265 Ki: {
34266 name: 'Ki',
34267 value: 1024,
34268 scientific: true
34269 },
34270 Mi: {
34271 name: 'Mi',
34272 value: Math.pow(1024, 2),
34273 scientific: true
34274 },
34275 Gi: {
34276 name: 'Gi',
34277 value: Math.pow(1024, 3),
34278 scientific: true
34279 },
34280 Ti: {
34281 name: 'Ti',
34282 value: Math.pow(1024, 4),
34283 scientific: true
34284 },
34285 Pi: {
34286 name: 'Pi',
34287 value: Math.pow(1024, 5),
34288 scientific: true
34289 },
34290 Ei: {
34291 name: 'Ei',
34292 value: Math.pow(1024, 6),
34293 scientific: true
34294 },
34295 Zi: {
34296 name: 'Zi',
34297 value: Math.pow(1024, 7),
34298 scientific: true
34299 },
34300 Yi: {
34301 name: 'Yi',
34302 value: Math.pow(1024, 8),
34303 scientific: true
34304 }
34305 },
34306 BINARY_LONG_SI: {
34307 '': {
34308 name: '',
34309 value: 1,
34310 scientific: true
34311 },
34312 kilo: {
34313 name: 'kilo',
34314 value: 1e3,
34315 scientific: true
34316 },
34317 mega: {
34318 name: 'mega',
34319 value: 1e6,
34320 scientific: true
34321 },
34322 giga: {
34323 name: 'giga',
34324 value: 1e9,
34325 scientific: true
34326 },
34327 tera: {
34328 name: 'tera',
34329 value: 1e12,
34330 scientific: true
34331 },
34332 peta: {
34333 name: 'peta',
34334 value: 1e15,
34335 scientific: true
34336 },
34337 exa: {
34338 name: 'exa',
34339 value: 1e18,
34340 scientific: true
34341 },
34342 zetta: {
34343 name: 'zetta',
34344 value: 1e21,
34345 scientific: true
34346 },
34347 yotta: {
34348 name: 'yotta',
34349 value: 1e24,
34350 scientific: true
34351 }
34352 },
34353 BINARY_LONG_IEC: {
34354 '': {
34355 name: '',
34356 value: 1,
34357 scientific: true
34358 },
34359 kibi: {
34360 name: 'kibi',
34361 value: 1024,
34362 scientific: true
34363 },
34364 mebi: {
34365 name: 'mebi',
34366 value: Math.pow(1024, 2),
34367 scientific: true
34368 },
34369 gibi: {
34370 name: 'gibi',
34371 value: Math.pow(1024, 3),
34372 scientific: true
34373 },
34374 tebi: {
34375 name: 'tebi',
34376 value: Math.pow(1024, 4),
34377 scientific: true
34378 },
34379 pebi: {
34380 name: 'pebi',
34381 value: Math.pow(1024, 5),
34382 scientific: true
34383 },
34384 exi: {
34385 name: 'exi',
34386 value: Math.pow(1024, 6),
34387 scientific: true
34388 },
34389 zebi: {
34390 name: 'zebi',
34391 value: Math.pow(1024, 7),
34392 scientific: true
34393 },
34394 yobi: {
34395 name: 'yobi',
34396 value: Math.pow(1024, 8),
34397 scientific: true
34398 }
34399 },
34400 BTU: {
34401 '': {
34402 name: '',
34403 value: 1,
34404 scientific: true
34405 },
34406 MM: {
34407 name: 'MM',
34408 value: 1e6,
34409 scientific: true
34410 }
34411 }
34412 };
34413 PREFIXES.SHORTLONG = _extends({}, PREFIXES.SHORT, PREFIXES.LONG);
34414 PREFIXES.BINARY_SHORT = _extends({}, PREFIXES.BINARY_SHORT_SI, PREFIXES.BINARY_SHORT_IEC);
34415 PREFIXES.BINARY_LONG = _extends({}, PREFIXES.BINARY_LONG_SI, PREFIXES.BINARY_LONG_IEC);
34416 /* Internally, each unit is represented by a value and a dimension array. The elements of the dimensions array have the following meaning:
34417 * Index Dimension
34418 * ----- ---------
34419 * 0 Length
34420 * 1 Mass
34421 * 2 Time
34422 * 3 Current
34423 * 4 Temperature
34424 * 5 Luminous intensity
34425 * 6 Amount of substance
34426 * 7 Angle
34427 * 8 Bit (digital)
34428 * For example, the unit "298.15 K" is a pure temperature and would have a value of 298.15 and a dimension array of [0, 0, 0, 0, 1, 0, 0, 0, 0]. The unit "1 cal / (gm °C)" can be written in terms of the 9 fundamental dimensions as [length^2] / ([time^2] * [temperature]), and would a value of (after conversion to SI) 4184.0 and a dimensions array of [2, 0, -2, 0, -1, 0, 0, 0, 0].
34429 *
34430 */
34431
34432 var BASE_DIMENSIONS = ['MASS', 'LENGTH', 'TIME', 'CURRENT', 'TEMPERATURE', 'LUMINOUS_INTENSITY', 'AMOUNT_OF_SUBSTANCE', 'ANGLE', 'BIT'];
34433 var BASE_UNITS = {
34434 NONE: {
34435 dimensions: [0, 0, 0, 0, 0, 0, 0, 0, 0]
34436 },
34437 MASS: {
34438 dimensions: [1, 0, 0, 0, 0, 0, 0, 0, 0]
34439 },
34440 LENGTH: {
34441 dimensions: [0, 1, 0, 0, 0, 0, 0, 0, 0]
34442 },
34443 TIME: {
34444 dimensions: [0, 0, 1, 0, 0, 0, 0, 0, 0]
34445 },
34446 CURRENT: {
34447 dimensions: [0, 0, 0, 1, 0, 0, 0, 0, 0]
34448 },
34449 TEMPERATURE: {
34450 dimensions: [0, 0, 0, 0, 1, 0, 0, 0, 0]
34451 },
34452 LUMINOUS_INTENSITY: {
34453 dimensions: [0, 0, 0, 0, 0, 1, 0, 0, 0]
34454 },
34455 AMOUNT_OF_SUBSTANCE: {
34456 dimensions: [0, 0, 0, 0, 0, 0, 1, 0, 0]
34457 },
34458 FORCE: {
34459 dimensions: [1, 1, -2, 0, 0, 0, 0, 0, 0]
34460 },
34461 SURFACE: {
34462 dimensions: [0, 2, 0, 0, 0, 0, 0, 0, 0]
34463 },
34464 VOLUME: {
34465 dimensions: [0, 3, 0, 0, 0, 0, 0, 0, 0]
34466 },
34467 ENERGY: {
34468 dimensions: [1, 2, -2, 0, 0, 0, 0, 0, 0]
34469 },
34470 POWER: {
34471 dimensions: [1, 2, -3, 0, 0, 0, 0, 0, 0]
34472 },
34473 PRESSURE: {
34474 dimensions: [1, -1, -2, 0, 0, 0, 0, 0, 0]
34475 },
34476 ELECTRIC_CHARGE: {
34477 dimensions: [0, 0, 1, 1, 0, 0, 0, 0, 0]
34478 },
34479 ELECTRIC_CAPACITANCE: {
34480 dimensions: [-1, -2, 4, 2, 0, 0, 0, 0, 0]
34481 },
34482 ELECTRIC_POTENTIAL: {
34483 dimensions: [1, 2, -3, -1, 0, 0, 0, 0, 0]
34484 },
34485 ELECTRIC_RESISTANCE: {
34486 dimensions: [1, 2, -3, -2, 0, 0, 0, 0, 0]
34487 },
34488 ELECTRIC_INDUCTANCE: {
34489 dimensions: [1, 2, -2, -2, 0, 0, 0, 0, 0]
34490 },
34491 ELECTRIC_CONDUCTANCE: {
34492 dimensions: [-1, -2, 3, 2, 0, 0, 0, 0, 0]
34493 },
34494 MAGNETIC_FLUX: {
34495 dimensions: [1, 2, -2, -1, 0, 0, 0, 0, 0]
34496 },
34497 MAGNETIC_FLUX_DENSITY: {
34498 dimensions: [1, 0, -2, -1, 0, 0, 0, 0, 0]
34499 },
34500 FREQUENCY: {
34501 dimensions: [0, 0, -1, 0, 0, 0, 0, 0, 0]
34502 },
34503 ANGLE: {
34504 dimensions: [0, 0, 0, 0, 0, 0, 0, 1, 0]
34505 },
34506 BIT: {
34507 dimensions: [0, 0, 0, 0, 0, 0, 0, 0, 1]
34508 }
34509 };
34510
34511 for (var key in BASE_UNITS) {
34512 BASE_UNITS[key].key = key;
34513 }
34514
34515 var BASE_UNIT_NONE = {};
34516 var UNIT_NONE = {
34517 name: '',
34518 base: BASE_UNIT_NONE,
34519 value: 1,
34520 offset: 0,
34521 dimensions: BASE_DIMENSIONS.map(function (x) {
34522 return 0;
34523 })
34524 };
34525 var UNITS = {
34526 // length
34527 meter: {
34528 name: 'meter',
34529 base: BASE_UNITS.LENGTH,
34530 prefixes: PREFIXES.LONG,
34531 value: 1,
34532 offset: 0
34533 },
34534 inch: {
34535 name: 'inch',
34536 base: BASE_UNITS.LENGTH,
34537 prefixes: PREFIXES.NONE,
34538 value: 0.0254,
34539 offset: 0
34540 },
34541 foot: {
34542 name: 'foot',
34543 base: BASE_UNITS.LENGTH,
34544 prefixes: PREFIXES.NONE,
34545 value: 0.3048,
34546 offset: 0
34547 },
34548 yard: {
34549 name: 'yard',
34550 base: BASE_UNITS.LENGTH,
34551 prefixes: PREFIXES.NONE,
34552 value: 0.9144,
34553 offset: 0
34554 },
34555 mile: {
34556 name: 'mile',
34557 base: BASE_UNITS.LENGTH,
34558 prefixes: PREFIXES.NONE,
34559 value: 1609.344,
34560 offset: 0
34561 },
34562 link: {
34563 name: 'link',
34564 base: BASE_UNITS.LENGTH,
34565 prefixes: PREFIXES.NONE,
34566 value: 0.201168,
34567 offset: 0
34568 },
34569 rod: {
34570 name: 'rod',
34571 base: BASE_UNITS.LENGTH,
34572 prefixes: PREFIXES.NONE,
34573 value: 5.0292,
34574 offset: 0
34575 },
34576 chain: {
34577 name: 'chain',
34578 base: BASE_UNITS.LENGTH,
34579 prefixes: PREFIXES.NONE,
34580 value: 20.1168,
34581 offset: 0
34582 },
34583 angstrom: {
34584 name: 'angstrom',
34585 base: BASE_UNITS.LENGTH,
34586 prefixes: PREFIXES.NONE,
34587 value: 1e-10,
34588 offset: 0
34589 },
34590 m: {
34591 name: 'm',
34592 base: BASE_UNITS.LENGTH,
34593 prefixes: PREFIXES.SHORT,
34594 value: 1,
34595 offset: 0
34596 },
34597 "in": {
34598 name: 'in',
34599 base: BASE_UNITS.LENGTH,
34600 prefixes: PREFIXES.NONE,
34601 value: 0.0254,
34602 offset: 0
34603 },
34604 ft: {
34605 name: 'ft',
34606 base: BASE_UNITS.LENGTH,
34607 prefixes: PREFIXES.NONE,
34608 value: 0.3048,
34609 offset: 0
34610 },
34611 yd: {
34612 name: 'yd',
34613 base: BASE_UNITS.LENGTH,
34614 prefixes: PREFIXES.NONE,
34615 value: 0.9144,
34616 offset: 0
34617 },
34618 mi: {
34619 name: 'mi',
34620 base: BASE_UNITS.LENGTH,
34621 prefixes: PREFIXES.NONE,
34622 value: 1609.344,
34623 offset: 0
34624 },
34625 li: {
34626 name: 'li',
34627 base: BASE_UNITS.LENGTH,
34628 prefixes: PREFIXES.NONE,
34629 value: 0.201168,
34630 offset: 0
34631 },
34632 rd: {
34633 name: 'rd',
34634 base: BASE_UNITS.LENGTH,
34635 prefixes: PREFIXES.NONE,
34636 value: 5.029210,
34637 offset: 0
34638 },
34639 ch: {
34640 name: 'ch',
34641 base: BASE_UNITS.LENGTH,
34642 prefixes: PREFIXES.NONE,
34643 value: 20.1168,
34644 offset: 0
34645 },
34646 mil: {
34647 name: 'mil',
34648 base: BASE_UNITS.LENGTH,
34649 prefixes: PREFIXES.NONE,
34650 value: 0.0000254,
34651 offset: 0
34652 },
34653 // 1/1000 inch
34654 // Surface
34655 m2: {
34656 name: 'm2',
34657 base: BASE_UNITS.SURFACE,
34658 prefixes: PREFIXES.SQUARED,
34659 value: 1,
34660 offset: 0
34661 },
34662 sqin: {
34663 name: 'sqin',
34664 base: BASE_UNITS.SURFACE,
34665 prefixes: PREFIXES.NONE,
34666 value: 0.00064516,
34667 offset: 0
34668 },
34669 // 645.16 mm2
34670 sqft: {
34671 name: 'sqft',
34672 base: BASE_UNITS.SURFACE,
34673 prefixes: PREFIXES.NONE,
34674 value: 0.09290304,
34675 offset: 0
34676 },
34677 // 0.09290304 m2
34678 sqyd: {
34679 name: 'sqyd',
34680 base: BASE_UNITS.SURFACE,
34681 prefixes: PREFIXES.NONE,
34682 value: 0.83612736,
34683 offset: 0
34684 },
34685 // 0.83612736 m2
34686 sqmi: {
34687 name: 'sqmi',
34688 base: BASE_UNITS.SURFACE,
34689 prefixes: PREFIXES.NONE,
34690 value: 2589988.110336,
34691 offset: 0
34692 },
34693 // 2.589988110336 km2
34694 sqrd: {
34695 name: 'sqrd',
34696 base: BASE_UNITS.SURFACE,
34697 prefixes: PREFIXES.NONE,
34698 value: 25.29295,
34699 offset: 0
34700 },
34701 // 25.29295 m2
34702 sqch: {
34703 name: 'sqch',
34704 base: BASE_UNITS.SURFACE,
34705 prefixes: PREFIXES.NONE,
34706 value: 404.6873,
34707 offset: 0
34708 },
34709 // 404.6873 m2
34710 sqmil: {
34711 name: 'sqmil',
34712 base: BASE_UNITS.SURFACE,
34713 prefixes: PREFIXES.NONE,
34714 value: 6.4516e-10,
34715 offset: 0
34716 },
34717 // 6.4516 * 10^-10 m2
34718 acre: {
34719 name: 'acre',
34720 base: BASE_UNITS.SURFACE,
34721 prefixes: PREFIXES.NONE,
34722 value: 4046.86,
34723 offset: 0
34724 },
34725 // 4046.86 m2
34726 hectare: {
34727 name: 'hectare',
34728 base: BASE_UNITS.SURFACE,
34729 prefixes: PREFIXES.NONE,
34730 value: 10000,
34731 offset: 0
34732 },
34733 // 10000 m2
34734 // Volume
34735 m3: {
34736 name: 'm3',
34737 base: BASE_UNITS.VOLUME,
34738 prefixes: PREFIXES.CUBIC,
34739 value: 1,
34740 offset: 0
34741 },
34742 L: {
34743 name: 'L',
34744 base: BASE_UNITS.VOLUME,
34745 prefixes: PREFIXES.SHORT,
34746 value: 0.001,
34747 offset: 0
34748 },
34749 // litre
34750 l: {
34751 name: 'l',
34752 base: BASE_UNITS.VOLUME,
34753 prefixes: PREFIXES.SHORT,
34754 value: 0.001,
34755 offset: 0
34756 },
34757 // litre
34758 litre: {
34759 name: 'litre',
34760 base: BASE_UNITS.VOLUME,
34761 prefixes: PREFIXES.LONG,
34762 value: 0.001,
34763 offset: 0
34764 },
34765 cuin: {
34766 name: 'cuin',
34767 base: BASE_UNITS.VOLUME,
34768 prefixes: PREFIXES.NONE,
34769 value: 1.6387064e-5,
34770 offset: 0
34771 },
34772 // 1.6387064e-5 m3
34773 cuft: {
34774 name: 'cuft',
34775 base: BASE_UNITS.VOLUME,
34776 prefixes: PREFIXES.NONE,
34777 value: 0.028316846592,
34778 offset: 0
34779 },
34780 // 28.316 846 592 L
34781 cuyd: {
34782 name: 'cuyd',
34783 base: BASE_UNITS.VOLUME,
34784 prefixes: PREFIXES.NONE,
34785 value: 0.764554857984,
34786 offset: 0
34787 },
34788 // 764.554 857 984 L
34789 teaspoon: {
34790 name: 'teaspoon',
34791 base: BASE_UNITS.VOLUME,
34792 prefixes: PREFIXES.NONE,
34793 value: 0.000005,
34794 offset: 0
34795 },
34796 // 5 mL
34797 tablespoon: {
34798 name: 'tablespoon',
34799 base: BASE_UNITS.VOLUME,
34800 prefixes: PREFIXES.NONE,
34801 value: 0.000015,
34802 offset: 0
34803 },
34804 // 15 mL
34805 // {name: 'cup', base: BASE_UNITS.VOLUME, prefixes: PREFIXES.NONE, value: 0.000240, offset: 0}, // 240 mL // not possible, we have already another cup
34806 drop: {
34807 name: 'drop',
34808 base: BASE_UNITS.VOLUME,
34809 prefixes: PREFIXES.NONE,
34810 value: 5e-8,
34811 offset: 0
34812 },
34813 // 0.05 mL = 5e-8 m3
34814 gtt: {
34815 name: 'gtt',
34816 base: BASE_UNITS.VOLUME,
34817 prefixes: PREFIXES.NONE,
34818 value: 5e-8,
34819 offset: 0
34820 },
34821 // 0.05 mL = 5e-8 m3
34822 // Liquid volume
34823 minim: {
34824 name: 'minim',
34825 base: BASE_UNITS.VOLUME,
34826 prefixes: PREFIXES.NONE,
34827 value: 0.00000006161152,
34828 offset: 0
34829 },
34830 // 0.06161152 mL
34831 fluiddram: {
34832 name: 'fluiddram',
34833 base: BASE_UNITS.VOLUME,
34834 prefixes: PREFIXES.NONE,
34835 value: 0.0000036966911,
34836 offset: 0
34837 },
34838 // 3.696691 mL
34839 fluidounce: {
34840 name: 'fluidounce',
34841 base: BASE_UNITS.VOLUME,
34842 prefixes: PREFIXES.NONE,
34843 value: 0.00002957353,
34844 offset: 0
34845 },
34846 // 29.57353 mL
34847 gill: {
34848 name: 'gill',
34849 base: BASE_UNITS.VOLUME,
34850 prefixes: PREFIXES.NONE,
34851 value: 0.0001182941,
34852 offset: 0
34853 },
34854 // 118.2941 mL
34855 cc: {
34856 name: 'cc',
34857 base: BASE_UNITS.VOLUME,
34858 prefixes: PREFIXES.NONE,
34859 value: 1e-6,
34860 offset: 0
34861 },
34862 // 1e-6 L
34863 cup: {
34864 name: 'cup',
34865 base: BASE_UNITS.VOLUME,
34866 prefixes: PREFIXES.NONE,
34867 value: 0.0002365882,
34868 offset: 0
34869 },
34870 // 236.5882 mL
34871 pint: {
34872 name: 'pint',
34873 base: BASE_UNITS.VOLUME,
34874 prefixes: PREFIXES.NONE,
34875 value: 0.0004731765,
34876 offset: 0
34877 },
34878 // 473.1765 mL
34879 quart: {
34880 name: 'quart',
34881 base: BASE_UNITS.VOLUME,
34882 prefixes: PREFIXES.NONE,
34883 value: 0.0009463529,
34884 offset: 0
34885 },
34886 // 946.3529 mL
34887 gallon: {
34888 name: 'gallon',
34889 base: BASE_UNITS.VOLUME,
34890 prefixes: PREFIXES.NONE,
34891 value: 0.003785412,
34892 offset: 0
34893 },
34894 // 3.785412 L
34895 beerbarrel: {
34896 name: 'beerbarrel',
34897 base: BASE_UNITS.VOLUME,
34898 prefixes: PREFIXES.NONE,
34899 value: 0.1173478,
34900 offset: 0
34901 },
34902 // 117.3478 L
34903 oilbarrel: {
34904 name: 'oilbarrel',
34905 base: BASE_UNITS.VOLUME,
34906 prefixes: PREFIXES.NONE,
34907 value: 0.1589873,
34908 offset: 0
34909 },
34910 // 158.9873 L
34911 hogshead: {
34912 name: 'hogshead',
34913 base: BASE_UNITS.VOLUME,
34914 prefixes: PREFIXES.NONE,
34915 value: 0.2384810,
34916 offset: 0
34917 },
34918 // 238.4810 L
34919 // {name: 'min', base: BASE_UNITS.VOLUME, prefixes: PREFIXES.NONE, value: 0.00000006161152, offset: 0}, // 0.06161152 mL // min is already in use as minute
34920 fldr: {
34921 name: 'fldr',
34922 base: BASE_UNITS.VOLUME,
34923 prefixes: PREFIXES.NONE,
34924 value: 0.0000036966911,
34925 offset: 0
34926 },
34927 // 3.696691 mL
34928 floz: {
34929 name: 'floz',
34930 base: BASE_UNITS.VOLUME,
34931 prefixes: PREFIXES.NONE,
34932 value: 0.00002957353,
34933 offset: 0
34934 },
34935 // 29.57353 mL
34936 gi: {
34937 name: 'gi',
34938 base: BASE_UNITS.VOLUME,
34939 prefixes: PREFIXES.NONE,
34940 value: 0.0001182941,
34941 offset: 0
34942 },
34943 // 118.2941 mL
34944 cp: {
34945 name: 'cp',
34946 base: BASE_UNITS.VOLUME,
34947 prefixes: PREFIXES.NONE,
34948 value: 0.0002365882,
34949 offset: 0
34950 },
34951 // 236.5882 mL
34952 pt: {
34953 name: 'pt',
34954 base: BASE_UNITS.VOLUME,
34955 prefixes: PREFIXES.NONE,
34956 value: 0.0004731765,
34957 offset: 0
34958 },
34959 // 473.1765 mL
34960 qt: {
34961 name: 'qt',
34962 base: BASE_UNITS.VOLUME,
34963 prefixes: PREFIXES.NONE,
34964 value: 0.0009463529,
34965 offset: 0
34966 },
34967 // 946.3529 mL
34968 gal: {
34969 name: 'gal',
34970 base: BASE_UNITS.VOLUME,
34971 prefixes: PREFIXES.NONE,
34972 value: 0.003785412,
34973 offset: 0
34974 },
34975 // 3.785412 L
34976 bbl: {
34977 name: 'bbl',
34978 base: BASE_UNITS.VOLUME,
34979 prefixes: PREFIXES.NONE,
34980 value: 0.1173478,
34981 offset: 0
34982 },
34983 // 117.3478 L
34984 obl: {
34985 name: 'obl',
34986 base: BASE_UNITS.VOLUME,
34987 prefixes: PREFIXES.NONE,
34988 value: 0.1589873,
34989 offset: 0
34990 },
34991 // 158.9873 L
34992 // {name: 'hogshead', base: BASE_UNITS.VOLUME, prefixes: PREFIXES.NONE, value: 0.2384810, offset: 0}, // 238.4810 L // TODO: hh?
34993 // Mass
34994 g: {
34995 name: 'g',
34996 base: BASE_UNITS.MASS,
34997 prefixes: PREFIXES.SHORT,
34998 value: 0.001,
34999 offset: 0
35000 },
35001 gram: {
35002 name: 'gram',
35003 base: BASE_UNITS.MASS,
35004 prefixes: PREFIXES.LONG,
35005 value: 0.001,
35006 offset: 0
35007 },
35008 ton: {
35009 name: 'ton',
35010 base: BASE_UNITS.MASS,
35011 prefixes: PREFIXES.SHORT,
35012 value: 907.18474,
35013 offset: 0
35014 },
35015 t: {
35016 name: 't',
35017 base: BASE_UNITS.MASS,
35018 prefixes: PREFIXES.SHORT,
35019 value: 1000,
35020 offset: 0
35021 },
35022 tonne: {
35023 name: 'tonne',
35024 base: BASE_UNITS.MASS,
35025 prefixes: PREFIXES.LONG,
35026 value: 1000,
35027 offset: 0
35028 },
35029 grain: {
35030 name: 'grain',
35031 base: BASE_UNITS.MASS,
35032 prefixes: PREFIXES.NONE,
35033 value: 64.79891e-6,
35034 offset: 0
35035 },
35036 dram: {
35037 name: 'dram',
35038 base: BASE_UNITS.MASS,
35039 prefixes: PREFIXES.NONE,
35040 value: 1.7718451953125e-3,
35041 offset: 0
35042 },
35043 ounce: {
35044 name: 'ounce',
35045 base: BASE_UNITS.MASS,
35046 prefixes: PREFIXES.NONE,
35047 value: 28.349523125e-3,
35048 offset: 0
35049 },
35050 poundmass: {
35051 name: 'poundmass',
35052 base: BASE_UNITS.MASS,
35053 prefixes: PREFIXES.NONE,
35054 value: 453.59237e-3,
35055 offset: 0
35056 },
35057 hundredweight: {
35058 name: 'hundredweight',
35059 base: BASE_UNITS.MASS,
35060 prefixes: PREFIXES.NONE,
35061 value: 45.359237,
35062 offset: 0
35063 },
35064 stick: {
35065 name: 'stick',
35066 base: BASE_UNITS.MASS,
35067 prefixes: PREFIXES.NONE,
35068 value: 115e-3,
35069 offset: 0
35070 },
35071 stone: {
35072 name: 'stone',
35073 base: BASE_UNITS.MASS,
35074 prefixes: PREFIXES.NONE,
35075 value: 6.35029318,
35076 offset: 0
35077 },
35078 gr: {
35079 name: 'gr',
35080 base: BASE_UNITS.MASS,
35081 prefixes: PREFIXES.NONE,
35082 value: 64.79891e-6,
35083 offset: 0
35084 },
35085 dr: {
35086 name: 'dr',
35087 base: BASE_UNITS.MASS,
35088 prefixes: PREFIXES.NONE,
35089 value: 1.7718451953125e-3,
35090 offset: 0
35091 },
35092 oz: {
35093 name: 'oz',
35094 base: BASE_UNITS.MASS,
35095 prefixes: PREFIXES.NONE,
35096 value: 28.349523125e-3,
35097 offset: 0
35098 },
35099 lbm: {
35100 name: 'lbm',
35101 base: BASE_UNITS.MASS,
35102 prefixes: PREFIXES.NONE,
35103 value: 453.59237e-3,
35104 offset: 0
35105 },
35106 cwt: {
35107 name: 'cwt',
35108 base: BASE_UNITS.MASS,
35109 prefixes: PREFIXES.NONE,
35110 value: 45.359237,
35111 offset: 0
35112 },
35113 // Time
35114 s: {
35115 name: 's',
35116 base: BASE_UNITS.TIME,
35117 prefixes: PREFIXES.SHORT,
35118 value: 1,
35119 offset: 0
35120 },
35121 min: {
35122 name: 'min',
35123 base: BASE_UNITS.TIME,
35124 prefixes: PREFIXES.NONE,
35125 value: 60,
35126 offset: 0
35127 },
35128 h: {
35129 name: 'h',
35130 base: BASE_UNITS.TIME,
35131 prefixes: PREFIXES.NONE,
35132 value: 3600,
35133 offset: 0
35134 },
35135 second: {
35136 name: 'second',
35137 base: BASE_UNITS.TIME,
35138 prefixes: PREFIXES.LONG,
35139 value: 1,
35140 offset: 0
35141 },
35142 sec: {
35143 name: 'sec',
35144 base: BASE_UNITS.TIME,
35145 prefixes: PREFIXES.LONG,
35146 value: 1,
35147 offset: 0
35148 },
35149 minute: {
35150 name: 'minute',
35151 base: BASE_UNITS.TIME,
35152 prefixes: PREFIXES.NONE,
35153 value: 60,
35154 offset: 0
35155 },
35156 hour: {
35157 name: 'hour',
35158 base: BASE_UNITS.TIME,
35159 prefixes: PREFIXES.NONE,
35160 value: 3600,
35161 offset: 0
35162 },
35163 day: {
35164 name: 'day',
35165 base: BASE_UNITS.TIME,
35166 prefixes: PREFIXES.NONE,
35167 value: 86400,
35168 offset: 0
35169 },
35170 week: {
35171 name: 'week',
35172 base: BASE_UNITS.TIME,
35173 prefixes: PREFIXES.NONE,
35174 value: 7 * 86400,
35175 offset: 0
35176 },
35177 month: {
35178 name: 'month',
35179 base: BASE_UNITS.TIME,
35180 prefixes: PREFIXES.NONE,
35181 value: 2629800,
35182 // 1/12th of Julian year
35183 offset: 0
35184 },
35185 year: {
35186 name: 'year',
35187 base: BASE_UNITS.TIME,
35188 prefixes: PREFIXES.NONE,
35189 value: 31557600,
35190 // Julian year
35191 offset: 0
35192 },
35193 decade: {
35194 name: 'decade',
35195 base: BASE_UNITS.TIME,
35196 prefixes: PREFIXES.NONE,
35197 value: 315576000,
35198 // Julian decade
35199 offset: 0
35200 },
35201 century: {
35202 name: 'century',
35203 base: BASE_UNITS.TIME,
35204 prefixes: PREFIXES.NONE,
35205 value: 3155760000,
35206 // Julian century
35207 offset: 0
35208 },
35209 millennium: {
35210 name: 'millennium',
35211 base: BASE_UNITS.TIME,
35212 prefixes: PREFIXES.NONE,
35213 value: 31557600000,
35214 // Julian millennium
35215 offset: 0
35216 },
35217 // Frequency
35218 hertz: {
35219 name: 'Hertz',
35220 base: BASE_UNITS.FREQUENCY,
35221 prefixes: PREFIXES.LONG,
35222 value: 1,
35223 offset: 0,
35224 reciprocal: true
35225 },
35226 Hz: {
35227 name: 'Hz',
35228 base: BASE_UNITS.FREQUENCY,
35229 prefixes: PREFIXES.SHORT,
35230 value: 1,
35231 offset: 0,
35232 reciprocal: true
35233 },
35234 // Angle
35235 rad: {
35236 name: 'rad',
35237 base: BASE_UNITS.ANGLE,
35238 prefixes: PREFIXES.SHORT,
35239 value: 1,
35240 offset: 0
35241 },
35242 radian: {
35243 name: 'radian',
35244 base: BASE_UNITS.ANGLE,
35245 prefixes: PREFIXES.LONG,
35246 value: 1,
35247 offset: 0
35248 },
35249 // deg = rad / (2*pi) * 360 = rad / 0.017453292519943295769236907684888
35250 deg: {
35251 name: 'deg',
35252 base: BASE_UNITS.ANGLE,
35253 prefixes: PREFIXES.SHORT,
35254 value: null,
35255 // will be filled in by calculateAngleValues()
35256 offset: 0
35257 },
35258 degree: {
35259 name: 'degree',
35260 base: BASE_UNITS.ANGLE,
35261 prefixes: PREFIXES.LONG,
35262 value: null,
35263 // will be filled in by calculateAngleValues()
35264 offset: 0
35265 },
35266 // grad = rad / (2*pi) * 400 = rad / 0.015707963267948966192313216916399
35267 grad: {
35268 name: 'grad',
35269 base: BASE_UNITS.ANGLE,
35270 prefixes: PREFIXES.SHORT,
35271 value: null,
35272 // will be filled in by calculateAngleValues()
35273 offset: 0
35274 },
35275 gradian: {
35276 name: 'gradian',
35277 base: BASE_UNITS.ANGLE,
35278 prefixes: PREFIXES.LONG,
35279 value: null,
35280 // will be filled in by calculateAngleValues()
35281 offset: 0
35282 },
35283 // cycle = rad / (2*pi) = rad / 6.2831853071795864769252867665793
35284 cycle: {
35285 name: 'cycle',
35286 base: BASE_UNITS.ANGLE,
35287 prefixes: PREFIXES.NONE,
35288 value: null,
35289 // will be filled in by calculateAngleValues()
35290 offset: 0
35291 },
35292 // arcsec = rad / (3600 * (360 / 2 * pi)) = rad / 0.0000048481368110953599358991410235795
35293 arcsec: {
35294 name: 'arcsec',
35295 base: BASE_UNITS.ANGLE,
35296 prefixes: PREFIXES.NONE,
35297 value: null,
35298 // will be filled in by calculateAngleValues()
35299 offset: 0
35300 },
35301 // arcmin = rad / (60 * (360 / 2 * pi)) = rad / 0.00029088820866572159615394846141477
35302 arcmin: {
35303 name: 'arcmin',
35304 base: BASE_UNITS.ANGLE,
35305 prefixes: PREFIXES.NONE,
35306 value: null,
35307 // will be filled in by calculateAngleValues()
35308 offset: 0
35309 },
35310 // Electric current
35311 A: {
35312 name: 'A',
35313 base: BASE_UNITS.CURRENT,
35314 prefixes: PREFIXES.SHORT,
35315 value: 1,
35316 offset: 0
35317 },
35318 ampere: {
35319 name: 'ampere',
35320 base: BASE_UNITS.CURRENT,
35321 prefixes: PREFIXES.LONG,
35322 value: 1,
35323 offset: 0
35324 },
35325 // Temperature
35326 // K(C) = °C + 273.15
35327 // K(F) = (°F + 459.67) / 1.8
35328 // K(R) = °R / 1.8
35329 K: {
35330 name: 'K',
35331 base: BASE_UNITS.TEMPERATURE,
35332 prefixes: PREFIXES.NONE,
35333 value: 1,
35334 offset: 0
35335 },
35336 degC: {
35337 name: 'degC',
35338 base: BASE_UNITS.TEMPERATURE,
35339 prefixes: PREFIXES.NONE,
35340 value: 1,
35341 offset: 273.15
35342 },
35343 degF: {
35344 name: 'degF',
35345 base: BASE_UNITS.TEMPERATURE,
35346 prefixes: PREFIXES.NONE,
35347 value: 1 / 1.8,
35348 offset: 459.67
35349 },
35350 degR: {
35351 name: 'degR',
35352 base: BASE_UNITS.TEMPERATURE,
35353 prefixes: PREFIXES.NONE,
35354 value: 1 / 1.8,
35355 offset: 0
35356 },
35357 kelvin: {
35358 name: 'kelvin',
35359 base: BASE_UNITS.TEMPERATURE,
35360 prefixes: PREFIXES.NONE,
35361 value: 1,
35362 offset: 0
35363 },
35364 celsius: {
35365 name: 'celsius',
35366 base: BASE_UNITS.TEMPERATURE,
35367 prefixes: PREFIXES.NONE,
35368 value: 1,
35369 offset: 273.15
35370 },
35371 fahrenheit: {
35372 name: 'fahrenheit',
35373 base: BASE_UNITS.TEMPERATURE,
35374 prefixes: PREFIXES.NONE,
35375 value: 1 / 1.8,
35376 offset: 459.67
35377 },
35378 rankine: {
35379 name: 'rankine',
35380 base: BASE_UNITS.TEMPERATURE,
35381 prefixes: PREFIXES.NONE,
35382 value: 1 / 1.8,
35383 offset: 0
35384 },
35385 // amount of substance
35386 mol: {
35387 name: 'mol',
35388 base: BASE_UNITS.AMOUNT_OF_SUBSTANCE,
35389 prefixes: PREFIXES.SHORT,
35390 value: 1,
35391 offset: 0
35392 },
35393 mole: {
35394 name: 'mole',
35395 base: BASE_UNITS.AMOUNT_OF_SUBSTANCE,
35396 prefixes: PREFIXES.LONG,
35397 value: 1,
35398 offset: 0
35399 },
35400 // luminous intensity
35401 cd: {
35402 name: 'cd',
35403 base: BASE_UNITS.LUMINOUS_INTENSITY,
35404 prefixes: PREFIXES.SHORT,
35405 value: 1,
35406 offset: 0
35407 },
35408 candela: {
35409 name: 'candela',
35410 base: BASE_UNITS.LUMINOUS_INTENSITY,
35411 prefixes: PREFIXES.LONG,
35412 value: 1,
35413 offset: 0
35414 },
35415 // TODO: units STERADIAN
35416 // {name: 'sr', base: BASE_UNITS.STERADIAN, prefixes: PREFIXES.NONE, value: 1, offset: 0},
35417 // {name: 'steradian', base: BASE_UNITS.STERADIAN, prefixes: PREFIXES.NONE, value: 1, offset: 0},
35418 // Force
35419 N: {
35420 name: 'N',
35421 base: BASE_UNITS.FORCE,
35422 prefixes: PREFIXES.SHORT,
35423 value: 1,
35424 offset: 0
35425 },
35426 newton: {
35427 name: 'newton',
35428 base: BASE_UNITS.FORCE,
35429 prefixes: PREFIXES.LONG,
35430 value: 1,
35431 offset: 0
35432 },
35433 dyn: {
35434 name: 'dyn',
35435 base: BASE_UNITS.FORCE,
35436 prefixes: PREFIXES.SHORT,
35437 value: 0.00001,
35438 offset: 0
35439 },
35440 dyne: {
35441 name: 'dyne',
35442 base: BASE_UNITS.FORCE,
35443 prefixes: PREFIXES.LONG,
35444 value: 0.00001,
35445 offset: 0
35446 },
35447 lbf: {
35448 name: 'lbf',
35449 base: BASE_UNITS.FORCE,
35450 prefixes: PREFIXES.NONE,
35451 value: 4.4482216152605,
35452 offset: 0
35453 },
35454 poundforce: {
35455 name: 'poundforce',
35456 base: BASE_UNITS.FORCE,
35457 prefixes: PREFIXES.NONE,
35458 value: 4.4482216152605,
35459 offset: 0
35460 },
35461 kip: {
35462 name: 'kip',
35463 base: BASE_UNITS.FORCE,
35464 prefixes: PREFIXES.LONG,
35465 value: 4448.2216,
35466 offset: 0
35467 },
35468 // Energy
35469 J: {
35470 name: 'J',
35471 base: BASE_UNITS.ENERGY,
35472 prefixes: PREFIXES.SHORT,
35473 value: 1,
35474 offset: 0
35475 },
35476 joule: {
35477 name: 'joule',
35478 base: BASE_UNITS.ENERGY,
35479 prefixes: PREFIXES.SHORT,
35480 value: 1,
35481 offset: 0
35482 },
35483 erg: {
35484 name: 'erg',
35485 base: BASE_UNITS.ENERGY,
35486 prefixes: PREFIXES.NONE,
35487 value: 1e-7,
35488 offset: 0
35489 },
35490 Wh: {
35491 name: 'Wh',
35492 base: BASE_UNITS.ENERGY,
35493 prefixes: PREFIXES.SHORT,
35494 value: 3600,
35495 offset: 0
35496 },
35497 BTU: {
35498 name: 'BTU',
35499 base: BASE_UNITS.ENERGY,
35500 prefixes: PREFIXES.BTU,
35501 value: 1055.05585262,
35502 offset: 0
35503 },
35504 eV: {
35505 name: 'eV',
35506 base: BASE_UNITS.ENERGY,
35507 prefixes: PREFIXES.SHORT,
35508 value: 1.602176565e-19,
35509 offset: 0
35510 },
35511 electronvolt: {
35512 name: 'electronvolt',
35513 base: BASE_UNITS.ENERGY,
35514 prefixes: PREFIXES.LONG,
35515 value: 1.602176565e-19,
35516 offset: 0
35517 },
35518 // Power
35519 W: {
35520 name: 'W',
35521 base: BASE_UNITS.POWER,
35522 prefixes: PREFIXES.SHORT,
35523 value: 1,
35524 offset: 0
35525 },
35526 watt: {
35527 name: 'watt',
35528 base: BASE_UNITS.POWER,
35529 prefixes: PREFIXES.LONG,
35530 value: 1,
35531 offset: 0
35532 },
35533 hp: {
35534 name: 'hp',
35535 base: BASE_UNITS.POWER,
35536 prefixes: PREFIXES.NONE,
35537 value: 745.6998715386,
35538 offset: 0
35539 },
35540 // Electrical power units
35541 VAR: {
35542 name: 'VAR',
35543 base: BASE_UNITS.POWER,
35544 prefixes: PREFIXES.SHORT,
35545 value: Complex.I,
35546 offset: 0
35547 },
35548 VA: {
35549 name: 'VA',
35550 base: BASE_UNITS.POWER,
35551 prefixes: PREFIXES.SHORT,
35552 value: 1,
35553 offset: 0
35554 },
35555 // Pressure
35556 Pa: {
35557 name: 'Pa',
35558 base: BASE_UNITS.PRESSURE,
35559 prefixes: PREFIXES.SHORT,
35560 value: 1,
35561 offset: 0
35562 },
35563 psi: {
35564 name: 'psi',
35565 base: BASE_UNITS.PRESSURE,
35566 prefixes: PREFIXES.NONE,
35567 value: 6894.75729276459,
35568 offset: 0
35569 },
35570 atm: {
35571 name: 'atm',
35572 base: BASE_UNITS.PRESSURE,
35573 prefixes: PREFIXES.NONE,
35574 value: 101325,
35575 offset: 0
35576 },
35577 bar: {
35578 name: 'bar',
35579 base: BASE_UNITS.PRESSURE,
35580 prefixes: PREFIXES.SHORTLONG,
35581 value: 100000,
35582 offset: 0
35583 },
35584 torr: {
35585 name: 'torr',
35586 base: BASE_UNITS.PRESSURE,
35587 prefixes: PREFIXES.NONE,
35588 value: 133.322,
35589 offset: 0
35590 },
35591 mmHg: {
35592 name: 'mmHg',
35593 base: BASE_UNITS.PRESSURE,
35594 prefixes: PREFIXES.NONE,
35595 value: 133.322,
35596 offset: 0
35597 },
35598 mmH2O: {
35599 name: 'mmH2O',
35600 base: BASE_UNITS.PRESSURE,
35601 prefixes: PREFIXES.NONE,
35602 value: 9.80665,
35603 offset: 0
35604 },
35605 cmH2O: {
35606 name: 'cmH2O',
35607 base: BASE_UNITS.PRESSURE,
35608 prefixes: PREFIXES.NONE,
35609 value: 98.0665,
35610 offset: 0
35611 },
35612 // Electric charge
35613 coulomb: {
35614 name: 'coulomb',
35615 base: BASE_UNITS.ELECTRIC_CHARGE,
35616 prefixes: PREFIXES.LONG,
35617 value: 1,
35618 offset: 0
35619 },
35620 C: {
35621 name: 'C',
35622 base: BASE_UNITS.ELECTRIC_CHARGE,
35623 prefixes: PREFIXES.SHORT,
35624 value: 1,
35625 offset: 0
35626 },
35627 // Electric capacitance
35628 farad: {
35629 name: 'farad',
35630 base: BASE_UNITS.ELECTRIC_CAPACITANCE,
35631 prefixes: PREFIXES.LONG,
35632 value: 1,
35633 offset: 0
35634 },
35635 F: {
35636 name: 'F',
35637 base: BASE_UNITS.ELECTRIC_CAPACITANCE,
35638 prefixes: PREFIXES.SHORT,
35639 value: 1,
35640 offset: 0
35641 },
35642 // Electric potential
35643 volt: {
35644 name: 'volt',
35645 base: BASE_UNITS.ELECTRIC_POTENTIAL,
35646 prefixes: PREFIXES.LONG,
35647 value: 1,
35648 offset: 0
35649 },
35650 V: {
35651 name: 'V',
35652 base: BASE_UNITS.ELECTRIC_POTENTIAL,
35653 prefixes: PREFIXES.SHORT,
35654 value: 1,
35655 offset: 0
35656 },
35657 // Electric resistance
35658 ohm: {
35659 name: 'ohm',
35660 base: BASE_UNITS.ELECTRIC_RESISTANCE,
35661 prefixes: PREFIXES.SHORTLONG,
35662 // Both Mohm and megaohm are acceptable
35663 value: 1,
35664 offset: 0
35665 },
35666
35667 /*
35668 * Unicode breaks in browsers if charset is not specified
35669 Ω: {
35670 name: 'Ω',
35671 base: BASE_UNITS.ELECTRIC_RESISTANCE,
35672 prefixes: PREFIXES.SHORT,
35673 value: 1,
35674 offset: 0
35675 },
35676 */
35677 // Electric inductance
35678 henry: {
35679 name: 'henry',
35680 base: BASE_UNITS.ELECTRIC_INDUCTANCE,
35681 prefixes: PREFIXES.LONG,
35682 value: 1,
35683 offset: 0
35684 },
35685 H: {
35686 name: 'H',
35687 base: BASE_UNITS.ELECTRIC_INDUCTANCE,
35688 prefixes: PREFIXES.SHORT,
35689 value: 1,
35690 offset: 0
35691 },
35692 // Electric conductance
35693 siemens: {
35694 name: 'siemens',
35695 base: BASE_UNITS.ELECTRIC_CONDUCTANCE,
35696 prefixes: PREFIXES.LONG,
35697 value: 1,
35698 offset: 0
35699 },
35700 S: {
35701 name: 'S',
35702 base: BASE_UNITS.ELECTRIC_CONDUCTANCE,
35703 prefixes: PREFIXES.SHORT,
35704 value: 1,
35705 offset: 0
35706 },
35707 // Magnetic flux
35708 weber: {
35709 name: 'weber',
35710 base: BASE_UNITS.MAGNETIC_FLUX,
35711 prefixes: PREFIXES.LONG,
35712 value: 1,
35713 offset: 0
35714 },
35715 Wb: {
35716 name: 'Wb',
35717 base: BASE_UNITS.MAGNETIC_FLUX,
35718 prefixes: PREFIXES.SHORT,
35719 value: 1,
35720 offset: 0
35721 },
35722 // Magnetic flux density
35723 tesla: {
35724 name: 'tesla',
35725 base: BASE_UNITS.MAGNETIC_FLUX_DENSITY,
35726 prefixes: PREFIXES.LONG,
35727 value: 1,
35728 offset: 0
35729 },
35730 T: {
35731 name: 'T',
35732 base: BASE_UNITS.MAGNETIC_FLUX_DENSITY,
35733 prefixes: PREFIXES.SHORT,
35734 value: 1,
35735 offset: 0
35736 },
35737 // Binary
35738 b: {
35739 name: 'b',
35740 base: BASE_UNITS.BIT,
35741 prefixes: PREFIXES.BINARY_SHORT,
35742 value: 1,
35743 offset: 0
35744 },
35745 bits: {
35746 name: 'bits',
35747 base: BASE_UNITS.BIT,
35748 prefixes: PREFIXES.BINARY_LONG,
35749 value: 1,
35750 offset: 0
35751 },
35752 B: {
35753 name: 'B',
35754 base: BASE_UNITS.BIT,
35755 prefixes: PREFIXES.BINARY_SHORT,
35756 value: 8,
35757 offset: 0
35758 },
35759 bytes: {
35760 name: 'bytes',
35761 base: BASE_UNITS.BIT,
35762 prefixes: PREFIXES.BINARY_LONG,
35763 value: 8,
35764 offset: 0
35765 }
35766 }; // aliases (formerly plurals)
35767
35768 var ALIASES = {
35769 meters: 'meter',
35770 inches: 'inch',
35771 feet: 'foot',
35772 yards: 'yard',
35773 miles: 'mile',
35774 links: 'link',
35775 rods: 'rod',
35776 chains: 'chain',
35777 angstroms: 'angstrom',
35778 lt: 'l',
35779 litres: 'litre',
35780 liter: 'litre',
35781 liters: 'litre',
35782 teaspoons: 'teaspoon',
35783 tablespoons: 'tablespoon',
35784 minims: 'minim',
35785 fluiddrams: 'fluiddram',
35786 fluidounces: 'fluidounce',
35787 gills: 'gill',
35788 cups: 'cup',
35789 pints: 'pint',
35790 quarts: 'quart',
35791 gallons: 'gallon',
35792 beerbarrels: 'beerbarrel',
35793 oilbarrels: 'oilbarrel',
35794 hogsheads: 'hogshead',
35795 gtts: 'gtt',
35796 grams: 'gram',
35797 tons: 'ton',
35798 tonnes: 'tonne',
35799 grains: 'grain',
35800 drams: 'dram',
35801 ounces: 'ounce',
35802 poundmasses: 'poundmass',
35803 hundredweights: 'hundredweight',
35804 sticks: 'stick',
35805 lb: 'lbm',
35806 lbs: 'lbm',
35807 kips: 'kip',
35808 acres: 'acre',
35809 hectares: 'hectare',
35810 sqfeet: 'sqft',
35811 sqyard: 'sqyd',
35812 sqmile: 'sqmi',
35813 sqmiles: 'sqmi',
35814 mmhg: 'mmHg',
35815 mmh2o: 'mmH2O',
35816 cmh2o: 'cmH2O',
35817 seconds: 'second',
35818 secs: 'second',
35819 minutes: 'minute',
35820 mins: 'minute',
35821 hours: 'hour',
35822 hr: 'hour',
35823 hrs: 'hour',
35824 days: 'day',
35825 weeks: 'week',
35826 months: 'month',
35827 years: 'year',
35828 decades: 'decade',
35829 centuries: 'century',
35830 millennia: 'millennium',
35831 hertz: 'hertz',
35832 radians: 'radian',
35833 degrees: 'degree',
35834 gradians: 'gradian',
35835 cycles: 'cycle',
35836 arcsecond: 'arcsec',
35837 arcseconds: 'arcsec',
35838 arcminute: 'arcmin',
35839 arcminutes: 'arcmin',
35840 BTUs: 'BTU',
35841 watts: 'watt',
35842 joules: 'joule',
35843 amperes: 'ampere',
35844 coulombs: 'coulomb',
35845 volts: 'volt',
35846 ohms: 'ohm',
35847 farads: 'farad',
35848 webers: 'weber',
35849 teslas: 'tesla',
35850 electronvolts: 'electronvolt',
35851 moles: 'mole',
35852 bit: 'bits',
35853 "byte": 'bytes'
35854 };
35855 /**
35856 * Calculate the values for the angle units.
35857 * Value is calculated as number or BigNumber depending on the configuration
35858 * @param {{number: 'number' | 'BigNumber'}} config
35859 */
35860
35861 function calculateAngleValues(config) {
35862 if (config.number === 'BigNumber') {
35863 var pi = createBigNumberPi(_BigNumber);
35864 UNITS.rad.value = new _BigNumber(1);
35865 UNITS.deg.value = pi.div(180); // 2 * pi / 360
35866
35867 UNITS.grad.value = pi.div(200); // 2 * pi / 400
35868
35869 UNITS.cycle.value = pi.times(2); // 2 * pi
35870
35871 UNITS.arcsec.value = pi.div(648000); // 2 * pi / 360 / 3600
35872
35873 UNITS.arcmin.value = pi.div(10800); // 2 * pi / 360 / 60
35874 } else {
35875 // number
35876 UNITS.rad.value = 1;
35877 UNITS.deg.value = Math.PI / 180; // 2 * pi / 360
35878
35879 UNITS.grad.value = Math.PI / 200; // 2 * pi / 400
35880
35881 UNITS.cycle.value = Math.PI * 2; // 2 * pi
35882
35883 UNITS.arcsec.value = Math.PI / 648000; // 2 * pi / 360 / 3600
35884
35885 UNITS.arcmin.value = Math.PI / 10800; // 2 * pi / 360 / 60
35886 } // copy to the full names of the angles
35887
35888
35889 UNITS.radian.value = UNITS.rad.value;
35890 UNITS.degree.value = UNITS.deg.value;
35891 UNITS.gradian.value = UNITS.grad.value;
35892 } // apply the angle values now
35893
35894
35895 calculateAngleValues(config);
35896
35897 if (on) {
35898 // recalculate the values on change of configuration
35899 on('config', function (curr, prev) {
35900 if (curr.number !== prev.number) {
35901 calculateAngleValues(curr);
35902 }
35903 });
35904 }
35905 /**
35906 * A unit system is a set of dimensionally independent base units plus a set of derived units, formed by multiplication and division of the base units, that are by convention used with the unit system.
35907 * A user perhaps could issue a command to select a preferred unit system, or use the default (see below).
35908 * Auto unit system: The default unit system is updated on the fly anytime a unit is parsed. The corresponding unit in the default unit system is updated, so that answers are given in the same units the user supplies.
35909 */
35910
35911
35912 var UNIT_SYSTEMS = {
35913 si: {
35914 // Base units
35915 NONE: {
35916 unit: UNIT_NONE,
35917 prefix: PREFIXES.NONE['']
35918 },
35919 LENGTH: {
35920 unit: UNITS.m,
35921 prefix: PREFIXES.SHORT['']
35922 },
35923 MASS: {
35924 unit: UNITS.g,
35925 prefix: PREFIXES.SHORT.k
35926 },
35927 TIME: {
35928 unit: UNITS.s,
35929 prefix: PREFIXES.SHORT['']
35930 },
35931 CURRENT: {
35932 unit: UNITS.A,
35933 prefix: PREFIXES.SHORT['']
35934 },
35935 TEMPERATURE: {
35936 unit: UNITS.K,
35937 prefix: PREFIXES.SHORT['']
35938 },
35939 LUMINOUS_INTENSITY: {
35940 unit: UNITS.cd,
35941 prefix: PREFIXES.SHORT['']
35942 },
35943 AMOUNT_OF_SUBSTANCE: {
35944 unit: UNITS.mol,
35945 prefix: PREFIXES.SHORT['']
35946 },
35947 ANGLE: {
35948 unit: UNITS.rad,
35949 prefix: PREFIXES.SHORT['']
35950 },
35951 BIT: {
35952 unit: UNITS.bits,
35953 prefix: PREFIXES.SHORT['']
35954 },
35955 // Derived units
35956 FORCE: {
35957 unit: UNITS.N,
35958 prefix: PREFIXES.SHORT['']
35959 },
35960 ENERGY: {
35961 unit: UNITS.J,
35962 prefix: PREFIXES.SHORT['']
35963 },
35964 POWER: {
35965 unit: UNITS.W,
35966 prefix: PREFIXES.SHORT['']
35967 },
35968 PRESSURE: {
35969 unit: UNITS.Pa,
35970 prefix: PREFIXES.SHORT['']
35971 },
35972 ELECTRIC_CHARGE: {
35973 unit: UNITS.C,
35974 prefix: PREFIXES.SHORT['']
35975 },
35976 ELECTRIC_CAPACITANCE: {
35977 unit: UNITS.F,
35978 prefix: PREFIXES.SHORT['']
35979 },
35980 ELECTRIC_POTENTIAL: {
35981 unit: UNITS.V,
35982 prefix: PREFIXES.SHORT['']
35983 },
35984 ELECTRIC_RESISTANCE: {
35985 unit: UNITS.ohm,
35986 prefix: PREFIXES.SHORT['']
35987 },
35988 ELECTRIC_INDUCTANCE: {
35989 unit: UNITS.H,
35990 prefix: PREFIXES.SHORT['']
35991 },
35992 ELECTRIC_CONDUCTANCE: {
35993 unit: UNITS.S,
35994 prefix: PREFIXES.SHORT['']
35995 },
35996 MAGNETIC_FLUX: {
35997 unit: UNITS.Wb,
35998 prefix: PREFIXES.SHORT['']
35999 },
36000 MAGNETIC_FLUX_DENSITY: {
36001 unit: UNITS.T,
36002 prefix: PREFIXES.SHORT['']
36003 },
36004 FREQUENCY: {
36005 unit: UNITS.Hz,
36006 prefix: PREFIXES.SHORT['']
36007 }
36008 }
36009 }; // Clone to create the other unit systems
36010
36011 UNIT_SYSTEMS.cgs = JSON.parse(JSON.stringify(UNIT_SYSTEMS.si));
36012 UNIT_SYSTEMS.cgs.LENGTH = {
36013 unit: UNITS.m,
36014 prefix: PREFIXES.SHORT.c
36015 };
36016 UNIT_SYSTEMS.cgs.MASS = {
36017 unit: UNITS.g,
36018 prefix: PREFIXES.SHORT['']
36019 };
36020 UNIT_SYSTEMS.cgs.FORCE = {
36021 unit: UNITS.dyn,
36022 prefix: PREFIXES.SHORT['']
36023 };
36024 UNIT_SYSTEMS.cgs.ENERGY = {
36025 unit: UNITS.erg,
36026 prefix: PREFIXES.NONE['']
36027 }; // there are wholly 4 unique cgs systems for electricity and magnetism,
36028 // so let's not worry about it unless somebody complains
36029
36030 UNIT_SYSTEMS.us = JSON.parse(JSON.stringify(UNIT_SYSTEMS.si));
36031 UNIT_SYSTEMS.us.LENGTH = {
36032 unit: UNITS.ft,
36033 prefix: PREFIXES.NONE['']
36034 };
36035 UNIT_SYSTEMS.us.MASS = {
36036 unit: UNITS.lbm,
36037 prefix: PREFIXES.NONE['']
36038 };
36039 UNIT_SYSTEMS.us.TEMPERATURE = {
36040 unit: UNITS.degF,
36041 prefix: PREFIXES.NONE['']
36042 };
36043 UNIT_SYSTEMS.us.FORCE = {
36044 unit: UNITS.lbf,
36045 prefix: PREFIXES.NONE['']
36046 };
36047 UNIT_SYSTEMS.us.ENERGY = {
36048 unit: UNITS.BTU,
36049 prefix: PREFIXES.BTU['']
36050 };
36051 UNIT_SYSTEMS.us.POWER = {
36052 unit: UNITS.hp,
36053 prefix: PREFIXES.NONE['']
36054 };
36055 UNIT_SYSTEMS.us.PRESSURE = {
36056 unit: UNITS.psi,
36057 prefix: PREFIXES.NONE['']
36058 }; // Add additional unit systems here.
36059 // Choose a unit system to seed the auto unit system.
36060
36061 UNIT_SYSTEMS.auto = JSON.parse(JSON.stringify(UNIT_SYSTEMS.si)); // Set the current unit system
36062
36063 var currentUnitSystem = UNIT_SYSTEMS.auto;
36064 /**
36065 * Set a unit system for formatting derived units.
36066 * @param {string} [name] The name of the unit system.
36067 */
36068
36069 Unit.setUnitSystem = function (name) {
36070 if (Object(utils_object["f" /* hasOwnProperty */])(UNIT_SYSTEMS, name)) {
36071 currentUnitSystem = UNIT_SYSTEMS[name];
36072 } else {
36073 throw new Error('Unit system ' + name + ' does not exist. Choices are: ' + Object.keys(UNIT_SYSTEMS).join(', '));
36074 }
36075 };
36076 /**
36077 * Return the current unit system.
36078 * @return {string} The current unit system.
36079 */
36080
36081
36082 Unit.getUnitSystem = function () {
36083 for (var _key in UNIT_SYSTEMS) {
36084 if (UNIT_SYSTEMS[_key] === currentUnitSystem) {
36085 return _key;
36086 }
36087 }
36088 };
36089 /**
36090 * Converters to convert from number to an other numeric type like BigNumber
36091 * or Fraction
36092 */
36093
36094
36095 Unit.typeConverters = {
36096 BigNumber: function BigNumber(x) {
36097 return new _BigNumber(x + ''); // stringify to prevent constructor error
36098 },
36099 Fraction: function Fraction(x) {
36100 return new _Fraction(x);
36101 },
36102 Complex: function Complex(x) {
36103 return x;
36104 },
36105 number: function number(x) {
36106 return x;
36107 }
36108 };
36109 /**
36110 * Retrieve the right convertor function corresponding with the type
36111 * of provided exampleValue.
36112 *
36113 * @param {string} type A string 'number', 'BigNumber', or 'Fraction'
36114 * In case of an unknown type,
36115 * @return {Function}
36116 */
36117
36118 Unit._getNumberConverter = function (type) {
36119 if (!Unit.typeConverters[type]) {
36120 throw new TypeError('Unsupported type "' + type + '"');
36121 }
36122
36123 return Unit.typeConverters[type];
36124 }; // Add dimensions to each built-in unit
36125
36126
36127 for (var _key2 in UNITS) {
36128 var unit = UNITS[_key2];
36129 unit.dimensions = unit.base.dimensions;
36130 } // Create aliases
36131
36132
36133 for (var _name2 in ALIASES) {
36134 if (Object(utils_object["f" /* hasOwnProperty */])(ALIASES, _name2)) {
36135 var _unit2 = UNITS[ALIASES[_name2]];
36136 var alias = {};
36137
36138 for (var _key3 in _unit2) {
36139 if (Object(utils_object["f" /* hasOwnProperty */])(_unit2, _key3)) {
36140 alias[_key3] = _unit2[_key3];
36141 }
36142 }
36143
36144 alias.name = _name2;
36145 UNITS[_name2] = alias;
36146 }
36147 }
36148
36149 function assertUnitNameIsValid(name) {
36150 for (var i = 0; i < name.length; i++) {
36151 var _c = name.charAt(i);
36152
36153 var isValidAlpha = function isValidAlpha(p) {
36154 return /^[a-zA-Z]$/.test(p);
36155 };
36156
36157 var _isDigit = function _isDigit(c) {
36158 return c >= '0' && c <= '9';
36159 };
36160
36161 if (i === 0 && !isValidAlpha(_c)) {
36162 throw new Error('Invalid unit name (must begin with alpha character): "' + name + '"');
36163 }
36164
36165 if (i > 0 && !(isValidAlpha(_c) || _isDigit(_c))) {
36166 throw new Error('Invalid unit name (only alphanumeric characters are allowed): "' + name + '"');
36167 }
36168 }
36169 }
36170 /**
36171 * Wrapper around createUnitSingle.
36172 * Example:
36173 * createUnit({
36174 * foo: { },
36175 * bar: {
36176 * definition: 'kg/foo',
36177 * aliases: ['ba', 'barr', 'bars'],
36178 * offset: 200
36179 * },
36180 * baz: '4 bar'
36181 * },
36182 * {
36183 * override: true
36184 * })
36185 * @param {object} obj Object map. Each key becomes a unit which is defined by its value.
36186 * @param {object} options
36187 */
36188
36189
36190 Unit.createUnit = function (obj, options) {
36191 if (Unit_typeof(obj) !== 'object') {
36192 throw new TypeError("createUnit expects first parameter to be of type 'Object'");
36193 } // Remove all units and aliases we are overriding
36194
36195
36196 if (options && options.override) {
36197 for (var _key4 in obj) {
36198 if (Object(utils_object["f" /* hasOwnProperty */])(obj, _key4)) {
36199 Unit.deleteUnit(_key4);
36200 }
36201
36202 if (obj[_key4].aliases) {
36203 for (var i = 0; i < obj[_key4].aliases.length; i++) {
36204 Unit.deleteUnit(obj[_key4].aliases[i]);
36205 }
36206 }
36207 }
36208 } // TODO: traverse multiple times until all units have been added
36209
36210
36211 var lastUnit;
36212
36213 for (var _key5 in obj) {
36214 if (Object(utils_object["f" /* hasOwnProperty */])(obj, _key5)) {
36215 lastUnit = Unit.createUnitSingle(_key5, obj[_key5]);
36216 }
36217 }
36218
36219 return lastUnit;
36220 };
36221 /**
36222 * Create a user-defined unit and register it with the Unit type.
36223 * Example:
36224 * createUnitSingle('knot', '0.514444444 m/s')
36225 * createUnitSingle('acre', new Unit(43560, 'ft^2'))
36226 *
36227 * @param {string} name The name of the new unit. Must be unique. Example: 'knot'
36228 * @param {string, Unit} definition Definition of the unit in terms of existing units. For example, '0.514444444 m / s'.
36229 * @param {Object} options (optional) An object containing any of the following properties:
36230 * prefixes {string} "none", "short", "long", "binary_short", or "binary_long". The default is "none".
36231 * aliases {Array} Array of strings. Example: ['knots', 'kt', 'kts']
36232 * offset {Numeric} An offset to apply when converting from the unit. For example, the offset for celsius is 273.15 and the offset for farhenheit is 459.67. Default is 0.
36233 *
36234 * @return {Unit}
36235 */
36236
36237
36238 Unit.createUnitSingle = function (name, obj, options) {
36239 if (typeof obj === 'undefined' || obj === null) {
36240 obj = {};
36241 }
36242
36243 if (typeof name !== 'string') {
36244 throw new TypeError("createUnitSingle expects first parameter to be of type 'string'");
36245 } // Check collisions with existing units
36246
36247
36248 if (Object(utils_object["f" /* hasOwnProperty */])(UNITS, name)) {
36249 throw new Error('Cannot create unit "' + name + '": a unit with that name already exists');
36250 } // TODO: Validate name for collisions with other built-in functions (like abs or cos, for example), and for acceptable variable names. For example, '42' is probably not a valid unit. Nor is '%', since it is also an operator.
36251
36252
36253 assertUnitNameIsValid(name);
36254 var defUnit = null; // The Unit from which the new unit will be created.
36255
36256 var aliases = [];
36257 var offset = 0;
36258 var definition;
36259 var prefixes;
36260
36261 if (obj && obj.type === 'Unit') {
36262 defUnit = obj.clone();
36263 } else if (typeof obj === 'string') {
36264 if (obj !== '') {
36265 definition = obj;
36266 }
36267 } else if (Unit_typeof(obj) === 'object') {
36268 definition = obj.definition;
36269 prefixes = obj.prefixes;
36270 offset = obj.offset;
36271
36272 if (obj.aliases) {
36273 aliases = obj.aliases.valueOf(); // aliases could be a Matrix, so convert to Array
36274 }
36275 } else {
36276 throw new TypeError('Cannot create unit "' + name + '" from "' + obj.toString() + '": expecting "string" or "Unit" or "Object"');
36277 }
36278
36279 if (aliases) {
36280 for (var i = 0; i < aliases.length; i++) {
36281 if (Object(utils_object["f" /* hasOwnProperty */])(UNITS, aliases[i])) {
36282 throw new Error('Cannot create alias "' + aliases[i] + '": a unit with that name already exists');
36283 }
36284 }
36285 }
36286
36287 if (definition && typeof definition === 'string' && !defUnit) {
36288 try {
36289 defUnit = Unit.parse(definition, {
36290 allowNoUnits: true
36291 });
36292 } catch (ex) {
36293 ex.message = 'Could not create unit "' + name + '" from "' + definition + '": ' + ex.message;
36294 throw ex;
36295 }
36296 } else if (definition && definition.type === 'Unit') {
36297 defUnit = definition.clone();
36298 }
36299
36300 aliases = aliases || [];
36301 offset = offset || 0;
36302
36303 if (prefixes && prefixes.toUpperCase) {
36304 prefixes = PREFIXES[prefixes.toUpperCase()] || PREFIXES.NONE;
36305 } else {
36306 prefixes = PREFIXES.NONE;
36307 } // If defUnit is null, it is because the user did not
36308 // specify a defintion. So create a new base dimension.
36309
36310
36311 var newUnit = {};
36312
36313 if (!defUnit) {
36314 // Add a new base dimension
36315 var baseName = name + '_STUFF'; // foo --> foo_STUFF, or the essence of foo
36316
36317 if (BASE_DIMENSIONS.indexOf(baseName) >= 0) {
36318 throw new Error('Cannot create new base unit "' + name + '": a base unit with that name already exists (and cannot be overridden)');
36319 }
36320
36321 BASE_DIMENSIONS.push(baseName); // Push 0 onto existing base units
36322
36323 for (var b in BASE_UNITS) {
36324 if (Object(utils_object["f" /* hasOwnProperty */])(BASE_UNITS, b)) {
36325 BASE_UNITS[b].dimensions[BASE_DIMENSIONS.length - 1] = 0;
36326 }
36327 } // Add the new base unit
36328
36329
36330 var newBaseUnit = {
36331 dimensions: []
36332 };
36333
36334 for (var _i6 = 0; _i6 < BASE_DIMENSIONS.length; _i6++) {
36335 newBaseUnit.dimensions[_i6] = 0;
36336 }
36337
36338 newBaseUnit.dimensions[BASE_DIMENSIONS.length - 1] = 1;
36339 newBaseUnit.key = baseName;
36340 BASE_UNITS[baseName] = newBaseUnit;
36341 newUnit = {
36342 name: name,
36343 value: 1,
36344 dimensions: BASE_UNITS[baseName].dimensions.slice(0),
36345 prefixes: prefixes,
36346 offset: offset,
36347 base: BASE_UNITS[baseName]
36348 };
36349 currentUnitSystem[baseName] = {
36350 unit: newUnit,
36351 prefix: PREFIXES.NONE['']
36352 };
36353 } else {
36354 newUnit = {
36355 name: name,
36356 value: defUnit.value,
36357 dimensions: defUnit.dimensions.slice(0),
36358 prefixes: prefixes,
36359 offset: offset
36360 }; // Create a new base if no matching base exists
36361
36362 var anyMatch = false;
36363
36364 for (var _i7 in BASE_UNITS) {
36365 if (Object(utils_object["f" /* hasOwnProperty */])(BASE_UNITS, _i7)) {
36366 var match = true;
36367
36368 for (var j = 0; j < BASE_DIMENSIONS.length; j++) {
36369 if (Math.abs((newUnit.dimensions[j] || 0) - (BASE_UNITS[_i7].dimensions[j] || 0)) > 1e-12) {
36370 match = false;
36371 break;
36372 }
36373 }
36374
36375 if (match) {
36376 anyMatch = true;
36377 newUnit.base = BASE_UNITS[_i7];
36378 break;
36379 }
36380 }
36381 }
36382
36383 if (!anyMatch) {
36384 var _baseName = name + '_STUFF'; // foo --> foo_STUFF, or the essence of foo
36385 // Add the new base unit
36386
36387
36388 var _newBaseUnit = {
36389 dimensions: defUnit.dimensions.slice(0)
36390 };
36391 _newBaseUnit.key = _baseName;
36392 BASE_UNITS[_baseName] = _newBaseUnit;
36393 currentUnitSystem[_baseName] = {
36394 unit: newUnit,
36395 prefix: PREFIXES.NONE['']
36396 };
36397 newUnit.base = BASE_UNITS[_baseName];
36398 }
36399 }
36400
36401 Unit.UNITS[name] = newUnit;
36402
36403 for (var _i8 = 0; _i8 < aliases.length; _i8++) {
36404 var aliasName = aliases[_i8];
36405 var _alias = {};
36406
36407 for (var _key6 in newUnit) {
36408 if (Object(utils_object["f" /* hasOwnProperty */])(newUnit, _key6)) {
36409 _alias[_key6] = newUnit[_key6];
36410 }
36411 }
36412
36413 _alias.name = aliasName;
36414 Unit.UNITS[aliasName] = _alias;
36415 }
36416
36417 return new Unit(null, name);
36418 };
36419
36420 Unit.deleteUnit = function (name) {
36421 delete Unit.UNITS[name];
36422 }; // expose arrays with prefixes, dimensions, units, systems
36423
36424
36425 Unit.PREFIXES = PREFIXES;
36426 Unit.BASE_DIMENSIONS = BASE_DIMENSIONS;
36427 Unit.BASE_UNITS = BASE_UNITS;
36428 Unit.UNIT_SYSTEMS = UNIT_SYSTEMS;
36429 Unit.UNITS = UNITS;
36430 return Unit;
36431}, {
36432 isClass: true
36433});
36434// CONCATENATED MODULE: ./src/type/unit/function/unit.js
36435
36436
36437var unit_name = 'unit';
36438var unit_dependencies = ['typed', 'Unit']; // This function is named createUnitFunction to prevent a naming conflict with createUnit
36439
36440var createUnitFunction =
36441/* #__PURE__ */
36442Object(factory["a" /* factory */])(unit_name, unit_dependencies, function (_ref) {
36443 var typed = _ref.typed,
36444 Unit = _ref.Unit;
36445
36446 /**
36447 * Create a unit. Depending on the passed arguments, the function
36448 * will create and return a new math.Unit object.
36449 * When a matrix is provided, all elements will be converted to units.
36450 *
36451 * Syntax:
36452 *
36453 * math.unit(unit : string)
36454 * math.unit(value : number, unit : string)
36455 *
36456 * Examples:
36457 *
36458 * const a = math.unit(5, 'cm') // returns Unit 50 mm
36459 * const b = math.unit('23 kg') // returns Unit 23 kg
36460 * a.to('m') // returns Unit 0.05 m
36461 *
36462 * See also:
36463 *
36464 * bignumber, boolean, complex, index, matrix, number, string, createUnit
36465 *
36466 * @param {* | Array | Matrix} args A number and unit.
36467 * @return {Unit | Array | Matrix} The created unit
36468 */
36469 var unit = typed(unit_name, {
36470 Unit: function Unit(x) {
36471 return x.clone();
36472 },
36473 string: function string(x) {
36474 if (Unit.isValuelessUnit(x)) {
36475 return new Unit(null, x); // a pure unit
36476 }
36477
36478 return Unit.parse(x, {
36479 allowNoUnits: true
36480 }); // a unit with value, like '5cm'
36481 },
36482 'number | BigNumber | Fraction | Complex, string': function numberBigNumberFractionComplexString(value, unit) {
36483 return new Unit(value, unit);
36484 },
36485 'Array | Matrix': function ArrayMatrix(x) {
36486 return deepMap(x, unit);
36487 }
36488 });
36489 return unit;
36490});
36491// CONCATENATED MODULE: ./src/type/matrix/function/sparse.js
36492
36493var sparse_name = 'sparse';
36494var sparse_dependencies = ['typed', 'SparseMatrix'];
36495var createSparse =
36496/* #__PURE__ */
36497Object(factory["a" /* factory */])(sparse_name, sparse_dependencies, function (_ref) {
36498 var typed = _ref.typed,
36499 SparseMatrix = _ref.SparseMatrix;
36500
36501 /**
36502 * Create a Sparse Matrix. The function creates a new `math.Matrix` object from
36503 * an `Array`. A Matrix has utility functions to manipulate the data in the
36504 * matrix, like getting the size and getting or setting values in the matrix.
36505 *
36506 * Syntax:
36507 *
36508 * math.sparse() // creates an empty sparse matrix.
36509 * math.sparse(data) // creates a sparse matrix with initial data.
36510 * math.sparse(data, 'number') // creates a sparse matrix with initial data, number datatype.
36511 *
36512 * Examples:
36513 *
36514 * let m = math.sparse([[1, 2], [3, 4]])
36515 * m.size() // Array [2, 2]
36516 * m.resize([3, 2], 5)
36517 * m.valueOf() // Array [[1, 2], [3, 4], [5, 5]]
36518 * m.get([1, 0]) // number 3
36519 *
36520 * See also:
36521 *
36522 * bignumber, boolean, complex, index, number, string, unit, matrix
36523 *
36524 * @param {Array | Matrix} [data] A two dimensional array
36525 *
36526 * @return {Matrix} The created matrix
36527 */
36528 return typed(sparse_name, {
36529 '': function _() {
36530 return new SparseMatrix([]);
36531 },
36532 string: function string(datatype) {
36533 return new SparseMatrix([], datatype);
36534 },
36535 'Array | Matrix': function ArrayMatrix(data) {
36536 return new SparseMatrix(data);
36537 },
36538 'Array | Matrix, string': function ArrayMatrixString(data, datatype) {
36539 return new SparseMatrix(data, datatype);
36540 }
36541 });
36542});
36543// CONCATENATED MODULE: ./src/type/unit/function/createUnit.js
36544
36545var createUnit_name = 'createUnit';
36546var createUnit_dependencies = ['typed', 'Unit'];
36547var createCreateUnit =
36548/* #__PURE__ */
36549Object(factory["a" /* factory */])(createUnit_name, createUnit_dependencies, function (_ref) {
36550 var typed = _ref.typed,
36551 Unit = _ref.Unit;
36552
36553 /**
36554 * Create a user-defined unit and register it with the Unit type.
36555 *
36556 * Syntax:
36557 *
36558 * math.createUnit({
36559 * baseUnit1: {
36560 * aliases: [string, ...]
36561 * prefixes: object
36562 * },
36563 * unit2: {
36564 * definition: string,
36565 * aliases: [string, ...]
36566 * prefixes: object,
36567 * offset: number
36568 * },
36569 * unit3: string // Shortcut
36570 * })
36571 *
36572 * // Another shortcut:
36573 * math.createUnit(string, unit : string, [object])
36574 *
36575 * Examples:
36576 *
36577 * math.createUnit('foo')
36578 * math.createUnit('knot', {definition: '0.514444444 m/s', aliases: ['knots', 'kt', 'kts']})
36579 * math.createUnit('mph', '1 mile/hour')
36580 *
36581 * @param {string} name The name of the new unit. Must be unique. Example: 'knot'
36582 * @param {string, Unit} definition Definition of the unit in terms of existing units. For example, '0.514444444 m / s'.
36583 * @param {Object} options (optional) An object containing any of the following properties:
36584 * - `prefixes {string}` "none", "short", "long", "binary_short", or "binary_long". The default is "none".
36585 * - `aliases {Array}` Array of strings. Example: ['knots', 'kt', 'kts']
36586 * - `offset {Numeric}` An offset to apply when converting from the unit. For example, the offset for celsius is 273.15. Default is 0.
36587 *
36588 * See also:
36589 *
36590 * unit
36591 *
36592 * @return {Unit} The new unit
36593 */
36594 return typed(createUnit_name, {
36595 // General function signature. First parameter is an object where each property is the definition of a new unit. The object keys are the unit names and the values are the definitions. The values can be objects, strings, or Units. If a property is an empty object or an empty string, a new base unit is created. The second parameter is the options.
36596 'Object, Object': function ObjectObject(obj, options) {
36597 return Unit.createUnit(obj, options);
36598 },
36599 // Same as above but without the options.
36600 Object: function Object(obj) {
36601 return Unit.createUnit(obj, {});
36602 },
36603 // Shortcut method for creating one unit.
36604 'string, Unit | string | Object, Object': function stringUnitStringObjectObject(name, def, options) {
36605 var obj = {};
36606 obj[name] = def;
36607 return Unit.createUnit(obj, options);
36608 },
36609 // Same as above but without the options.
36610 'string, Unit | string | Object': function stringUnitStringObject(name, def) {
36611 var obj = {};
36612 obj[name] = def;
36613 return Unit.createUnit(obj, {});
36614 },
36615 // Without a definition, creates a base unit.
36616 string: function string(name) {
36617 var obj = {};
36618 obj[name] = {};
36619 return Unit.createUnit(obj, {});
36620 }
36621 });
36622});
36623// CONCATENATED MODULE: ./src/function/trigonometry/acos.js
36624
36625
36626var acos_name = 'acos';
36627var acos_dependencies = ['typed', 'config', 'Complex'];
36628var createAcos =
36629/* #__PURE__ */
36630Object(factory["a" /* factory */])(acos_name, acos_dependencies, function (_ref) {
36631 var typed = _ref.typed,
36632 config = _ref.config,
36633 Complex = _ref.Complex;
36634
36635 /**
36636 * Calculate the inverse cosine of a value.
36637 *
36638 * For matrices, the function is evaluated element wise.
36639 *
36640 * Syntax:
36641 *
36642 * math.acos(x)
36643 *
36644 * Examples:
36645 *
36646 * math.acos(0.5) // returns number 1.0471975511965979
36647 * math.acos(math.cos(1.5)) // returns number 1.5
36648 *
36649 * math.acos(2) // returns Complex 0 + 1.3169578969248166 i
36650 *
36651 * See also:
36652 *
36653 * cos, atan, asin
36654 *
36655 * @param {number | BigNumber | Complex | Array | Matrix} x Function input
36656 * @return {number | BigNumber | Complex | Array | Matrix} The arc cosine of x
36657 */
36658 var acos = typed(acos_name, {
36659 number: function number(x) {
36660 if (x >= -1 && x <= 1 || config.predictable) {
36661 return Math.acos(x);
36662 } else {
36663 return new Complex(x, 0).acos();
36664 }
36665 },
36666 Complex: function Complex(x) {
36667 return x.acos();
36668 },
36669 BigNumber: function BigNumber(x) {
36670 return x.acos();
36671 },
36672 'Array | Matrix': function ArrayMatrix(x) {
36673 return deepMap(x, acos);
36674 }
36675 });
36676 return acos;
36677});
36678// CONCATENATED MODULE: ./src/plain/number/trigonometry.js
36679
36680var trigonometry_n1 = 'number';
36681var trigonometry_n2 = 'number, number';
36682function acosNumber(x) {
36683 return Math.acos(x);
36684}
36685acosNumber.signature = trigonometry_n1;
36686function acoshNumber(x) {
36687 return Object(utils_number["a" /* acosh */])(x);
36688}
36689acoshNumber.signature = trigonometry_n1;
36690function acotNumber(x) {
36691 return Math.atan(1 / x);
36692}
36693acotNumber.signature = trigonometry_n1;
36694function acothNumber(x) {
36695 return isFinite(x) ? (Math.log((x + 1) / x) + Math.log(x / (x - 1))) / 2 : 0;
36696}
36697acothNumber.signature = trigonometry_n1;
36698function acscNumber(x) {
36699 return Math.asin(1 / x);
36700}
36701acscNumber.signature = trigonometry_n1;
36702function acschNumber(x) {
36703 var xInv = 1 / x;
36704 return Math.log(xInv + Math.sqrt(xInv * xInv + 1));
36705}
36706acschNumber.signature = trigonometry_n1;
36707function asecNumber(x) {
36708 return Math.acos(1 / x);
36709}
36710asecNumber.signature = trigonometry_n1;
36711function asechNumber(x) {
36712 var xInv = 1 / x;
36713 var ret = Math.sqrt(xInv * xInv - 1);
36714 return Math.log(ret + xInv);
36715}
36716asechNumber.signature = trigonometry_n1;
36717function asinNumber(x) {
36718 return Math.asin(x);
36719}
36720asinNumber.signature = trigonometry_n1;
36721function asinhNumber(x) {
36722 return Object(utils_number["b" /* asinh */])(x);
36723}
36724asinhNumber.signature = trigonometry_n1;
36725function atanNumber(x) {
36726 return Math.atan(x);
36727}
36728atanNumber.signature = trigonometry_n1;
36729function atan2Number(y, x) {
36730 return Math.atan2(y, x);
36731}
36732atan2Number.signature = trigonometry_n2;
36733function atanhNumber(x) {
36734 return Object(utils_number["c" /* atanh */])(x);
36735}
36736atanhNumber.signature = trigonometry_n1;
36737function cosNumber(x) {
36738 return Math.cos(x);
36739}
36740cosNumber.signature = trigonometry_n1;
36741function coshNumber(x) {
36742 return Object(utils_number["e" /* cosh */])(x);
36743}
36744coshNumber.signature = trigonometry_n1;
36745function cotNumber(x) {
36746 return 1 / Math.tan(x);
36747}
36748cotNumber.signature = trigonometry_n1;
36749function cothNumber(x) {
36750 var e = Math.exp(2 * x);
36751 return (e + 1) / (e - 1);
36752}
36753cothNumber.signature = trigonometry_n1;
36754function cscNumber(x) {
36755 return 1 / Math.sin(x);
36756}
36757cscNumber.signature = trigonometry_n1;
36758function cschNumber(x) {
36759 // consider values close to zero (+/-)
36760 if (x === 0) {
36761 return Number.POSITIVE_INFINITY;
36762 } else {
36763 return Math.abs(2 / (Math.exp(x) - Math.exp(-x))) * Object(utils_number["n" /* sign */])(x);
36764 }
36765}
36766cschNumber.signature = trigonometry_n1;
36767function secNumber(x) {
36768 return 1 / Math.cos(x);
36769}
36770secNumber.signature = trigonometry_n1;
36771function sechNumber(x) {
36772 return 2 / (Math.exp(x) + Math.exp(-x));
36773}
36774sechNumber.signature = trigonometry_n1;
36775function sinNumber(x) {
36776 return Math.sin(x);
36777}
36778sinNumber.signature = trigonometry_n1;
36779function sinhNumber(x) {
36780 return Object(utils_number["o" /* sinh */])(x);
36781}
36782sinhNumber.signature = trigonometry_n1;
36783function tanNumber(x) {
36784 return Math.tan(x);
36785}
36786tanNumber.signature = trigonometry_n1;
36787function tanhNumber(x) {
36788 return Object(utils_number["p" /* tanh */])(x);
36789}
36790tanhNumber.signature = trigonometry_n1;
36791// CONCATENATED MODULE: ./src/function/trigonometry/acosh.js
36792
36793
36794
36795var acosh_name = 'acosh';
36796var acosh_dependencies = ['typed', 'config', 'Complex'];
36797var createAcosh =
36798/* #__PURE__ */
36799Object(factory["a" /* factory */])(acosh_name, acosh_dependencies, function (_ref) {
36800 var typed = _ref.typed,
36801 config = _ref.config,
36802 Complex = _ref.Complex;
36803
36804 /**
36805 * Calculate the hyperbolic arccos of a value,
36806 * defined as `acosh(x) = ln(sqrt(x^2 - 1) + x)`.
36807 *
36808 * For matrices, the function is evaluated element wise.
36809 *
36810 * Syntax:
36811 *
36812 * math.acosh(x)
36813 *
36814 * Examples:
36815 *
36816 * math.acosh(1.5) // returns 0.9624236501192069
36817 *
36818 * See also:
36819 *
36820 * cosh, asinh, atanh
36821 *
36822 * @param {number | Complex | Unit | Array | Matrix} x Function input
36823 * @return {number | Complex | Array | Matrix} Hyperbolic arccosine of x
36824 */
36825 var acosh = typed(acosh_name, {
36826 number: function number(x) {
36827 if (x >= 1 || config.predictable) {
36828 return acoshNumber(x);
36829 }
36830
36831 if (x <= -1) {
36832 return new Complex(Math.log(Math.sqrt(x * x - 1) - x), Math.PI);
36833 }
36834
36835 return new Complex(x, 0).acosh();
36836 },
36837 Complex: function Complex(x) {
36838 return x.acosh();
36839 },
36840 BigNumber: function BigNumber(x) {
36841 return x.acosh();
36842 },
36843 'Array | Matrix': function ArrayMatrix(x) {
36844 return deepMap(x, acosh);
36845 }
36846 });
36847 return acosh;
36848});
36849// CONCATENATED MODULE: ./src/function/trigonometry/acot.js
36850
36851
36852
36853var acot_name = 'acot';
36854var acot_dependencies = ['typed', 'BigNumber'];
36855var createAcot =
36856/* #__PURE__ */
36857Object(factory["a" /* factory */])(acot_name, acot_dependencies, function (_ref) {
36858 var typed = _ref.typed,
36859 _BigNumber = _ref.BigNumber;
36860
36861 /**
36862 * Calculate the inverse cotangent of a value, defined as `acot(x) = atan(1/x)`.
36863 *
36864 * For matrices, the function is evaluated element wise.
36865 *
36866 * Syntax:
36867 *
36868 * math.acot(x)
36869 *
36870 * Examples:
36871 *
36872 * math.acot(0.5) // returns number 0.4636476090008061
36873 * math.acot(math.cot(1.5)) // returns number 1.5
36874 *
36875 * math.acot(2) // returns Complex 1.5707963267948966 -1.3169578969248166 i
36876 *
36877 * See also:
36878 *
36879 * cot, atan
36880 *
36881 * @param {number | Complex | Array | Matrix} x Function input
36882 * @return {number | Complex | Array | Matrix} The arc cotangent of x
36883 */
36884 var acot = typed(acot_name, {
36885 number: acotNumber,
36886 Complex: function Complex(x) {
36887 return x.acot();
36888 },
36889 BigNumber: function BigNumber(x) {
36890 return new _BigNumber(1).div(x).atan();
36891 },
36892 'Array | Matrix': function ArrayMatrix(x) {
36893 return deepMap(x, acot);
36894 }
36895 });
36896 return acot;
36897});
36898// CONCATENATED MODULE: ./src/function/trigonometry/acoth.js
36899
36900
36901
36902var acoth_name = 'acoth';
36903var acoth_dependencies = ['typed', 'config', 'Complex', 'BigNumber'];
36904var createAcoth =
36905/* #__PURE__ */
36906Object(factory["a" /* factory */])(acoth_name, acoth_dependencies, function (_ref) {
36907 var typed = _ref.typed,
36908 config = _ref.config,
36909 Complex = _ref.Complex,
36910 _BigNumber = _ref.BigNumber;
36911
36912 /**
36913 * Calculate the hyperbolic arccotangent of a value,
36914 * defined as `acoth(x) = atanh(1/x) = (ln((x+1)/x) + ln(x/(x-1))) / 2`.
36915 *
36916 * For matrices, the function is evaluated element wise.
36917 *
36918 * Syntax:
36919 *
36920 * math.acoth(x)
36921 *
36922 * Examples:
36923 *
36924 * math.acoth(0.5) // returns 0.8047189562170503
36925 *
36926 * See also:
36927 *
36928 * acsch, asech
36929 *
36930 * @param {number | Complex | Array | Matrix} x Function input
36931 * @return {number | Complex | Array | Matrix} Hyperbolic arccotangent of x
36932 */
36933 var acoth = typed(acoth_name, {
36934 number: function number(x) {
36935 if (x >= 1 || x <= -1 || config.predictable) {
36936 return acothNumber(x);
36937 }
36938
36939 return new Complex(x, 0).acoth();
36940 },
36941 Complex: function Complex(x) {
36942 return x.acoth();
36943 },
36944 BigNumber: function BigNumber(x) {
36945 return new _BigNumber(1).div(x).atanh();
36946 },
36947 'Array | Matrix': function ArrayMatrix(x) {
36948 return deepMap(x, acoth);
36949 }
36950 });
36951 return acoth;
36952});
36953// CONCATENATED MODULE: ./src/function/trigonometry/acsc.js
36954
36955
36956
36957var acsc_name = 'acsc';
36958var acsc_dependencies = ['typed', 'config', 'Complex', 'BigNumber'];
36959var createAcsc =
36960/* #__PURE__ */
36961Object(factory["a" /* factory */])(acsc_name, acsc_dependencies, function (_ref) {
36962 var typed = _ref.typed,
36963 config = _ref.config,
36964 Complex = _ref.Complex,
36965 _BigNumber = _ref.BigNumber;
36966
36967 /**
36968 * Calculate the inverse cosecant of a value, defined as `acsc(x) = asin(1/x)`.
36969 *
36970 * For matrices, the function is evaluated element wise.
36971 *
36972 * Syntax:
36973 *
36974 * math.acsc(x)
36975 *
36976 * Examples:
36977 *
36978 * math.acsc(0.5) // returns number 0.5235987755982989
36979 * math.acsc(math.csc(1.5)) // returns number ~1.5
36980 *
36981 * math.acsc(2) // returns Complex 1.5707963267948966 -1.3169578969248166 i
36982 *
36983 * See also:
36984 *
36985 * csc, asin, asec
36986 *
36987 * @param {number | Complex | Array | Matrix} x Function input
36988 * @return {number | Complex | Array | Matrix} The arc cosecant of x
36989 */
36990 var acsc = typed(acsc_name, {
36991 number: function number(x) {
36992 if (x <= -1 || x >= 1 || config.predictable) {
36993 return acscNumber(x);
36994 }
36995
36996 return new Complex(x, 0).acsc();
36997 },
36998 Complex: function Complex(x) {
36999 return x.acsc();
37000 },
37001 BigNumber: function BigNumber(x) {
37002 return new _BigNumber(1).div(x).asin();
37003 },
37004 'Array | Matrix': function ArrayMatrix(x) {
37005 return deepMap(x, acsc);
37006 }
37007 });
37008 return acsc;
37009});
37010// CONCATENATED MODULE: ./src/function/trigonometry/acsch.js
37011
37012
37013
37014var acsch_name = 'acsch';
37015var acsch_dependencies = ['typed', 'BigNumber'];
37016var createAcsch =
37017/* #__PURE__ */
37018Object(factory["a" /* factory */])(acsch_name, acsch_dependencies, function (_ref) {
37019 var typed = _ref.typed,
37020 _BigNumber = _ref.BigNumber;
37021
37022 /**
37023 * Calculate the hyperbolic arccosecant of a value,
37024 * defined as `acsch(x) = asinh(1/x) = ln(1/x + sqrt(1/x^2 + 1))`.
37025 *
37026 * For matrices, the function is evaluated element wise.
37027 *
37028 * Syntax:
37029 *
37030 * math.acsch(x)
37031 *
37032 * Examples:
37033 *
37034 * math.acsch(0.5) // returns 1.4436354751788103
37035 *
37036 * See also:
37037 *
37038 * asech, acoth
37039 *
37040 * @param {number | Complex | Array | Matrix} x Function input
37041 * @return {number | Complex | Array | Matrix} Hyperbolic arccosecant of x
37042 */
37043 var acsch = typed(acsch_name, {
37044 number: acschNumber,
37045 Complex: function Complex(x) {
37046 return x.acsch();
37047 },
37048 BigNumber: function BigNumber(x) {
37049 return new _BigNumber(1).div(x).asinh();
37050 },
37051 'Array | Matrix': function ArrayMatrix(x) {
37052 return deepMap(x, acsch);
37053 }
37054 });
37055 return acsch;
37056});
37057// CONCATENATED MODULE: ./src/function/trigonometry/asec.js
37058
37059
37060
37061var asec_name = 'asec';
37062var asec_dependencies = ['typed', 'config', 'Complex', 'BigNumber'];
37063var createAsec =
37064/* #__PURE__ */
37065Object(factory["a" /* factory */])(asec_name, asec_dependencies, function (_ref) {
37066 var typed = _ref.typed,
37067 config = _ref.config,
37068 Complex = _ref.Complex,
37069 _BigNumber = _ref.BigNumber;
37070
37071 /**
37072 * Calculate the inverse secant of a value. Defined as `asec(x) = acos(1/x)`.
37073 *
37074 * For matrices, the function is evaluated element wise.
37075 *
37076 * Syntax:
37077 *
37078 * math.asec(x)
37079 *
37080 * Examples:
37081 *
37082 * math.asec(0.5) // returns 1.0471975511965979
37083 * math.asec(math.sec(1.5)) // returns 1.5
37084 *
37085 * math.asec(2) // returns 0 + 1.3169578969248166 i
37086 *
37087 * See also:
37088 *
37089 * acos, acot, acsc
37090 *
37091 * @param {number | Complex | Array | Matrix} x Function input
37092 * @return {number | Complex | Array | Matrix} The arc secant of x
37093 */
37094 var asec = typed(asec_name, {
37095 number: function number(x) {
37096 if (x <= -1 || x >= 1 || config.predictable) {
37097 return asecNumber(x);
37098 }
37099
37100 return new Complex(x, 0).asec();
37101 },
37102 Complex: function Complex(x) {
37103 return x.asec();
37104 },
37105 BigNumber: function BigNumber(x) {
37106 return new _BigNumber(1).div(x).acos();
37107 },
37108 'Array | Matrix': function ArrayMatrix(x) {
37109 return deepMap(x, asec);
37110 }
37111 });
37112 return asec;
37113});
37114// CONCATENATED MODULE: ./src/function/trigonometry/asech.js
37115
37116
37117
37118var asech_name = 'asech';
37119var asech_dependencies = ['typed', 'config', 'Complex', 'BigNumber'];
37120var createAsech =
37121/* #__PURE__ */
37122Object(factory["a" /* factory */])(asech_name, asech_dependencies, function (_ref) {
37123 var typed = _ref.typed,
37124 config = _ref.config,
37125 Complex = _ref.Complex,
37126 _BigNumber = _ref.BigNumber;
37127
37128 /**
37129 * Calculate the hyperbolic arcsecant of a value,
37130 * defined as `asech(x) = acosh(1/x) = ln(sqrt(1/x^2 - 1) + 1/x)`.
37131 *
37132 * For matrices, the function is evaluated element wise.
37133 *
37134 * Syntax:
37135 *
37136 * math.asech(x)
37137 *
37138 * Examples:
37139 *
37140 * math.asech(0.5) // returns 1.3169578969248166
37141 *
37142 * See also:
37143 *
37144 * acsch, acoth
37145 *
37146 * @param {number | Complex | Array | Matrix} x Function input
37147 * @return {number | Complex | Array | Matrix} Hyperbolic arcsecant of x
37148 */
37149 var asech = typed(asech_name, {
37150 number: function number(x) {
37151 if (x <= 1 && x >= -1 || config.predictable) {
37152 var xInv = 1 / x;
37153
37154 if (xInv > 0 || config.predictable) {
37155 return asechNumber(x);
37156 }
37157
37158 var ret = Math.sqrt(xInv * xInv - 1);
37159 return new Complex(Math.log(ret - xInv), Math.PI);
37160 }
37161
37162 return new Complex(x, 0).asech();
37163 },
37164 Complex: function Complex(x) {
37165 return x.asech();
37166 },
37167 BigNumber: function BigNumber(x) {
37168 return new _BigNumber(1).div(x).acosh();
37169 },
37170 'Array | Matrix': function ArrayMatrix(x) {
37171 return deepMap(x, asech);
37172 }
37173 });
37174 return asech;
37175});
37176// CONCATENATED MODULE: ./src/function/trigonometry/asin.js
37177
37178
37179var asin_name = 'asin';
37180var asin_dependencies = ['typed', 'config', 'Complex'];
37181var createAsin =
37182/* #__PURE__ */
37183Object(factory["a" /* factory */])(asin_name, asin_dependencies, function (_ref) {
37184 var typed = _ref.typed,
37185 config = _ref.config,
37186 Complex = _ref.Complex;
37187
37188 /**
37189 * Calculate the inverse sine of a value.
37190 *
37191 * For matrices, the function is evaluated element wise.
37192 *
37193 * Syntax:
37194 *
37195 * math.asin(x)
37196 *
37197 * Examples:
37198 *
37199 * math.asin(0.5) // returns number 0.5235987755982989
37200 * math.asin(math.sin(1.5)) // returns number ~1.5
37201 *
37202 * math.asin(2) // returns Complex 1.5707963267948966 -1.3169578969248166 i
37203 *
37204 * See also:
37205 *
37206 * sin, atan, acos
37207 *
37208 * @param {number | BigNumber | Complex | Array | Matrix} x Function input
37209 * @return {number | BigNumber | Complex | Array | Matrix} The arc sine of x
37210 */
37211 var asin = typed(asin_name, {
37212 number: function number(x) {
37213 if (x >= -1 && x <= 1 || config.predictable) {
37214 return Math.asin(x);
37215 } else {
37216 return new Complex(x, 0).asin();
37217 }
37218 },
37219 Complex: function Complex(x) {
37220 return x.asin();
37221 },
37222 BigNumber: function BigNumber(x) {
37223 return x.asin();
37224 },
37225 'Array | Matrix': function ArrayMatrix(x) {
37226 // deep map collection, skip zeros since asin(0) = 0
37227 return deepMap(x, asin, true);
37228 }
37229 });
37230 return asin;
37231});
37232// CONCATENATED MODULE: ./src/function/trigonometry/asinh.js
37233
37234
37235
37236var asinh_name = 'asinh';
37237var asinh_dependencies = ['typed'];
37238var createAsinh =
37239/* #__PURE__ */
37240Object(factory["a" /* factory */])(asinh_name, asinh_dependencies, function (_ref) {
37241 var typed = _ref.typed;
37242
37243 /**
37244 * Calculate the hyperbolic arcsine of a value,
37245 * defined as `asinh(x) = ln(x + sqrt(x^2 + 1))`.
37246 *
37247 * For matrices, the function is evaluated element wise.
37248 *
37249 * Syntax:
37250 *
37251 * math.asinh(x)
37252 *
37253 * Examples:
37254 *
37255 * math.asinh(0.5) // returns 0.48121182505960347
37256 *
37257 * See also:
37258 *
37259 * acosh, atanh
37260 *
37261 * @param {number | Complex | Array | Matrix} x Function input
37262 * @return {number | Complex | Array | Matrix} Hyperbolic arcsine of x
37263 */
37264 var asinh = typed('asinh', {
37265 number: asinhNumber,
37266 Complex: function Complex(x) {
37267 return x.asinh();
37268 },
37269 BigNumber: function BigNumber(x) {
37270 return x.asinh();
37271 },
37272 'Array | Matrix': function ArrayMatrix(x) {
37273 // deep map collection, skip zeros since asinh(0) = 0
37274 return deepMap(x, asinh, true);
37275 }
37276 });
37277 return asinh;
37278});
37279// CONCATENATED MODULE: ./src/function/trigonometry/atan.js
37280
37281
37282var atan_name = 'atan';
37283var atan_dependencies = ['typed'];
37284var createAtan =
37285/* #__PURE__ */
37286Object(factory["a" /* factory */])(atan_name, atan_dependencies, function (_ref) {
37287 var typed = _ref.typed;
37288
37289 /**
37290 * Calculate the inverse tangent of a value.
37291 *
37292 * For matrices, the function is evaluated element wise.
37293 *
37294 * Syntax:
37295 *
37296 * math.atan(x)
37297 *
37298 * Examples:
37299 *
37300 * math.atan(0.5) // returns number 0.4636476090008061
37301 * math.atan(math.tan(1.5)) // returns number 1.5
37302 *
37303 * math.atan(2) // returns Complex 1.5707963267948966 -1.3169578969248166 i
37304 *
37305 * See also:
37306 *
37307 * tan, asin, acos
37308 *
37309 * @param {number | BigNumber | Complex | Array | Matrix} x Function input
37310 * @return {number | BigNumber | Complex | Array | Matrix} The arc tangent of x
37311 */
37312 var atan = typed('atan', {
37313 number: function number(x) {
37314 return Math.atan(x);
37315 },
37316 Complex: function Complex(x) {
37317 return x.atan();
37318 },
37319 BigNumber: function BigNumber(x) {
37320 return x.atan();
37321 },
37322 'Array | Matrix': function ArrayMatrix(x) {
37323 // deep map collection, skip zeros since atan(0) = 0
37324 return deepMap(x, atan, true);
37325 }
37326 });
37327 return atan;
37328});
37329// CONCATENATED MODULE: ./src/function/trigonometry/atan2.js
37330
37331
37332
37333
37334
37335
37336
37337
37338var atan2_name = 'atan2';
37339var atan2_dependencies = ['typed', 'matrix', 'equalScalar', 'BigNumber', 'DenseMatrix'];
37340var createAtan2 =
37341/* #__PURE__ */
37342Object(factory["a" /* factory */])(atan2_name, atan2_dependencies, function (_ref) {
37343 var typed = _ref.typed,
37344 matrix = _ref.matrix,
37345 equalScalar = _ref.equalScalar,
37346 BigNumber = _ref.BigNumber,
37347 DenseMatrix = _ref.DenseMatrix;
37348 var algorithm02 = createAlgorithm02({
37349 typed: typed,
37350 equalScalar: equalScalar
37351 });
37352 var algorithm03 = createAlgorithm03({
37353 typed: typed
37354 });
37355 var algorithm09 = createAlgorithm09({
37356 typed: typed,
37357 equalScalar: equalScalar
37358 });
37359 var algorithm11 = createAlgorithm11({
37360 typed: typed,
37361 equalScalar: equalScalar
37362 });
37363 var algorithm12 = createAlgorithm12({
37364 typed: typed,
37365 DenseMatrix: DenseMatrix
37366 });
37367 var algorithm13 = createAlgorithm13({
37368 typed: typed
37369 });
37370 var algorithm14 = createAlgorithm14({
37371 typed: typed
37372 });
37373 /**
37374 * Calculate the inverse tangent function with two arguments, y/x.
37375 * By providing two arguments, the right quadrant of the computed angle can be
37376 * determined.
37377 *
37378 * For matrices, the function is evaluated element wise.
37379 *
37380 * Syntax:
37381 *
37382 * math.atan2(y, x)
37383 *
37384 * Examples:
37385 *
37386 * math.atan2(2, 2) / math.pi // returns number 0.25
37387 *
37388 * const angle = math.unit(60, 'deg') // returns Unit 60 deg
37389 * const x = math.cos(angle)
37390 * const y = math.sin(angle)
37391 *
37392 * math.atan(2) // returns Complex 1.5707963267948966 -1.3169578969248166 i
37393 *
37394 * See also:
37395 *
37396 * tan, atan, sin, cos
37397 *
37398 * @param {number | Array | Matrix} y Second dimension
37399 * @param {number | Array | Matrix} x First dimension
37400 * @return {number | Array | Matrix} Four-quadrant inverse tangent
37401 */
37402
37403 var atan2 = typed(atan2_name, {
37404 'number, number': Math.atan2,
37405 // Complex numbers doesn't seem to have a reasonable implementation of
37406 // atan2(). Even Matlab removed the support, after they only calculated
37407 // the atan only on base of the real part of the numbers and ignored the imaginary.
37408 'BigNumber, BigNumber': function BigNumberBigNumber(y, x) {
37409 return BigNumber.atan2(y, x);
37410 },
37411 'SparseMatrix, SparseMatrix': function SparseMatrixSparseMatrix(x, y) {
37412 return algorithm09(x, y, atan2, false);
37413 },
37414 'SparseMatrix, DenseMatrix': function SparseMatrixDenseMatrix(x, y) {
37415 // mind the order of y and x!
37416 return algorithm02(y, x, atan2, true);
37417 },
37418 'DenseMatrix, SparseMatrix': function DenseMatrixSparseMatrix(x, y) {
37419 return algorithm03(x, y, atan2, false);
37420 },
37421 'DenseMatrix, DenseMatrix': function DenseMatrixDenseMatrix(x, y) {
37422 return algorithm13(x, y, atan2);
37423 },
37424 'Array, Array': function ArrayArray(x, y) {
37425 return atan2(matrix(x), matrix(y)).valueOf();
37426 },
37427 'Array, Matrix': function ArrayMatrix(x, y) {
37428 return atan2(matrix(x), y);
37429 },
37430 'Matrix, Array': function MatrixArray(x, y) {
37431 return atan2(x, matrix(y));
37432 },
37433 'SparseMatrix, number | BigNumber': function SparseMatrixNumberBigNumber(x, y) {
37434 return algorithm11(x, y, atan2, false);
37435 },
37436 'DenseMatrix, number | BigNumber': function DenseMatrixNumberBigNumber(x, y) {
37437 return algorithm14(x, y, atan2, false);
37438 },
37439 'number | BigNumber, SparseMatrix': function numberBigNumberSparseMatrix(x, y) {
37440 // mind the order of y and x
37441 return algorithm12(y, x, atan2, true);
37442 },
37443 'number | BigNumber, DenseMatrix': function numberBigNumberDenseMatrix(x, y) {
37444 // mind the order of y and x
37445 return algorithm14(y, x, atan2, true);
37446 },
37447 'Array, number | BigNumber': function ArrayNumberBigNumber(x, y) {
37448 return algorithm14(matrix(x), y, atan2, false).valueOf();
37449 },
37450 'number | BigNumber, Array': function numberBigNumberArray(x, y) {
37451 return algorithm14(matrix(y), x, atan2, true).valueOf();
37452 }
37453 });
37454 return atan2;
37455});
37456// CONCATENATED MODULE: ./src/function/trigonometry/atanh.js
37457
37458
37459
37460var atanh_name = 'atanh';
37461var atanh_dependencies = ['typed', 'config', 'Complex'];
37462var createAtanh =
37463/* #__PURE__ */
37464Object(factory["a" /* factory */])(atanh_name, atanh_dependencies, function (_ref) {
37465 var typed = _ref.typed,
37466 config = _ref.config,
37467 Complex = _ref.Complex;
37468
37469 /**
37470 * Calculate the hyperbolic arctangent of a value,
37471 * defined as `atanh(x) = ln((1 + x)/(1 - x)) / 2`.
37472 *
37473 * For matrices, the function is evaluated element wise.
37474 *
37475 * Syntax:
37476 *
37477 * math.atanh(x)
37478 *
37479 * Examples:
37480 *
37481 * math.atanh(0.5) // returns 0.5493061443340549
37482 *
37483 * See also:
37484 *
37485 * acosh, asinh
37486 *
37487 * @param {number | Complex | Array | Matrix} x Function input
37488 * @return {number | Complex | Array | Matrix} Hyperbolic arctangent of x
37489 */
37490 var atanh = typed(atanh_name, {
37491 number: function number(x) {
37492 if (x <= 1 && x >= -1 || config.predictable) {
37493 return atanhNumber(x);
37494 }
37495
37496 return new Complex(x, 0).atanh();
37497 },
37498 Complex: function Complex(x) {
37499 return x.atanh();
37500 },
37501 BigNumber: function BigNumber(x) {
37502 return x.atanh();
37503 },
37504 'Array | Matrix': function ArrayMatrix(x) {
37505 // deep map collection, skip zeros since atanh(0) = 0
37506 return deepMap(x, atanh, true);
37507 }
37508 });
37509 return atanh;
37510});
37511// CONCATENATED MODULE: ./src/function/trigonometry/cos.js
37512
37513
37514var cos_name = 'cos';
37515var cos_dependencies = ['typed'];
37516var createCos =
37517/* #__PURE__ */
37518Object(factory["a" /* factory */])(cos_name, cos_dependencies, function (_ref) {
37519 var typed = _ref.typed;
37520
37521 /**
37522 * Calculate the cosine of a value.
37523 *
37524 * For matrices, the function is evaluated element wise.
37525 *
37526 * Syntax:
37527 *
37528 * math.cos(x)
37529 *
37530 * Examples:
37531 *
37532 * math.cos(2) // returns number -0.4161468365471422
37533 * math.cos(math.pi / 4) // returns number 0.7071067811865475
37534 * math.cos(math.unit(180, 'deg')) // returns number -1
37535 * math.cos(math.unit(60, 'deg')) // returns number 0.5
37536 *
37537 * const angle = 0.2
37538 * math.pow(math.sin(angle), 2) + math.pow(math.cos(angle), 2) // returns number ~1
37539 *
37540 * See also:
37541 *
37542 * cos, tan
37543 *
37544 * @param {number | BigNumber | Complex | Unit | Array | Matrix} x Function input
37545 * @return {number | BigNumber | Complex | Array | Matrix} Cosine of x
37546 */
37547 var cos = typed(cos_name, {
37548 number: Math.cos,
37549 Complex: function Complex(x) {
37550 return x.cos();
37551 },
37552 BigNumber: function BigNumber(x) {
37553 return x.cos();
37554 },
37555 Unit: function Unit(x) {
37556 if (!x.hasBase(x.constructor.BASE_UNITS.ANGLE)) {
37557 throw new TypeError('Unit in function cos is no angle');
37558 }
37559
37560 return cos(x.value);
37561 },
37562 'Array | Matrix': function ArrayMatrix(x) {
37563 return deepMap(x, cos);
37564 }
37565 });
37566 return cos;
37567});
37568// CONCATENATED MODULE: ./src/function/trigonometry/cosh.js
37569
37570
37571
37572var cosh_name = 'cosh';
37573var cosh_dependencies = ['typed'];
37574var createCosh =
37575/* #__PURE__ */
37576Object(factory["a" /* factory */])(cosh_name, cosh_dependencies, function (_ref) {
37577 var typed = _ref.typed;
37578
37579 /**
37580 * Calculate the hyperbolic cosine of a value,
37581 * defined as `cosh(x) = 1/2 * (exp(x) + exp(-x))`.
37582 *
37583 * For matrices, the function is evaluated element wise.
37584 *
37585 * Syntax:
37586 *
37587 * math.cosh(x)
37588 *
37589 * Examples:
37590 *
37591 * math.cosh(0.5) // returns number 1.1276259652063807
37592 *
37593 * See also:
37594 *
37595 * sinh, tanh
37596 *
37597 * @param {number | BigNumber | Complex | Unit | Array | Matrix} x Function input
37598 * @return {number | BigNumber | Complex | Array | Matrix} Hyperbolic cosine of x
37599 */
37600 var cosh = typed(cosh_name, {
37601 number: utils_number["e" /* cosh */],
37602 Complex: function Complex(x) {
37603 return x.cosh();
37604 },
37605 BigNumber: function BigNumber(x) {
37606 return x.cosh();
37607 },
37608 Unit: function Unit(x) {
37609 if (!x.hasBase(x.constructor.BASE_UNITS.ANGLE)) {
37610 throw new TypeError('Unit in function cosh is no angle');
37611 }
37612
37613 return cosh(x.value);
37614 },
37615 'Array | Matrix': function ArrayMatrix(x) {
37616 return deepMap(x, cosh);
37617 }
37618 });
37619 return cosh;
37620});
37621// CONCATENATED MODULE: ./src/function/trigonometry/cot.js
37622
37623
37624
37625var cot_name = 'cot';
37626var cot_dependencies = ['typed', 'BigNumber'];
37627var createCot =
37628/* #__PURE__ */
37629Object(factory["a" /* factory */])(cot_name, cot_dependencies, function (_ref) {
37630 var typed = _ref.typed,
37631 _BigNumber = _ref.BigNumber;
37632
37633 /**
37634 * Calculate the cotangent of a value. Defined as `cot(x) = 1 / tan(x)`.
37635 *
37636 * For matrices, the function is evaluated element wise.
37637 *
37638 * Syntax:
37639 *
37640 * math.cot(x)
37641 *
37642 * Examples:
37643 *
37644 * math.cot(2) // returns number -0.45765755436028577
37645 * 1 / math.tan(2) // returns number -0.45765755436028577
37646 *
37647 * See also:
37648 *
37649 * tan, sec, csc
37650 *
37651 * @param {number | Complex | Unit | Array | Matrix} x Function input
37652 * @return {number | Complex | Array | Matrix} Cotangent of x
37653 */
37654 var cot = typed(cot_name, {
37655 number: cotNumber,
37656 Complex: function Complex(x) {
37657 return x.cot();
37658 },
37659 BigNumber: function BigNumber(x) {
37660 return new _BigNumber(1).div(x.tan());
37661 },
37662 Unit: function Unit(x) {
37663 if (!x.hasBase(x.constructor.BASE_UNITS.ANGLE)) {
37664 throw new TypeError('Unit in function cot is no angle');
37665 }
37666
37667 return cot(x.value);
37668 },
37669 'Array | Matrix': function ArrayMatrix(x) {
37670 return deepMap(x, cot);
37671 }
37672 });
37673 return cot;
37674});
37675// CONCATENATED MODULE: ./src/function/trigonometry/coth.js
37676
37677
37678
37679var coth_name = 'coth';
37680var coth_dependencies = ['typed', 'BigNumber'];
37681var createCoth =
37682/* #__PURE__ */
37683Object(factory["a" /* factory */])(coth_name, coth_dependencies, function (_ref) {
37684 var typed = _ref.typed,
37685 _BigNumber = _ref.BigNumber;
37686
37687 /**
37688 * Calculate the hyperbolic cotangent of a value,
37689 * defined as `coth(x) = 1 / tanh(x)`.
37690 *
37691 * For matrices, the function is evaluated element wise.
37692 *
37693 * Syntax:
37694 *
37695 * math.coth(x)
37696 *
37697 * Examples:
37698 *
37699 * // coth(x) = 1 / tanh(x)
37700 * math.coth(2) // returns 1.0373147207275482
37701 * 1 / math.tanh(2) // returns 1.0373147207275482
37702 *
37703 * See also:
37704 *
37705 * sinh, tanh, cosh
37706 *
37707 * @param {number | Complex | Unit | Array | Matrix} x Function input
37708 * @return {number | Complex | Array | Matrix} Hyperbolic cotangent of x
37709 */
37710 var coth = typed(coth_name, {
37711 number: cothNumber,
37712 Complex: function Complex(x) {
37713 return x.coth();
37714 },
37715 BigNumber: function BigNumber(x) {
37716 return new _BigNumber(1).div(x.tanh());
37717 },
37718 Unit: function Unit(x) {
37719 if (!x.hasBase(x.constructor.BASE_UNITS.ANGLE)) {
37720 throw new TypeError('Unit in function coth is no angle');
37721 }
37722
37723 return coth(x.value);
37724 },
37725 'Array | Matrix': function ArrayMatrix(x) {
37726 return deepMap(x, coth);
37727 }
37728 });
37729 return coth;
37730});
37731// CONCATENATED MODULE: ./src/function/trigonometry/csc.js
37732
37733
37734
37735var csc_name = 'csc';
37736var csc_dependencies = ['typed', 'BigNumber'];
37737var createCsc =
37738/* #__PURE__ */
37739Object(factory["a" /* factory */])(csc_name, csc_dependencies, function (_ref) {
37740 var typed = _ref.typed,
37741 _BigNumber = _ref.BigNumber;
37742
37743 /**
37744 * Calculate the cosecant of a value, defined as `csc(x) = 1/sin(x)`.
37745 *
37746 * For matrices, the function is evaluated element wise.
37747 *
37748 * Syntax:
37749 *
37750 * math.csc(x)
37751 *
37752 * Examples:
37753 *
37754 * math.csc(2) // returns number 1.099750170294617
37755 * 1 / math.sin(2) // returns number 1.099750170294617
37756 *
37757 * See also:
37758 *
37759 * sin, sec, cot
37760 *
37761 * @param {number | Complex | Unit | Array | Matrix} x Function input
37762 * @return {number | Complex | Array | Matrix} Cosecant of x
37763 */
37764 var csc = typed(csc_name, {
37765 number: cscNumber,
37766 Complex: function Complex(x) {
37767 return x.csc();
37768 },
37769 BigNumber: function BigNumber(x) {
37770 return new _BigNumber(1).div(x.sin());
37771 },
37772 Unit: function Unit(x) {
37773 if (!x.hasBase(x.constructor.BASE_UNITS.ANGLE)) {
37774 throw new TypeError('Unit in function csc is no angle');
37775 }
37776
37777 return csc(x.value);
37778 },
37779 'Array | Matrix': function ArrayMatrix(x) {
37780 return deepMap(x, csc);
37781 }
37782 });
37783 return csc;
37784});
37785// CONCATENATED MODULE: ./src/function/trigonometry/csch.js
37786
37787
37788
37789var csch_name = 'csch';
37790var csch_dependencies = ['typed', 'BigNumber'];
37791var createCsch =
37792/* #__PURE__ */
37793Object(factory["a" /* factory */])(csch_name, csch_dependencies, function (_ref) {
37794 var typed = _ref.typed,
37795 _BigNumber = _ref.BigNumber;
37796
37797 /**
37798 * Calculate the hyperbolic cosecant of a value,
37799 * defined as `csch(x) = 1 / sinh(x)`.
37800 *
37801 * For matrices, the function is evaluated element wise.
37802 *
37803 * Syntax:
37804 *
37805 * math.csch(x)
37806 *
37807 * Examples:
37808 *
37809 * // csch(x) = 1/ sinh(x)
37810 * math.csch(0.5) // returns 1.9190347513349437
37811 * 1 / math.sinh(0.5) // returns 1.9190347513349437
37812 *
37813 * See also:
37814 *
37815 * sinh, sech, coth
37816 *
37817 * @param {number | Complex | Unit | Array | Matrix} x Function input
37818 * @return {number | Complex | Array | Matrix} Hyperbolic cosecant of x
37819 */
37820 var csch = typed(csch_name, {
37821 number: cschNumber,
37822 Complex: function Complex(x) {
37823 return x.csch();
37824 },
37825 BigNumber: function BigNumber(x) {
37826 return new _BigNumber(1).div(x.sinh());
37827 },
37828 Unit: function Unit(x) {
37829 if (!x.hasBase(x.constructor.BASE_UNITS.ANGLE)) {
37830 throw new TypeError('Unit in function csch is no angle');
37831 }
37832
37833 return csch(x.value);
37834 },
37835 'Array | Matrix': function ArrayMatrix(x) {
37836 return deepMap(x, csch);
37837 }
37838 });
37839 return csch;
37840});
37841// CONCATENATED MODULE: ./src/function/trigonometry/sec.js
37842
37843
37844
37845var sec_name = 'sec';
37846var sec_dependencies = ['typed', 'BigNumber'];
37847var createSec =
37848/* #__PURE__ */
37849Object(factory["a" /* factory */])(sec_name, sec_dependencies, function (_ref) {
37850 var typed = _ref.typed,
37851 _BigNumber = _ref.BigNumber;
37852
37853 /**
37854 * Calculate the secant of a value, defined as `sec(x) = 1/cos(x)`.
37855 *
37856 * For matrices, the function is evaluated element wise.
37857 *
37858 * Syntax:
37859 *
37860 * math.sec(x)
37861 *
37862 * Examples:
37863 *
37864 * math.sec(2) // returns number -2.4029979617223822
37865 * 1 / math.cos(2) // returns number -2.4029979617223822
37866 *
37867 * See also:
37868 *
37869 * cos, csc, cot
37870 *
37871 * @param {number | Complex | Unit | Array | Matrix} x Function input
37872 * @return {number | Complex | Array | Matrix} Secant of x
37873 */
37874 var sec = typed(sec_name, {
37875 number: secNumber,
37876 Complex: function Complex(x) {
37877 return x.sec();
37878 },
37879 BigNumber: function BigNumber(x) {
37880 return new _BigNumber(1).div(x.cos());
37881 },
37882 Unit: function Unit(x) {
37883 if (!x.hasBase(x.constructor.BASE_UNITS.ANGLE)) {
37884 throw new TypeError('Unit in function sec is no angle');
37885 }
37886
37887 return sec(x.value);
37888 },
37889 'Array | Matrix': function ArrayMatrix(x) {
37890 return deepMap(x, sec);
37891 }
37892 });
37893 return sec;
37894});
37895// CONCATENATED MODULE: ./src/function/trigonometry/sech.js
37896
37897
37898
37899var sech_name = 'sech';
37900var sech_dependencies = ['typed', 'BigNumber'];
37901var createSech =
37902/* #__PURE__ */
37903Object(factory["a" /* factory */])(sech_name, sech_dependencies, function (_ref) {
37904 var typed = _ref.typed,
37905 _BigNumber = _ref.BigNumber;
37906
37907 /**
37908 * Calculate the hyperbolic secant of a value,
37909 * defined as `sech(x) = 1 / cosh(x)`.
37910 *
37911 * For matrices, the function is evaluated element wise.
37912 *
37913 * Syntax:
37914 *
37915 * math.sech(x)
37916 *
37917 * Examples:
37918 *
37919 * // sech(x) = 1/ cosh(x)
37920 * math.sech(0.5) // returns 0.886818883970074
37921 * 1 / math.cosh(0.5) // returns 0.886818883970074
37922 *
37923 * See also:
37924 *
37925 * cosh, csch, coth
37926 *
37927 * @param {number | Complex | Unit | Array | Matrix} x Function input
37928 * @return {number | Complex | Array | Matrix} Hyperbolic secant of x
37929 */
37930 var sech = typed(sech_name, {
37931 number: sechNumber,
37932 Complex: function Complex(x) {
37933 return x.sech();
37934 },
37935 BigNumber: function BigNumber(x) {
37936 return new _BigNumber(1).div(x.cosh());
37937 },
37938 Unit: function Unit(x) {
37939 if (!x.hasBase(x.constructor.BASE_UNITS.ANGLE)) {
37940 throw new TypeError('Unit in function sech is no angle');
37941 }
37942
37943 return sech(x.value);
37944 },
37945 'Array | Matrix': function ArrayMatrix(x) {
37946 return deepMap(x, sech);
37947 }
37948 });
37949 return sech;
37950});
37951// CONCATENATED MODULE: ./src/function/trigonometry/sin.js
37952
37953
37954var sin_name = 'sin';
37955var sin_dependencies = ['typed'];
37956var createSin =
37957/* #__PURE__ */
37958Object(factory["a" /* factory */])(sin_name, sin_dependencies, function (_ref) {
37959 var typed = _ref.typed;
37960
37961 /**
37962 * Calculate the sine of a value.
37963 *
37964 * For matrices, the function is evaluated element wise.
37965 *
37966 * Syntax:
37967 *
37968 * math.sin(x)
37969 *
37970 * Examples:
37971 *
37972 * math.sin(2) // returns number 0.9092974268256813
37973 * math.sin(math.pi / 4) // returns number 0.7071067811865475
37974 * math.sin(math.unit(90, 'deg')) // returns number 1
37975 * math.sin(math.unit(30, 'deg')) // returns number 0.5
37976 *
37977 * const angle = 0.2
37978 * math.pow(math.sin(angle), 2) + math.pow(math.cos(angle), 2) // returns number ~1
37979 *
37980 * See also:
37981 *
37982 * cos, tan
37983 *
37984 * @param {number | BigNumber | Complex | Unit | Array | Matrix} x Function input
37985 * @return {number | BigNumber | Complex | Array | Matrix} Sine of x
37986 */
37987 var sin = typed(sin_name, {
37988 number: Math.sin,
37989 Complex: function Complex(x) {
37990 return x.sin();
37991 },
37992 BigNumber: function BigNumber(x) {
37993 return x.sin();
37994 },
37995 Unit: function Unit(x) {
37996 if (!x.hasBase(x.constructor.BASE_UNITS.ANGLE)) {
37997 throw new TypeError('Unit in function sin is no angle');
37998 }
37999
38000 return sin(x.value);
38001 },
38002 'Array | Matrix': function ArrayMatrix(x) {
38003 // deep map collection, skip zeros since sin(0) = 0
38004 return deepMap(x, sin, true);
38005 }
38006 });
38007 return sin;
38008});
38009// CONCATENATED MODULE: ./src/function/trigonometry/sinh.js
38010
38011
38012
38013var sinh_name = 'sinh';
38014var sinh_dependencies = ['typed'];
38015var createSinh =
38016/* #__PURE__ */
38017Object(factory["a" /* factory */])(sinh_name, sinh_dependencies, function (_ref) {
38018 var typed = _ref.typed;
38019
38020 /**
38021 * Calculate the hyperbolic sine of a value,
38022 * defined as `sinh(x) = 1/2 * (exp(x) - exp(-x))`.
38023 *
38024 * For matrices, the function is evaluated element wise.
38025 *
38026 * Syntax:
38027 *
38028 * math.sinh(x)
38029 *
38030 * Examples:
38031 *
38032 * math.sinh(0.5) // returns number 0.5210953054937474
38033 *
38034 * See also:
38035 *
38036 * cosh, tanh
38037 *
38038 * @param {number | BigNumber | Complex | Unit | Array | Matrix} x Function input
38039 * @return {number | BigNumber | Complex | Array | Matrix} Hyperbolic sine of x
38040 */
38041 var sinh = typed(sinh_name, {
38042 number: sinhNumber,
38043 Complex: function Complex(x) {
38044 return x.sinh();
38045 },
38046 BigNumber: function BigNumber(x) {
38047 return x.sinh();
38048 },
38049 Unit: function Unit(x) {
38050 if (!x.hasBase(x.constructor.BASE_UNITS.ANGLE)) {
38051 throw new TypeError('Unit in function sinh is no angle');
38052 }
38053
38054 return sinh(x.value);
38055 },
38056 'Array | Matrix': function ArrayMatrix(x) {
38057 // deep map collection, skip zeros since sinh(0) = 0
38058 return deepMap(x, sinh, true);
38059 }
38060 });
38061 return sinh;
38062});
38063// CONCATENATED MODULE: ./src/function/trigonometry/tan.js
38064
38065
38066var tan_name = 'tan';
38067var tan_dependencies = ['typed'];
38068var createTan =
38069/* #__PURE__ */
38070Object(factory["a" /* factory */])(tan_name, tan_dependencies, function (_ref) {
38071 var typed = _ref.typed;
38072
38073 /**
38074 * Calculate the tangent of a value. `tan(x)` is equal to `sin(x) / cos(x)`.
38075 *
38076 * For matrices, the function is evaluated element wise.
38077 *
38078 * Syntax:
38079 *
38080 * math.tan(x)
38081 *
38082 * Examples:
38083 *
38084 * math.tan(0.5) // returns number 0.5463024898437905
38085 * math.sin(0.5) / math.cos(0.5) // returns number 0.5463024898437905
38086 * math.tan(math.pi / 4) // returns number 1
38087 * math.tan(math.unit(45, 'deg')) // returns number 1
38088 *
38089 * See also:
38090 *
38091 * atan, sin, cos
38092 *
38093 * @param {number | BigNumber | Complex | Unit | Array | Matrix} x Function input
38094 * @return {number | BigNumber | Complex | Array | Matrix} Tangent of x
38095 */
38096 var tan = typed(tan_name, {
38097 number: Math.tan,
38098 Complex: function Complex(x) {
38099 return x.tan();
38100 },
38101 BigNumber: function BigNumber(x) {
38102 return x.tan();
38103 },
38104 Unit: function Unit(x) {
38105 if (!x.hasBase(x.constructor.BASE_UNITS.ANGLE)) {
38106 throw new TypeError('Unit in function tan is no angle');
38107 }
38108
38109 return tan(x.value);
38110 },
38111 'Array | Matrix': function ArrayMatrix(x) {
38112 // deep map collection, skip zeros since tan(0) = 0
38113 return deepMap(x, tan, true);
38114 }
38115 });
38116 return tan;
38117});
38118// CONCATENATED MODULE: ./src/function/trigonometry/tanh.js
38119
38120
38121
38122var tanh_name = 'tanh';
38123var tanh_dependencies = ['typed'];
38124var createTanh =
38125/* #__PURE__ */
38126Object(factory["a" /* factory */])(tanh_name, tanh_dependencies, function (_ref) {
38127 var typed = _ref.typed;
38128
38129 /**
38130 * Calculate the hyperbolic tangent of a value,
38131 * defined as `tanh(x) = (exp(2 * x) - 1) / (exp(2 * x) + 1)`.
38132 *
38133 * For matrices, the function is evaluated element wise.
38134 *
38135 * Syntax:
38136 *
38137 * math.tanh(x)
38138 *
38139 * Examples:
38140 *
38141 * // tanh(x) = sinh(x) / cosh(x) = 1 / coth(x)
38142 * math.tanh(0.5) // returns 0.46211715726000974
38143 * math.sinh(0.5) / math.cosh(0.5) // returns 0.46211715726000974
38144 * 1 / math.coth(0.5) // returns 0.46211715726000974
38145 *
38146 * See also:
38147 *
38148 * sinh, cosh, coth
38149 *
38150 * @param {number | BigNumber | Complex | Unit | Array | Matrix} x Function input
38151 * @return {number | BigNumber | Complex | Array | Matrix} Hyperbolic tangent of x
38152 */
38153 var tanh = typed('tanh', {
38154 number: utils_number["p" /* tanh */],
38155 Complex: function Complex(x) {
38156 return x.tanh();
38157 },
38158 BigNumber: function BigNumber(x) {
38159 return x.tanh();
38160 },
38161 Unit: function Unit(x) {
38162 if (!x.hasBase(x.constructor.BASE_UNITS.ANGLE)) {
38163 throw new TypeError('Unit in function tanh is no angle');
38164 }
38165
38166 return tanh(x.value);
38167 },
38168 'Array | Matrix': function ArrayMatrix(x) {
38169 // deep map collection, skip zeros since tanh(0) = 0
38170 return deepMap(x, tanh, true);
38171 }
38172 });
38173 return tanh;
38174});
38175// CONCATENATED MODULE: ./src/function/set/setCartesian.js
38176
38177
38178var setCartesian_name = 'setCartesian';
38179var setCartesian_dependencies = ['typed', 'size', 'subset', 'compareNatural', 'Index', 'DenseMatrix'];
38180var createSetCartesian =
38181/* #__PURE__ */
38182Object(factory["a" /* factory */])(setCartesian_name, setCartesian_dependencies, function (_ref) {
38183 var typed = _ref.typed,
38184 size = _ref.size,
38185 subset = _ref.subset,
38186 compareNatural = _ref.compareNatural,
38187 Index = _ref.Index,
38188 DenseMatrix = _ref.DenseMatrix;
38189
38190 /**
38191 * Create the cartesian product of two (multi)sets.
38192 * Multi-dimension arrays will be converted to single-dimension arrays before the operation.
38193 *
38194 * Syntax:
38195 *
38196 * math.setCartesian(set1, set2)
38197 *
38198 * Examples:
38199 *
38200 * math.setCartesian([1, 2], [3, 4]) // returns [[1, 3], [1, 4], [2, 3], [2, 4]]
38201 *
38202 * See also:
38203 *
38204 * setUnion, setIntersect, setDifference, setPowerset
38205 *
38206 * @param {Array | Matrix} a1 A (multi)set
38207 * @param {Array | Matrix} a2 A (multi)set
38208 * @return {Array | Matrix} The cartesian product of two (multi)sets
38209 */
38210 return typed(setCartesian_name, {
38211 'Array | Matrix, Array | Matrix': function ArrayMatrixArrayMatrix(a1, a2) {
38212 var result = [];
38213
38214 if (subset(size(a1), new Index(0)) !== 0 && subset(size(a2), new Index(0)) !== 0) {
38215 // if any of them is empty, return empty
38216 var b1 = Object(utils_array["e" /* flatten */])(Array.isArray(a1) ? a1 : a1.toArray()).sort(compareNatural);
38217 var b2 = Object(utils_array["e" /* flatten */])(Array.isArray(a2) ? a2 : a2.toArray()).sort(compareNatural);
38218 result = [];
38219
38220 for (var i = 0; i < b1.length; i++) {
38221 for (var j = 0; j < b2.length; j++) {
38222 result.push([b1[i], b2[j]]);
38223 }
38224 }
38225 } // return an array, if both inputs were arrays
38226
38227
38228 if (Array.isArray(a1) && Array.isArray(a2)) {
38229 return result;
38230 } // return a matrix otherwise
38231
38232
38233 return new DenseMatrix(result);
38234 }
38235 });
38236});
38237// CONCATENATED MODULE: ./src/function/set/setDifference.js
38238
38239
38240var setDifference_name = 'setDifference';
38241var setDifference_dependencies = ['typed', 'size', 'subset', 'compareNatural', 'Index', 'DenseMatrix'];
38242var createSetDifference =
38243/* #__PURE__ */
38244Object(factory["a" /* factory */])(setDifference_name, setDifference_dependencies, function (_ref) {
38245 var typed = _ref.typed,
38246 size = _ref.size,
38247 subset = _ref.subset,
38248 compareNatural = _ref.compareNatural,
38249 Index = _ref.Index,
38250 DenseMatrix = _ref.DenseMatrix;
38251
38252 /**
38253 * Create the difference of two (multi)sets: every element of set1, that is not the element of set2.
38254 * Multi-dimension arrays will be converted to single-dimension arrays before the operation.
38255 *
38256 * Syntax:
38257 *
38258 * math.setDifference(set1, set2)
38259 *
38260 * Examples:
38261 *
38262 * math.setDifference([1, 2, 3, 4], [3, 4, 5, 6]) // returns [1, 2]
38263 * math.setDifference([[1, 2], [3, 4]], [[3, 4], [5, 6]]) // returns [1, 2]
38264 *
38265 * See also:
38266 *
38267 * setUnion, setIntersect, setSymDifference
38268 *
38269 * @param {Array | Matrix} a1 A (multi)set
38270 * @param {Array | Matrix} a2 A (multi)set
38271 * @return {Array | Matrix} The difference of two (multi)sets
38272 */
38273 return typed(setDifference_name, {
38274 'Array | Matrix, Array | Matrix': function ArrayMatrixArrayMatrix(a1, a2) {
38275 var result;
38276
38277 if (subset(size(a1), new Index(0)) === 0) {
38278 // empty-anything=empty
38279 result = [];
38280 } else if (subset(size(a2), new Index(0)) === 0) {
38281 // anything-empty=anything
38282 return Object(utils_array["e" /* flatten */])(a1.toArray());
38283 } else {
38284 var b1 = Object(utils_array["i" /* identify */])(Object(utils_array["e" /* flatten */])(Array.isArray(a1) ? a1 : a1.toArray()).sort(compareNatural));
38285 var b2 = Object(utils_array["i" /* identify */])(Object(utils_array["e" /* flatten */])(Array.isArray(a2) ? a2 : a2.toArray()).sort(compareNatural));
38286 result = [];
38287 var inb2;
38288
38289 for (var i = 0; i < b1.length; i++) {
38290 inb2 = false;
38291
38292 for (var j = 0; j < b2.length; j++) {
38293 if (compareNatural(b1[i].value, b2[j].value) === 0 && b1[i].identifier === b2[j].identifier) {
38294 // the identifier is always a decimal int
38295 inb2 = true;
38296 break;
38297 }
38298 }
38299
38300 if (!inb2) {
38301 result.push(b1[i]);
38302 }
38303 }
38304 } // return an array, if both inputs were arrays
38305
38306
38307 if (Array.isArray(a1) && Array.isArray(a2)) {
38308 return Object(utils_array["g" /* generalize */])(result);
38309 } // return a matrix otherwise
38310
38311
38312 return new DenseMatrix(Object(utils_array["g" /* generalize */])(result));
38313 }
38314 });
38315});
38316// CONCATENATED MODULE: ./src/function/set/setDistinct.js
38317
38318
38319var setDistinct_name = 'setDistinct';
38320var setDistinct_dependencies = ['typed', 'size', 'subset', 'compareNatural', 'Index', 'DenseMatrix'];
38321var createSetDistinct =
38322/* #__PURE__ */
38323Object(factory["a" /* factory */])(setDistinct_name, setDistinct_dependencies, function (_ref) {
38324 var typed = _ref.typed,
38325 size = _ref.size,
38326 subset = _ref.subset,
38327 compareNatural = _ref.compareNatural,
38328 Index = _ref.Index,
38329 DenseMatrix = _ref.DenseMatrix;
38330
38331 /**
38332 * Collect the distinct elements of a multiset.
38333 * A multi-dimension array will be converted to a single-dimension array before the operation.
38334 *
38335 * Syntax:
38336 *
38337 * math.setDistinct(set)
38338 *
38339 * Examples:
38340 *
38341 * math.setDistinct([1, 1, 1, 2, 2, 3]) // returns [1, 2, 3]
38342 *
38343 * See also:
38344 *
38345 * setMultiplicity
38346 *
38347 * @param {Array | Matrix} a A multiset
38348 * @return {Array | Matrix} A set containing the distinc elements of the multiset
38349 */
38350 return typed(setDistinct_name, {
38351 'Array | Matrix': function ArrayMatrix(a) {
38352 var result;
38353
38354 if (subset(size(a), new Index(0)) === 0) {
38355 // if empty, return empty
38356 result = [];
38357 } else {
38358 var b = Object(utils_array["e" /* flatten */])(Array.isArray(a) ? a : a.toArray()).sort(compareNatural);
38359 result = [];
38360 result.push(b[0]);
38361
38362 for (var i = 1; i < b.length; i++) {
38363 if (compareNatural(b[i], b[i - 1]) !== 0) {
38364 result.push(b[i]);
38365 }
38366 }
38367 } // return an array, if the input was an array
38368
38369
38370 if (Array.isArray(a)) {
38371 return result;
38372 } // return a matrix otherwise
38373
38374
38375 return new DenseMatrix(result);
38376 }
38377 });
38378});
38379// CONCATENATED MODULE: ./src/function/set/setIntersect.js
38380
38381
38382var setIntersect_name = 'setIntersect';
38383var setIntersect_dependencies = ['typed', 'size', 'subset', 'compareNatural', 'Index', 'DenseMatrix'];
38384var createSetIntersect =
38385/* #__PURE__ */
38386Object(factory["a" /* factory */])(setIntersect_name, setIntersect_dependencies, function (_ref) {
38387 var typed = _ref.typed,
38388 size = _ref.size,
38389 subset = _ref.subset,
38390 compareNatural = _ref.compareNatural,
38391 Index = _ref.Index,
38392 DenseMatrix = _ref.DenseMatrix;
38393
38394 /**
38395 * Create the intersection of two (multi)sets.
38396 * Multi-dimension arrays will be converted to single-dimension arrays before the operation.
38397 *
38398 * Syntax:
38399 *
38400 * math.setIntersect(set1, set2)
38401 *
38402 * Examples:
38403 *
38404 * math.setIntersect([1, 2, 3, 4], [3, 4, 5, 6]) // returns [3, 4]
38405 * math.setIntersect([[1, 2], [3, 4]], [[3, 4], [5, 6]]) // returns [3, 4]
38406 *
38407 * See also:
38408 *
38409 * setUnion, setDifference
38410 *
38411 * @param {Array | Matrix} a1 A (multi)set
38412 * @param {Array | Matrix} a2 A (multi)set
38413 * @return {Array | Matrix} The intersection of two (multi)sets
38414 */
38415 return typed(setIntersect_name, {
38416 'Array | Matrix, Array | Matrix': function ArrayMatrixArrayMatrix(a1, a2) {
38417 var result;
38418
38419 if (subset(size(a1), new Index(0)) === 0 || subset(size(a2), new Index(0)) === 0) {
38420 // of any of them is empty, return empty
38421 result = [];
38422 } else {
38423 var b1 = Object(utils_array["i" /* identify */])(Object(utils_array["e" /* flatten */])(Array.isArray(a1) ? a1 : a1.toArray()).sort(compareNatural));
38424 var b2 = Object(utils_array["i" /* identify */])(Object(utils_array["e" /* flatten */])(Array.isArray(a2) ? a2 : a2.toArray()).sort(compareNatural));
38425 result = [];
38426
38427 for (var i = 0; i < b1.length; i++) {
38428 for (var j = 0; j < b2.length; j++) {
38429 if (compareNatural(b1[i].value, b2[j].value) === 0 && b1[i].identifier === b2[j].identifier) {
38430 // the identifier is always a decimal int
38431 result.push(b1[i]);
38432 break;
38433 }
38434 }
38435 }
38436 } // return an array, if both inputs were arrays
38437
38438
38439 if (Array.isArray(a1) && Array.isArray(a2)) {
38440 return Object(utils_array["g" /* generalize */])(result);
38441 } // return a matrix otherwise
38442
38443
38444 return new DenseMatrix(Object(utils_array["g" /* generalize */])(result));
38445 }
38446 });
38447});
38448// CONCATENATED MODULE: ./src/function/set/setIsSubset.js
38449
38450
38451var setIsSubset_name = 'setIsSubset';
38452var setIsSubset_dependencies = ['typed', 'size', 'subset', 'compareNatural', 'Index'];
38453var createSetIsSubset =
38454/* #__PURE__ */
38455Object(factory["a" /* factory */])(setIsSubset_name, setIsSubset_dependencies, function (_ref) {
38456 var typed = _ref.typed,
38457 size = _ref.size,
38458 subset = _ref.subset,
38459 compareNatural = _ref.compareNatural,
38460 Index = _ref.Index;
38461
38462 /**
38463 * Check whether a (multi)set is a subset of another (multi)set. (Every element of set1 is the element of set2.)
38464 * Multi-dimension arrays will be converted to single-dimension arrays before the operation.
38465 *
38466 * Syntax:
38467 *
38468 * math.setIsSubset(set1, set2)
38469 *
38470 * Examples:
38471 *
38472 * math.setIsSubset([1, 2], [3, 4, 5, 6]) // returns false
38473 * math.setIsSubset([3, 4], [3, 4, 5, 6]) // returns true
38474 *
38475 * See also:
38476 *
38477 * setUnion, setIntersect, setDifference
38478 *
38479 * @param {Array | Matrix} a1 A (multi)set
38480 * @param {Array | Matrix} a2 A (multi)set
38481 * @return {boolean} true | false
38482 */
38483 return typed(setIsSubset_name, {
38484 'Array | Matrix, Array | Matrix': function ArrayMatrixArrayMatrix(a1, a2) {
38485 if (subset(size(a1), new Index(0)) === 0) {
38486 // empty is a subset of anything
38487 return true;
38488 } else if (subset(size(a2), new Index(0)) === 0) {
38489 // anything is not a subset of empty
38490 return false;
38491 }
38492
38493 var b1 = Object(utils_array["i" /* identify */])(Object(utils_array["e" /* flatten */])(Array.isArray(a1) ? a1 : a1.toArray()).sort(compareNatural));
38494 var b2 = Object(utils_array["i" /* identify */])(Object(utils_array["e" /* flatten */])(Array.isArray(a2) ? a2 : a2.toArray()).sort(compareNatural));
38495 var inb2;
38496
38497 for (var i = 0; i < b1.length; i++) {
38498 inb2 = false;
38499
38500 for (var j = 0; j < b2.length; j++) {
38501 if (compareNatural(b1[i].value, b2[j].value) === 0 && b1[i].identifier === b2[j].identifier) {
38502 // the identifier is always a decimal int
38503 inb2 = true;
38504 break;
38505 }
38506 }
38507
38508 if (inb2 === false) {
38509 return false;
38510 }
38511 }
38512
38513 return true;
38514 }
38515 });
38516});
38517// CONCATENATED MODULE: ./src/function/set/setMultiplicity.js
38518
38519
38520var setMultiplicity_name = 'setMultiplicity';
38521var setMultiplicity_dependencies = ['typed', 'size', 'subset', 'compareNatural', 'Index'];
38522var createSetMultiplicity =
38523/* #__PURE__ */
38524Object(factory["a" /* factory */])(setMultiplicity_name, setMultiplicity_dependencies, function (_ref) {
38525 var typed = _ref.typed,
38526 size = _ref.size,
38527 subset = _ref.subset,
38528 compareNatural = _ref.compareNatural,
38529 Index = _ref.Index;
38530
38531 /**
38532 * Count the multiplicity of an element in a multiset.
38533 * A multi-dimension array will be converted to a single-dimension array before the operation.
38534 *
38535 * Syntax:
38536 *
38537 * math.setMultiplicity(element, set)
38538 *
38539 * Examples:
38540 *
38541 * math.setMultiplicity(1, [1, 2, 2, 4]) // returns 1
38542 * math.setMultiplicity(2, [1, 2, 2, 4]) // returns 2
38543 *
38544 * See also:
38545 *
38546 * setDistinct, setSize
38547 *
38548 * @param {number | BigNumber | Fraction | Complex} e An element in the multiset
38549 * @param {Array | Matrix} a A multiset
38550 * @return {number} The number of how many times the multiset contains the element
38551 */
38552 return typed(setMultiplicity_name, {
38553 'number | BigNumber | Fraction | Complex, Array | Matrix': function numberBigNumberFractionComplexArrayMatrix(e, a) {
38554 if (subset(size(a), new Index(0)) === 0) {
38555 // if empty, return 0
38556 return 0;
38557 }
38558
38559 var b = Object(utils_array["e" /* flatten */])(Array.isArray(a) ? a : a.toArray());
38560 var count = 0;
38561
38562 for (var i = 0; i < b.length; i++) {
38563 if (compareNatural(b[i], e) === 0) {
38564 count++;
38565 }
38566 }
38567
38568 return count;
38569 }
38570 });
38571});
38572// CONCATENATED MODULE: ./src/function/set/setPowerset.js
38573
38574
38575var setPowerset_name = 'setPowerset';
38576var setPowerset_dependencies = ['typed', 'size', 'subset', 'compareNatural', 'Index'];
38577var createSetPowerset =
38578/* #__PURE__ */
38579Object(factory["a" /* factory */])(setPowerset_name, setPowerset_dependencies, function (_ref) {
38580 var typed = _ref.typed,
38581 size = _ref.size,
38582 subset = _ref.subset,
38583 compareNatural = _ref.compareNatural,
38584 Index = _ref.Index;
38585
38586 /**
38587 * Create the powerset of a (multi)set. (The powerset contains very possible subsets of a (multi)set.)
38588 * A multi-dimension array will be converted to a single-dimension array before the operation.
38589 *
38590 * Syntax:
38591 *
38592 * math.setPowerset(set)
38593 *
38594 * Examples:
38595 *
38596 * math.setPowerset([1, 2, 3]) // returns [[], [1], [2], [3], [1, 2], [1, 3], [2, 3], [1, 2, 3]]
38597 *
38598 * See also:
38599 *
38600 * setCartesian
38601 *
38602 * @param {Array | Matrix} a A (multi)set
38603 * @return {Array} The powerset of the (multi)set
38604 */
38605 return typed(setPowerset_name, {
38606 'Array | Matrix': function ArrayMatrix(a) {
38607 if (subset(size(a), new Index(0)) === 0) {
38608 // if empty, return empty
38609 return [];
38610 }
38611
38612 var b = Object(utils_array["e" /* flatten */])(Array.isArray(a) ? a : a.toArray()).sort(compareNatural);
38613 var result = [];
38614 var number = 0;
38615
38616 while (number.toString(2).length <= b.length) {
38617 result.push(_subset(b, number.toString(2).split('').reverse()));
38618 number++;
38619 } // can not return a matrix, because of the different size of the subarrays
38620
38621
38622 return _sort(result);
38623 }
38624 }); // create subset
38625
38626 function _subset(array, bitarray) {
38627 var result = [];
38628
38629 for (var i = 0; i < bitarray.length; i++) {
38630 if (bitarray[i] === '1') {
38631 result.push(array[i]);
38632 }
38633 }
38634
38635 return result;
38636 } // sort subsests by length
38637
38638
38639 function _sort(array) {
38640 var temp = [];
38641
38642 for (var i = array.length - 1; i > 0; i--) {
38643 for (var j = 0; j < i; j++) {
38644 if (array[j].length > array[j + 1].length) {
38645 temp = array[j];
38646 array[j] = array[j + 1];
38647 array[j + 1] = temp;
38648 }
38649 }
38650 }
38651
38652 return array;
38653 }
38654});
38655// CONCATENATED MODULE: ./src/function/set/setSize.js
38656
38657
38658var setSize_name = 'setSize';
38659var setSize_dependencies = ['typed', 'compareNatural'];
38660var createSetSize =
38661/* #__PURE__ */
38662Object(factory["a" /* factory */])(setSize_name, setSize_dependencies, function (_ref) {
38663 var typed = _ref.typed,
38664 compareNatural = _ref.compareNatural;
38665
38666 /**
38667 * Count the number of elements of a (multi)set. When a second parameter is 'true', count only the unique values.
38668 * A multi-dimension array will be converted to a single-dimension array before the operation.
38669 *
38670 * Syntax:
38671 *
38672 * math.setSize(set)
38673 * math.setSize(set, unique)
38674 *
38675 * Examples:
38676 *
38677 * math.setSize([1, 2, 2, 4]) // returns 4
38678 * math.setSize([1, 2, 2, 4], true) // returns 3
38679 *
38680 * See also:
38681 *
38682 * setUnion, setIntersect, setDifference
38683 *
38684 * @param {Array | Matrix} a A multiset
38685 * @return {number} The number of elements of the (multi)set
38686 */
38687 return typed(setSize_name, {
38688 'Array | Matrix': function ArrayMatrix(a) {
38689 return Array.isArray(a) ? Object(utils_array["e" /* flatten */])(a).length : Object(utils_array["e" /* flatten */])(a.toArray()).length;
38690 },
38691 'Array | Matrix, boolean': function ArrayMatrixBoolean(a, unique) {
38692 if (unique === false || a.length === 0) {
38693 return Array.isArray(a) ? Object(utils_array["e" /* flatten */])(a).length : Object(utils_array["e" /* flatten */])(a.toArray()).length;
38694 } else {
38695 var b = Object(utils_array["e" /* flatten */])(Array.isArray(a) ? a : a.toArray()).sort(compareNatural);
38696 var count = 1;
38697
38698 for (var i = 1; i < b.length; i++) {
38699 if (compareNatural(b[i], b[i - 1]) !== 0) {
38700 count++;
38701 }
38702 }
38703
38704 return count;
38705 }
38706 }
38707 });
38708});
38709// CONCATENATED MODULE: ./src/function/set/setSymDifference.js
38710
38711
38712var setSymDifference_name = 'setSymDifference';
38713var setSymDifference_dependencies = ['typed', 'size', 'concat', 'subset', 'setDifference', 'Index'];
38714var createSetSymDifference =
38715/* #__PURE__ */
38716Object(factory["a" /* factory */])(setSymDifference_name, setSymDifference_dependencies, function (_ref) {
38717 var typed = _ref.typed,
38718 size = _ref.size,
38719 concat = _ref.concat,
38720 subset = _ref.subset,
38721 setDifference = _ref.setDifference,
38722 Index = _ref.Index;
38723
38724 /**
38725 * Create the symmetric difference of two (multi)sets.
38726 * Multi-dimension arrays will be converted to single-dimension arrays before the operation.
38727 *
38728 * Syntax:
38729 *
38730 * math.setSymDifference(set1, set2)
38731 *
38732 * Examples:
38733 *
38734 * math.setSymDifference([1, 2, 3, 4], [3, 4, 5, 6]) // returns [1, 2, 5, 6]
38735 * math.setSymDifference([[1, 2], [3, 4]], [[3, 4], [5, 6]]) // returns [1, 2, 5, 6]
38736 *
38737 * See also:
38738 *
38739 * setUnion, setIntersect, setDifference
38740 *
38741 * @param {Array | Matrix} a1 A (multi)set
38742 * @param {Array | Matrix} a2 A (multi)set
38743 * @return {Array | Matrix} The symmetric difference of two (multi)sets
38744 */
38745 return typed(setSymDifference_name, {
38746 'Array | Matrix, Array | Matrix': function ArrayMatrixArrayMatrix(a1, a2) {
38747 if (subset(size(a1), new Index(0)) === 0) {
38748 // if any of them is empty, return the other one
38749 return Object(utils_array["e" /* flatten */])(a2);
38750 } else if (subset(size(a2), new Index(0)) === 0) {
38751 return Object(utils_array["e" /* flatten */])(a1);
38752 }
38753
38754 var b1 = Object(utils_array["e" /* flatten */])(a1);
38755 var b2 = Object(utils_array["e" /* flatten */])(a2);
38756 return concat(setDifference(b1, b2), setDifference(b2, b1));
38757 }
38758 });
38759});
38760// CONCATENATED MODULE: ./src/function/set/setUnion.js
38761
38762
38763var setUnion_name = 'setUnion';
38764var setUnion_dependencies = ['typed', 'size', 'concat', 'subset', 'setIntersect', 'setSymDifference', 'Index'];
38765var createSetUnion =
38766/* #__PURE__ */
38767Object(factory["a" /* factory */])(setUnion_name, setUnion_dependencies, function (_ref) {
38768 var typed = _ref.typed,
38769 size = _ref.size,
38770 concat = _ref.concat,
38771 subset = _ref.subset,
38772 setIntersect = _ref.setIntersect,
38773 setSymDifference = _ref.setSymDifference,
38774 Index = _ref.Index;
38775
38776 /**
38777 * Create the union of two (multi)sets.
38778 * Multi-dimension arrays will be converted to single-dimension arrays before the operation.
38779 *
38780 * Syntax:
38781 *
38782 * math.setUnion(set1, set2)
38783 *
38784 * Examples:
38785 *
38786 * math.setUnion([1, 2, 3, 4], [3, 4, 5, 6]) // returns [1, 2, 3, 4, 5, 6]
38787 * math.setUnion([[1, 2], [3, 4]], [[3, 4], [5, 6]]) // returns [1, 2, 3, 4, 5, 6]
38788 *
38789 * See also:
38790 *
38791 * setIntersect, setDifference
38792 *
38793 * @param {Array | Matrix} a1 A (multi)set
38794 * @param {Array | Matrix} a2 A (multi)set
38795 * @return {Array | Matrix} The union of two (multi)sets
38796 */
38797 return typed(setUnion_name, {
38798 'Array | Matrix, Array | Matrix': function ArrayMatrixArrayMatrix(a1, a2) {
38799 if (subset(size(a1), new Index(0)) === 0) {
38800 // if any of them is empty, return the other one
38801 return Object(utils_array["e" /* flatten */])(a2);
38802 } else if (subset(size(a2), new Index(0)) === 0) {
38803 return Object(utils_array["e" /* flatten */])(a1);
38804 }
38805
38806 var b1 = Object(utils_array["e" /* flatten */])(a1);
38807 var b2 = Object(utils_array["e" /* flatten */])(a2);
38808 return concat(setSymDifference(b1, b2), setIntersect(b1, b2));
38809 }
38810 });
38811});
38812// CONCATENATED MODULE: ./src/function/arithmetic/add.js
38813
38814
38815
38816
38817
38818
38819
38820var add_name = 'add';
38821var add_dependencies = ['typed', 'matrix', 'addScalar', 'equalScalar', 'DenseMatrix', 'SparseMatrix'];
38822var createAdd =
38823/* #__PURE__ */
38824Object(factory["a" /* factory */])(add_name, add_dependencies, function (_ref) {
38825 var typed = _ref.typed,
38826 matrix = _ref.matrix,
38827 addScalar = _ref.addScalar,
38828 equalScalar = _ref.equalScalar,
38829 DenseMatrix = _ref.DenseMatrix,
38830 SparseMatrix = _ref.SparseMatrix;
38831 var algorithm01 = createAlgorithm01({
38832 typed: typed
38833 });
38834 var algorithm04 = createAlgorithm04({
38835 typed: typed,
38836 equalScalar: equalScalar
38837 });
38838 var algorithm10 = createAlgorithm10({
38839 typed: typed,
38840 DenseMatrix: DenseMatrix
38841 });
38842 var algorithm13 = createAlgorithm13({
38843 typed: typed
38844 });
38845 var algorithm14 = createAlgorithm14({
38846 typed: typed
38847 });
38848 /**
38849 * Add two or more values, `x + y`.
38850 * For matrices, the function is evaluated element wise.
38851 *
38852 * Syntax:
38853 *
38854 * math.add(x, y)
38855 * math.add(x, y, z, ...)
38856 *
38857 * Examples:
38858 *
38859 * math.add(2, 3) // returns number 5
38860 * math.add(2, 3, 4) // returns number 9
38861 *
38862 * const a = math.complex(2, 3)
38863 * const b = math.complex(-4, 1)
38864 * math.add(a, b) // returns Complex -2 + 4i
38865 *
38866 * math.add([1, 2, 3], 4) // returns Array [5, 6, 7]
38867 *
38868 * const c = math.unit('5 cm')
38869 * const d = math.unit('2.1 mm')
38870 * math.add(c, d) // returns Unit 52.1 mm
38871 *
38872 * math.add("2.3", "4") // returns number 6.3
38873 *
38874 * See also:
38875 *
38876 * subtract, sum
38877 *
38878 * @param {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} x First value to add
38879 * @param {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} y Second value to add
38880 * @return {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} Sum of `x` and `y`
38881 */
38882
38883 var add = typed(add_name, Object(utils_object["e" /* extend */])({
38884 // we extend the signatures of addScalar with signatures dealing with matrices
38885 'DenseMatrix, DenseMatrix': function DenseMatrixDenseMatrix(x, y) {
38886 return algorithm13(x, y, addScalar);
38887 },
38888 'DenseMatrix, SparseMatrix': function DenseMatrixSparseMatrix(x, y) {
38889 return algorithm01(x, y, addScalar, false);
38890 },
38891 'SparseMatrix, DenseMatrix': function SparseMatrixDenseMatrix(x, y) {
38892 return algorithm01(y, x, addScalar, true);
38893 },
38894 'SparseMatrix, SparseMatrix': function SparseMatrixSparseMatrix(x, y) {
38895 return algorithm04(x, y, addScalar);
38896 },
38897 'Array, Array': function ArrayArray(x, y) {
38898 // use matrix implementation
38899 return add(matrix(x), matrix(y)).valueOf();
38900 },
38901 'Array, Matrix': function ArrayMatrix(x, y) {
38902 // use matrix implementation
38903 return add(matrix(x), y);
38904 },
38905 'Matrix, Array': function MatrixArray(x, y) {
38906 // use matrix implementation
38907 return add(x, matrix(y));
38908 },
38909 'DenseMatrix, any': function DenseMatrixAny(x, y) {
38910 return algorithm14(x, y, addScalar, false);
38911 },
38912 'SparseMatrix, any': function SparseMatrixAny(x, y) {
38913 return algorithm10(x, y, addScalar, false);
38914 },
38915 'any, DenseMatrix': function anyDenseMatrix(x, y) {
38916 return algorithm14(y, x, addScalar, true);
38917 },
38918 'any, SparseMatrix': function anySparseMatrix(x, y) {
38919 return algorithm10(y, x, addScalar, true);
38920 },
38921 'Array, any': function ArrayAny(x, y) {
38922 // use matrix implementation
38923 return algorithm14(matrix(x), y, addScalar, false).valueOf();
38924 },
38925 'any, Array': function anyArray(x, y) {
38926 // use matrix implementation
38927 return algorithm14(matrix(y), x, addScalar, true).valueOf();
38928 },
38929 'any, any': addScalar,
38930 'any, any, ...any': function anyAnyAny(x, y, rest) {
38931 var result = add(x, y);
38932
38933 for (var i = 0; i < rest.length; i++) {
38934 result = add(result, rest[i]);
38935 }
38936
38937 return result;
38938 }
38939 }, addScalar.signatures));
38940 return add;
38941});
38942// CONCATENATED MODULE: ./src/function/arithmetic/hypot.js
38943
38944
38945var hypot_name = 'hypot';
38946var hypot_dependencies = ['typed', 'abs', 'addScalar', 'divideScalar', 'multiplyScalar', 'sqrt', 'smaller', 'isPositive'];
38947var createHypot =
38948/* #__PURE__ */
38949Object(factory["a" /* factory */])(hypot_name, hypot_dependencies, function (_ref) {
38950 var typed = _ref.typed,
38951 abs = _ref.abs,
38952 addScalar = _ref.addScalar,
38953 divideScalar = _ref.divideScalar,
38954 multiplyScalar = _ref.multiplyScalar,
38955 sqrt = _ref.sqrt,
38956 smaller = _ref.smaller,
38957 isPositive = _ref.isPositive;
38958
38959 /**
38960 * Calculate the hypotenusa of a list with values. The hypotenusa is defined as:
38961 *
38962 * hypot(a, b, c, ...) = sqrt(a^2 + b^2 + c^2 + ...)
38963 *
38964 * For matrix input, the hypotenusa is calculated for all values in the matrix.
38965 *
38966 * Syntax:
38967 *
38968 * math.hypot(a, b, ...)
38969 * math.hypot([a, b, c, ...])
38970 *
38971 * Examples:
38972 *
38973 * math.hypot(3, 4) // 5
38974 * math.hypot(3, 4, 5) // 7.0710678118654755
38975 * math.hypot([3, 4, 5]) // 7.0710678118654755
38976 * math.hypot(-2) // 2
38977 *
38978 * See also:
38979 *
38980 * abs, norm
38981 *
38982 * @param {... number | BigNumber | Array | Matrix} args A list with numeric values or an Array or Matrix.
38983 * Matrix and Array input is flattened and returns a
38984 * single number for the whole matrix.
38985 * @return {number | BigNumber} Returns the hypothenusa of the input values.
38986 */
38987 var hypot = typed(hypot_name, {
38988 '... number | BigNumber': _hypot,
38989 Array: function Array(x) {
38990 return hypot.apply(hypot, Object(utils_array["e" /* flatten */])(x));
38991 },
38992 Matrix: function Matrix(x) {
38993 return hypot.apply(hypot, Object(utils_array["e" /* flatten */])(x.toArray()));
38994 }
38995 });
38996 /**
38997 * Calculate the hypotenusa for an Array with values
38998 * @param {Array.<number | BigNumber>} args
38999 * @return {number | BigNumber} Returns the result
39000 * @private
39001 */
39002
39003 function _hypot(args) {
39004 // code based on `hypot` from es6-shim:
39005 // https://github.com/paulmillr/es6-shim/blob/master/es6-shim.js#L1619-L1633
39006 var result = 0;
39007 var largest = 0;
39008
39009 for (var i = 0; i < args.length; i++) {
39010 var value = abs(args[i]);
39011
39012 if (smaller(largest, value)) {
39013 result = multiplyScalar(result, multiplyScalar(divideScalar(largest, value), divideScalar(largest, value)));
39014 result = addScalar(result, 1);
39015 largest = value;
39016 } else {
39017 result = addScalar(result, isPositive(value) ? multiplyScalar(divideScalar(value, largest), divideScalar(value, largest)) : value);
39018 }
39019 }
39020
39021 return multiplyScalar(largest, sqrt(result));
39022 }
39023
39024 return hypot;
39025});
39026// CONCATENATED MODULE: ./src/function/arithmetic/norm.js
39027
39028var norm_name = 'norm';
39029var norm_dependencies = ['typed', 'abs', 'add', 'pow', 'conj', 'sqrt', 'multiply', 'equalScalar', 'larger', 'smaller', 'matrix'];
39030var createNorm =
39031/* #__PURE__ */
39032Object(factory["a" /* factory */])(norm_name, norm_dependencies, function (_ref) {
39033 var typed = _ref.typed,
39034 abs = _ref.abs,
39035 add = _ref.add,
39036 pow = _ref.pow,
39037 conj = _ref.conj,
39038 sqrt = _ref.sqrt,
39039 multiply = _ref.multiply,
39040 equalScalar = _ref.equalScalar,
39041 larger = _ref.larger,
39042 smaller = _ref.smaller,
39043 matrix = _ref.matrix;
39044
39045 /**
39046 * Calculate the norm of a number, vector or matrix.
39047 *
39048 * The second parameter p is optional. If not provided, it defaults to 2.
39049 *
39050 * Syntax:
39051 *
39052 * math.norm(x)
39053 * math.norm(x, p)
39054 *
39055 * Examples:
39056 *
39057 * math.abs(-3.5) // returns 3.5
39058 * math.norm(-3.5) // returns 3.5
39059 *
39060 * math.norm(math.complex(3, -4)) // returns 5
39061 *
39062 * math.norm([1, 2, -3], Infinity) // returns 3
39063 * math.norm([1, 2, -3], -Infinity) // returns 1
39064 *
39065 * math.norm([3, 4], 2) // returns 5
39066 *
39067 * math.norm([[1, 2], [3, 4]], 1) // returns 6
39068 * math.norm([[1, 2], [3, 4]], 'inf') // returns 7
39069 * math.norm([[1, 2], [3, 4]], 'fro') // returns 5.477225575051661
39070 *
39071 * See also:
39072 *
39073 * abs, hypot
39074 *
39075 * @param {number | BigNumber | Complex | Array | Matrix} x
39076 * Value for which to calculate the norm
39077 * @param {number | BigNumber | string} [p=2]
39078 * Vector space.
39079 * Supported numbers include Infinity and -Infinity.
39080 * Supported strings are: 'inf', '-inf', and 'fro' (The Frobenius norm)
39081 * @return {number | BigNumber} the p-norm
39082 */
39083 var norm = typed(norm_name, {
39084 number: Math.abs,
39085 Complex: function Complex(x) {
39086 return x.abs();
39087 },
39088 BigNumber: function BigNumber(x) {
39089 // norm(x) = abs(x)
39090 return x.abs();
39091 },
39092 "boolean": function boolean(x) {
39093 // norm(x) = abs(x)
39094 return Math.abs(x);
39095 },
39096 Array: function Array(x) {
39097 return _norm(matrix(x), 2);
39098 },
39099 Matrix: function Matrix(x) {
39100 return _norm(x, 2);
39101 },
39102 'number | Complex | BigNumber | boolean, number | BigNumber | string': function numberComplexBigNumberBooleanNumberBigNumberString(x) {
39103 // ignore second parameter, TODO: remove the option of second parameter for these types
39104 return norm(x);
39105 },
39106 'Array, number | BigNumber | string': function ArrayNumberBigNumberString(x, p) {
39107 return _norm(matrix(x), p);
39108 },
39109 'Matrix, number | BigNumber | string': function MatrixNumberBigNumberString(x, p) {
39110 return _norm(x, p);
39111 }
39112 });
39113 /**
39114 * Calculate the norm for an array
39115 * @param {Matrix} x
39116 * @param {number | string} p
39117 * @returns {number} Returns the norm
39118 * @private
39119 */
39120
39121 function _norm(x, p) {
39122 // size
39123 var sizeX = x.size(); // check if it is a vector
39124
39125 if (sizeX.length === 1) {
39126 // check p
39127 if (p === Number.POSITIVE_INFINITY || p === 'inf') {
39128 // norm(x, Infinity) = max(abs(x))
39129 var pinf = 0; // skip zeros since abs(0) === 0
39130
39131 x.forEach(function (value) {
39132 var v = abs(value);
39133
39134 if (larger(v, pinf)) {
39135 pinf = v;
39136 }
39137 }, true);
39138 return pinf;
39139 }
39140
39141 if (p === Number.NEGATIVE_INFINITY || p === '-inf') {
39142 // norm(x, -Infinity) = min(abs(x))
39143 var ninf; // skip zeros since abs(0) === 0
39144
39145 x.forEach(function (value) {
39146 var v = abs(value);
39147
39148 if (!ninf || smaller(v, ninf)) {
39149 ninf = v;
39150 }
39151 }, true);
39152 return ninf || 0;
39153 }
39154
39155 if (p === 'fro') {
39156 return _norm(x, 2);
39157 }
39158
39159 if (typeof p === 'number' && !isNaN(p)) {
39160 // check p != 0
39161 if (!equalScalar(p, 0)) {
39162 // norm(x, p) = sum(abs(xi) ^ p) ^ 1/p
39163 var n = 0; // skip zeros since abs(0) === 0
39164
39165 x.forEach(function (value) {
39166 n = add(pow(abs(value), p), n);
39167 }, true);
39168 return pow(n, 1 / p);
39169 }
39170
39171 return Number.POSITIVE_INFINITY;
39172 } // invalid parameter value
39173
39174
39175 throw new Error('Unsupported parameter value');
39176 } // MxN matrix
39177
39178
39179 if (sizeX.length === 2) {
39180 // check p
39181 if (p === 1) {
39182 // norm(x) = the largest column sum
39183 var c = []; // result
39184
39185 var maxc = 0; // skip zeros since abs(0) == 0
39186
39187 x.forEach(function (value, index) {
39188 var j = index[1];
39189 var cj = add(c[j] || 0, abs(value));
39190
39191 if (larger(cj, maxc)) {
39192 maxc = cj;
39193 }
39194
39195 c[j] = cj;
39196 }, true);
39197 return maxc;
39198 }
39199
39200 if (p === Number.POSITIVE_INFINITY || p === 'inf') {
39201 // norm(x) = the largest row sum
39202 var r = []; // result
39203
39204 var maxr = 0; // skip zeros since abs(0) == 0
39205
39206 x.forEach(function (value, index) {
39207 var i = index[0];
39208 var ri = add(r[i] || 0, abs(value));
39209
39210 if (larger(ri, maxr)) {
39211 maxr = ri;
39212 }
39213
39214 r[i] = ri;
39215 }, true);
39216 return maxr;
39217 }
39218
39219 if (p === 'fro') {
39220 // norm(x) = sqrt(sum(diag(x'x)))
39221 var fro = 0;
39222 x.forEach(function (value, index) {
39223 fro = add(fro, multiply(value, conj(value)));
39224 });
39225 return abs(sqrt(fro));
39226 }
39227
39228 if (p === 2) {
39229 // not implemented
39230 throw new Error('Unsupported parameter value, missing implementation of matrix singular value decomposition');
39231 } // invalid parameter value
39232
39233
39234 throw new Error('Unsupported parameter value');
39235 }
39236 }
39237
39238 return norm;
39239});
39240// CONCATENATED MODULE: ./src/function/matrix/dot.js
39241
39242
39243var dot_name = 'dot';
39244var dot_dependencies = ['typed', 'add', 'multiply'];
39245var createDot =
39246/* #__PURE__ */
39247Object(factory["a" /* factory */])(dot_name, dot_dependencies, function (_ref) {
39248 var typed = _ref.typed,
39249 add = _ref.add,
39250 multiply = _ref.multiply;
39251
39252 /**
39253 * Calculate the dot product of two vectors. The dot product of
39254 * `A = [a1, a2, a3, ..., an]` and `B = [b1, b2, b3, ..., bn]` is defined as:
39255 *
39256 * dot(A, B) = a1 * b1 + a2 * b2 + a3 * b3 + ... + an * bn
39257 *
39258 * Syntax:
39259 *
39260 * math.dot(x, y)
39261 *
39262 * Examples:
39263 *
39264 * math.dot([2, 4, 1], [2, 2, 3]) // returns number 15
39265 * math.multiply([2, 4, 1], [2, 2, 3]) // returns number 15
39266 *
39267 * See also:
39268 *
39269 * multiply, cross
39270 *
39271 * @param {Array | Matrix} x First vector
39272 * @param {Array | Matrix} y Second vector
39273 * @return {number} Returns the dot product of `x` and `y`
39274 */
39275 return typed(dot_name, {
39276 'Matrix, Matrix': function MatrixMatrix(x, y) {
39277 return _dot(x.toArray(), y.toArray());
39278 },
39279 'Matrix, Array': function MatrixArray(x, y) {
39280 return _dot(x.toArray(), y);
39281 },
39282 'Array, Matrix': function ArrayMatrix(x, y) {
39283 return _dot(x, y.toArray());
39284 },
39285 'Array, Array': _dot
39286 });
39287 /**
39288 * Calculate the dot product for two arrays
39289 * @param {Array} x First vector
39290 * @param {Array} y Second vector
39291 * @returns {number} Returns the dot product of x and y
39292 * @private
39293 */
39294 // TODO: double code with math.multiply
39295
39296 function _dot(x, y) {
39297 var xSize = Object(utils_array["a" /* arraySize */])(x);
39298 var ySize = Object(utils_array["a" /* arraySize */])(y);
39299 var len = xSize[0];
39300 if (xSize.length !== 1 || ySize.length !== 1) throw new RangeError('Vector expected'); // TODO: better error message
39301
39302 if (xSize[0] !== ySize[0]) throw new RangeError('Vectors must have equal length (' + xSize[0] + ' != ' + ySize[0] + ')');
39303 if (len === 0) throw new RangeError('Cannot calculate the dot product of empty vectors');
39304 var prod = 0;
39305
39306 for (var i = 0; i < len; i++) {
39307 prod = add(prod, multiply(x[i], y[i]));
39308 }
39309
39310 return prod;
39311 }
39312});
39313// CONCATENATED MODULE: ./src/function/matrix/trace.js
39314
39315
39316
39317var trace_name = 'trace';
39318var trace_dependencies = ['typed', 'matrix', 'add'];
39319var createTrace =
39320/* #__PURE__ */
39321Object(factory["a" /* factory */])(trace_name, trace_dependencies, function (_ref) {
39322 var typed = _ref.typed,
39323 matrix = _ref.matrix,
39324 add = _ref.add;
39325
39326 /**
39327 * Calculate the trace of a matrix: the sum of the elements on the main
39328 * diagonal of a square matrix.
39329 *
39330 * Syntax:
39331 *
39332 * math.trace(x)
39333 *
39334 * Examples:
39335 *
39336 * math.trace([[1, 2], [3, 4]]) // returns 5
39337 *
39338 * const A = [
39339 * [1, 2, 3],
39340 * [-1, 2, 3],
39341 * [2, 0, 3]
39342 * ]
39343 * math.trace(A) // returns 6
39344 *
39345 * See also:
39346 *
39347 * diag
39348 *
39349 * @param {Array | Matrix} x A matrix
39350 *
39351 * @return {number} The trace of `x`
39352 */
39353 return typed('trace', {
39354 Array: function _arrayTrace(x) {
39355 // use dense matrix implementation
39356 return _denseTrace(matrix(x));
39357 },
39358 SparseMatrix: _sparseTrace,
39359 DenseMatrix: _denseTrace,
39360 any: utils_object["a" /* clone */]
39361 });
39362
39363 function _denseTrace(m) {
39364 // matrix size & data
39365 var size = m._size;
39366 var data = m._data; // process dimensions
39367
39368 switch (size.length) {
39369 case 1:
39370 // vector
39371 if (size[0] === 1) {
39372 // return data[0]
39373 return Object(utils_object["a" /* clone */])(data[0]);
39374 }
39375
39376 throw new RangeError('Matrix must be square (size: ' + Object(utils_string["d" /* format */])(size) + ')');
39377
39378 case 2:
39379 {
39380 // two dimensional
39381 var rows = size[0];
39382 var cols = size[1];
39383
39384 if (rows === cols) {
39385 // calulate sum
39386 var sum = 0; // loop diagonal
39387
39388 for (var i = 0; i < rows; i++) {
39389 sum = add(sum, data[i][i]);
39390 } // return trace
39391
39392
39393 return sum;
39394 } else {
39395 throw new RangeError('Matrix must be square (size: ' + Object(utils_string["d" /* format */])(size) + ')');
39396 }
39397 }
39398
39399 default:
39400 // multi dimensional
39401 throw new RangeError('Matrix must be two dimensional (size: ' + Object(utils_string["d" /* format */])(size) + ')');
39402 }
39403 }
39404
39405 function _sparseTrace(m) {
39406 // matrix arrays
39407 var values = m._values;
39408 var index = m._index;
39409 var ptr = m._ptr;
39410 var size = m._size; // check dimensions
39411
39412 var rows = size[0];
39413 var columns = size[1]; // matrix must be square
39414
39415 if (rows === columns) {
39416 // calulate sum
39417 var sum = 0; // check we have data (avoid looping columns)
39418
39419 if (values.length > 0) {
39420 // loop columns
39421 for (var j = 0; j < columns; j++) {
39422 // k0 <= k < k1 where k0 = _ptr[j] && k1 = _ptr[j+1]
39423 var k0 = ptr[j];
39424 var k1 = ptr[j + 1]; // loop k within [k0, k1[
39425
39426 for (var k = k0; k < k1; k++) {
39427 // row index
39428 var i = index[k]; // check row
39429
39430 if (i === j) {
39431 // accumulate value
39432 sum = add(sum, values[k]); // exit loop
39433
39434 break;
39435 }
39436
39437 if (i > j) {
39438 // exit loop, no value on the diagonal for column j
39439 break;
39440 }
39441 }
39442 }
39443 } // return trace
39444
39445
39446 return sum;
39447 }
39448
39449 throw new RangeError('Matrix must be square (size: ' + Object(utils_string["d" /* format */])(size) + ')');
39450 }
39451});
39452// CONCATENATED MODULE: ./src/type/matrix/function/index.js
39453
39454
39455var function_name = 'index';
39456var function_dependencies = ['typed', 'Index'];
39457var createIndex =
39458/* #__PURE__ */
39459Object(factory["a" /* factory */])(function_name, function_dependencies, function (_ref) {
39460 var typed = _ref.typed,
39461 Index = _ref.Index;
39462
39463 /**
39464 * Create an index. An Index can store ranges having start, step, and end
39465 * for multiple dimensions.
39466 * Matrix.get, Matrix.set, and math.subset accept an Index as input.
39467 *
39468 * Syntax:
39469 *
39470 * math.index(range1, range2, ...)
39471 *
39472 * Where each range can be any of:
39473 *
39474 * - A number
39475 * - A string for getting/setting an object property
39476 * - An instance of `Range`
39477 * - A one-dimensional Array or a Matrix with numbers
39478 *
39479 * Indexes must be zero-based, integer numbers.
39480 *
39481 * Examples:
39482 *
39483 * const b = [1, 2, 3, 4, 5]
39484 * math.subset(b, math.index([1, 2, 3])) // returns [2, 3, 4]
39485 *
39486 * const a = math.matrix([[1, 2], [3, 4]])
39487 * a.subset(math.index(0, 1)) // returns 2
39488 *
39489 * See also:
39490 *
39491 * bignumber, boolean, complex, matrix, number, string, unit
39492 *
39493 * @param {...*} ranges Zero or more ranges or numbers.
39494 * @return {Index} Returns the created index
39495 */
39496 return typed(function_name, {
39497 '...number | string | BigNumber | Range | Array | Matrix': function numberStringBigNumberRangeArrayMatrix(args) {
39498 var ranges = args.map(function (arg) {
39499 if (Object(is["e" /* isBigNumber */])(arg)) {
39500 return arg.toNumber(); // convert BigNumber to Number
39501 } else if (Array.isArray(arg) || Object(is["v" /* isMatrix */])(arg)) {
39502 return arg.map(function (elem) {
39503 // convert BigNumber to Number
39504 return Object(is["e" /* isBigNumber */])(elem) ? elem.toNumber() : elem;
39505 });
39506 } else {
39507 return arg;
39508 }
39509 });
39510 var res = new Index();
39511 Index.apply(res, ranges);
39512 return res;
39513 }
39514 });
39515});
39516// CONCATENATED MODULE: ./src/expression/keywords.js
39517// Reserved keywords not allowed to use in the parser
39518var keywords = {
39519 end: true
39520};
39521// CONCATENATED MODULE: ./src/expression/node/Node.js
39522function Node_typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { Node_typeof = function _typeof(obj) { return typeof obj; }; } else { Node_typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return Node_typeof(obj); }
39523
39524
39525
39526
39527
39528
39529var Node_name = 'Node';
39530var Node_dependencies = ['mathWithTransform'];
39531var createNode =
39532/* #__PURE__ */
39533Object(factory["a" /* factory */])(Node_name, Node_dependencies, function (_ref) {
39534 var mathWithTransform = _ref.mathWithTransform;
39535
39536 /**
39537 * Node
39538 */
39539 function Node() {
39540 if (!(this instanceof Node)) {
39541 throw new SyntaxError('Constructor must be called with the new operator');
39542 }
39543 }
39544 /**
39545 * Evaluate the node
39546 * @param {Object} [scope] Scope to read/write variables
39547 * @return {*} Returns the result
39548 */
39549
39550
39551 Node.prototype.evaluate = function (scope) {
39552 return this.compile().evaluate(scope);
39553 };
39554 /**
39555 * Evaluate the node
39556 * @param {Object} [scope] Scope to read/write variables
39557 * @return {*} Returns the result
39558 */
39559 // TODO: Deprecated since v6.0.0. Clean up some day
39560
39561
39562 Node.prototype.eval = function (scope) {
39563 Object(utils_log["a" /* warnOnce */])('Method Node.eval is renamed to Node.evaluate. Please use the new method name.');
39564 return this.evaluate(scope);
39565 };
39566
39567 Node.prototype.type = 'Node';
39568 Node.prototype.isNode = true;
39569 Node.prototype.comment = '';
39570 /**
39571 * Compile the node into an optimized, evauatable JavaScript function
39572 * @return {{evaluate: function([Object])}} object
39573 * Returns an object with a function 'evaluate',
39574 * which can be invoked as expr.evaluate([scope: Object]),
39575 * where scope is an optional object with
39576 * variables.
39577 */
39578
39579 Node.prototype.compile = function () {
39580 var expr = this._compile(mathWithTransform, {});
39581
39582 var args = {};
39583 var context = null;
39584
39585 function evaluate(scope) {
39586 var s = scope || {};
39587
39588 _validateScope(s);
39589
39590 return expr(s, args, context);
39591 }
39592
39593 return {
39594 evaluate: evaluate,
39595 // TODO: Deprecated since v6.0.0. Clean up some day
39596 eval: function deprecatedEval(scope) {
39597 Object(utils_log["a" /* warnOnce */])('Method eval is renamed to evaluate. Please use the new method.');
39598 return evaluate(scope);
39599 }
39600 };
39601 };
39602 /**
39603 * Compile a node into a JavaScript function.
39604 * This basically pre-calculates as much as possible and only leaves open
39605 * calculations which depend on a dynamic scope with variables.
39606 * @param {Object} math Math.js namespace with functions and constants.
39607 * @param {Object} argNames An object with argument names as key and `true`
39608 * as value. Used in the SymbolNode to optimize
39609 * for arguments from user assigned functions
39610 * (see FunctionAssignmentNode) or special symbols
39611 * like `end` (see IndexNode).
39612 * @return {function} Returns a function which can be called like:
39613 * evalNode(scope: Object, args: Object, context: *)
39614 */
39615
39616
39617 Node.prototype._compile = function (math, argNames) {
39618 throw new Error('Method _compile should be implemented by type ' + this.type);
39619 };
39620 /**
39621 * Execute a callback for each of the child nodes of this node
39622 * @param {function(child: Node, path: string, parent: Node)} callback
39623 */
39624
39625
39626 Node.prototype.forEach = function (callback) {
39627 // must be implemented by each of the Node implementations
39628 throw new Error('Cannot run forEach on a Node interface');
39629 };
39630 /**
39631 * Create a new Node having it's childs be the results of calling
39632 * the provided callback function for each of the childs of the original node.
39633 * @param {function(child: Node, path: string, parent: Node): Node} callback
39634 * @returns {OperatorNode} Returns a transformed copy of the node
39635 */
39636
39637
39638 Node.prototype.map = function (callback) {
39639 // must be implemented by each of the Node implementations
39640 throw new Error('Cannot run map on a Node interface');
39641 };
39642 /**
39643 * Validate whether an object is a Node, for use with map
39644 * @param {Node} node
39645 * @returns {Node} Returns the input if it's a node, else throws an Error
39646 * @protected
39647 */
39648
39649
39650 Node.prototype._ifNode = function (node) {
39651 if (!Object(is["w" /* isNode */])(node)) {
39652 throw new TypeError('Callback function must return a Node');
39653 }
39654
39655 return node;
39656 };
39657 /**
39658 * Recursively traverse all nodes in a node tree. Executes given callback for
39659 * this node and each of its child nodes.
39660 * @param {function(node: Node, path: string, parent: Node)} callback
39661 * A callback called for every node in the node tree.
39662 */
39663
39664
39665 Node.prototype.traverse = function (callback) {
39666 // execute callback for itself
39667 callback(this, null, null); // eslint-disable-line standard/no-callback-literal
39668 // recursively traverse over all childs of a node
39669
39670 function _traverse(node, callback) {
39671 node.forEach(function (child, path, parent) {
39672 callback(child, path, parent);
39673
39674 _traverse(child, callback);
39675 });
39676 }
39677
39678 _traverse(this, callback);
39679 };
39680 /**
39681 * Recursively transform a node tree via a transform function.
39682 *
39683 * For example, to replace all nodes of type SymbolNode having name 'x' with a
39684 * ConstantNode with value 2:
39685 *
39686 * const res = Node.transform(function (node, path, parent) {
39687 * if (node && node.isSymbolNode) && (node.name === 'x')) {
39688 * return new ConstantNode(2)
39689 * }
39690 * else {
39691 * return node
39692 * }
39693 * })
39694 *
39695 * @param {function(node: Node, path: string, parent: Node) : Node} callback
39696 * A mapping function accepting a node, and returning
39697 * a replacement for the node or the original node.
39698 * Signature: callback(node: Node, index: string, parent: Node) : Node
39699 * @return {Node} Returns the original node or its replacement
39700 */
39701
39702
39703 Node.prototype.transform = function (callback) {
39704 function _transform(child, path, parent) {
39705 var replacement = callback(child, path, parent);
39706
39707 if (replacement !== child) {
39708 // stop iterating when the node is replaced
39709 return replacement;
39710 }
39711
39712 return child.map(_transform);
39713 }
39714
39715 return _transform(this, null, null);
39716 };
39717 /**
39718 * Find any node in the node tree matching given filter function. For example, to
39719 * find all nodes of type SymbolNode having name 'x':
39720 *
39721 * const results = Node.filter(function (node) {
39722 * return (node && node.isSymbolNode) && (node.name === 'x')
39723 * })
39724 *
39725 * @param {function(node: Node, path: string, parent: Node) : Node} callback
39726 * A test function returning true when a node matches, and false
39727 * otherwise. Function signature:
39728 * callback(node: Node, index: string, parent: Node) : boolean
39729 * @return {Node[]} nodes An array with nodes matching given filter criteria
39730 */
39731
39732
39733 Node.prototype.filter = function (callback) {
39734 var nodes = [];
39735 this.traverse(function (node, path, parent) {
39736 if (callback(node, path, parent)) {
39737 nodes.push(node);
39738 }
39739 });
39740 return nodes;
39741 }; // TODO: deprecated since version 1.1.0, remove this some day
39742
39743
39744 Node.prototype.find = function () {
39745 throw new Error('Function Node.find is deprecated. Use Node.filter instead.');
39746 }; // TODO: deprecated since version 1.1.0, remove this some day
39747
39748
39749 Node.prototype.match = function () {
39750 throw new Error('Function Node.match is deprecated. See functions Node.filter, Node.transform, Node.traverse.');
39751 };
39752 /**
39753 * Create a shallow clone of this node
39754 * @return {Node}
39755 */
39756
39757
39758 Node.prototype.clone = function () {
39759 // must be implemented by each of the Node implementations
39760 throw new Error('Cannot clone a Node interface');
39761 };
39762 /**
39763 * Create a deep clone of this node
39764 * @return {Node}
39765 */
39766
39767
39768 Node.prototype.cloneDeep = function () {
39769 return this.map(function (node) {
39770 return node.cloneDeep();
39771 });
39772 };
39773 /**
39774 * Deep compare this node with another node.
39775 * @param {Node} other
39776 * @return {boolean} Returns true when both nodes are of the same type and
39777 * contain the same values (as do their childs)
39778 */
39779
39780
39781 Node.prototype.equals = function (other) {
39782 return other ? Object(utils_object["d" /* deepStrictEqual */])(this, other) : false;
39783 };
39784 /**
39785 * Get string representation. (wrapper function)
39786 *
39787 * This function can get an object of the following form:
39788 * {
39789 * handler: //This can be a callback function of the form
39790 * // "function callback(node, options)"or
39791 * // a map that maps function names (used in FunctionNodes)
39792 * // to callbacks
39793 * parenthesis: "keep" //the parenthesis option (This is optional)
39794 * }
39795 *
39796 * @param {Object} [options]
39797 * @return {string}
39798 */
39799
39800
39801 Node.prototype.toString = function (options) {
39802 var customString;
39803
39804 if (options && Node_typeof(options) === 'object') {
39805 switch (Node_typeof(options.handler)) {
39806 case 'object':
39807 case 'undefined':
39808 break;
39809
39810 case 'function':
39811 customString = options.handler(this, options);
39812 break;
39813
39814 default:
39815 throw new TypeError('Object or function expected as callback');
39816 }
39817 }
39818
39819 if (typeof customString !== 'undefined') {
39820 return customString;
39821 }
39822
39823 return this._toString(options);
39824 };
39825 /**
39826 * Get a JSON representation of the node
39827 * Both .toJSON() and the static .fromJSON(json) should be implemented by all
39828 * implementations of Node
39829 * @returns {Object}
39830 */
39831
39832
39833 Node.prototype.toJSON = function () {
39834 throw new Error('Cannot serialize object: toJSON not implemented by ' + this.type);
39835 };
39836 /**
39837 * Get HTML representation. (wrapper function)
39838 *
39839 * This function can get an object of the following form:
39840 * {
39841 * handler: //This can be a callback function of the form
39842 * // "function callback(node, options)" or
39843 * // a map that maps function names (used in FunctionNodes)
39844 * // to callbacks
39845 * parenthesis: "keep" //the parenthesis option (This is optional)
39846 * }
39847 *
39848 * @param {Object} [options]
39849 * @return {string}
39850 */
39851
39852
39853 Node.prototype.toHTML = function (options) {
39854 var customString;
39855
39856 if (options && Node_typeof(options) === 'object') {
39857 switch (Node_typeof(options.handler)) {
39858 case 'object':
39859 case 'undefined':
39860 break;
39861
39862 case 'function':
39863 customString = options.handler(this, options);
39864 break;
39865
39866 default:
39867 throw new TypeError('Object or function expected as callback');
39868 }
39869 }
39870
39871 if (typeof customString !== 'undefined') {
39872 return customString;
39873 }
39874
39875 return this.toHTML(options);
39876 };
39877 /**
39878 * Internal function to generate the string output.
39879 * This has to be implemented by every Node
39880 *
39881 * @throws {Error}
39882 */
39883
39884
39885 Node.prototype._toString = function () {
39886 // must be implemented by each of the Node implementations
39887 throw new Error('_toString not implemented for ' + this.type);
39888 };
39889 /**
39890 * Get LaTeX representation. (wrapper function)
39891 *
39892 * This function can get an object of the following form:
39893 * {
39894 * handler: //This can be a callback function of the form
39895 * // "function callback(node, options)"or
39896 * // a map that maps function names (used in FunctionNodes)
39897 * // to callbacks
39898 * parenthesis: "keep" //the parenthesis option (This is optional)
39899 * }
39900 *
39901 * @param {Object} [options]
39902 * @return {string}
39903 */
39904
39905
39906 Node.prototype.toTex = function (options) {
39907 var customTex;
39908
39909 if (options && Node_typeof(options) === 'object') {
39910 switch (Node_typeof(options.handler)) {
39911 case 'object':
39912 case 'undefined':
39913 break;
39914
39915 case 'function':
39916 customTex = options.handler(this, options);
39917 break;
39918
39919 default:
39920 throw new TypeError('Object or function expected as callback');
39921 }
39922 }
39923
39924 if (typeof customTex !== 'undefined') {
39925 return customTex;
39926 }
39927
39928 return this._toTex(options);
39929 };
39930 /**
39931 * Internal function to generate the LaTeX output.
39932 * This has to be implemented by every Node
39933 *
39934 * @param {Object} [options]
39935 * @throws {Error}
39936 */
39937
39938
39939 Node.prototype._toTex = function (options) {
39940 // must be implemented by each of the Node implementations
39941 throw new Error('_toTex not implemented for ' + this.type);
39942 };
39943 /**
39944 * Get identifier.
39945 * @return {string}
39946 */
39947
39948
39949 Node.prototype.getIdentifier = function () {
39950 return this.type;
39951 };
39952 /**
39953 * Get the content of the current Node.
39954 * @return {Node} node
39955 **/
39956
39957
39958 Node.prototype.getContent = function () {
39959 return this;
39960 };
39961 /**
39962 * Validate the symbol names of a scope.
39963 * Throws an error when the scope contains an illegal symbol.
39964 * @param {Object} scope
39965 */
39966
39967
39968 function _validateScope(scope) {
39969 for (var symbol in scope) {
39970 if (Object(utils_object["f" /* hasOwnProperty */])(scope, symbol)) {
39971 if (symbol in keywords) {
39972 throw new Error('Scope contains an illegal symbol, "' + symbol + '" is a reserved keyword');
39973 }
39974 }
39975 }
39976 }
39977
39978 return Node;
39979}, {
39980 isClass: true,
39981 isNode: true
39982});
39983// CONCATENATED MODULE: ./src/expression/transform/utils/errorTransform.js
39984
39985/**
39986 * Transform zero-based indices to one-based indices in errors
39987 * @param {Error} err
39988 * @returns {Error | IndexError} Returns the transformed error
39989 */
39990
39991function errorTransform(err) {
39992 if (err && err.isIndexError) {
39993 return new IndexError["a" /* IndexError */](err.index + 1, err.min + 1, err.max !== undefined ? err.max + 1 : undefined);
39994 }
39995
39996 return err;
39997}
39998// CONCATENATED MODULE: ./src/expression/node/utils/access.js
39999function access_typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { access_typeof = function _typeof(obj) { return typeof obj; }; } else { access_typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return access_typeof(obj); }
40000
40001
40002
40003function accessFactory(_ref) {
40004 var subset = _ref.subset;
40005
40006 /**
40007 * Retrieve part of an object:
40008 *
40009 * - Retrieve a property from an object
40010 * - Retrieve a part of a string
40011 * - Retrieve a matrix subset
40012 *
40013 * @param {Object | Array | Matrix | string} object
40014 * @param {Index} index
40015 * @return {Object | Array | Matrix | string} Returns the subset
40016 */
40017 return function access(object, index) {
40018 try {
40019 if (Array.isArray(object)) {
40020 return subset(object, index);
40021 } else if (object && typeof object.subset === 'function') {
40022 // Matrix
40023 return object.subset(index);
40024 } else if (typeof object === 'string') {
40025 // TODO: move getStringSubset into a separate util file, use that
40026 return subset(object, index);
40027 } else if (access_typeof(object) === 'object') {
40028 if (!index.isObjectProperty()) {
40029 throw new TypeError('Cannot apply a numeric index as object property');
40030 }
40031
40032 return getSafeProperty(object, index.getObjectProperty());
40033 } else {
40034 throw new TypeError('Cannot apply index: unsupported type of object');
40035 }
40036 } catch (err) {
40037 throw errorTransform(err);
40038 }
40039 };
40040}
40041// CONCATENATED MODULE: ./src/expression/node/AccessorNode.js
40042
40043
40044
40045
40046var AccessorNode_name = 'AccessorNode';
40047var AccessorNode_dependencies = ['subset', 'Node'];
40048var createAccessorNode =
40049/* #__PURE__ */
40050Object(factory["a" /* factory */])(AccessorNode_name, AccessorNode_dependencies, function (_ref) {
40051 var subset = _ref.subset,
40052 Node = _ref.Node;
40053 var access = accessFactory({
40054 subset: subset
40055 });
40056 /**
40057 * @constructor AccessorNode
40058 * @extends {Node}
40059 * Access an object property or get a matrix subset
40060 *
40061 * @param {Node} object The object from which to retrieve
40062 * a property or subset.
40063 * @param {IndexNode} index IndexNode containing ranges
40064 */
40065
40066 function AccessorNode(object, index) {
40067 if (!(this instanceof AccessorNode)) {
40068 throw new SyntaxError('Constructor must be called with the new operator');
40069 }
40070
40071 if (!Object(is["w" /* isNode */])(object)) {
40072 throw new TypeError('Node expected for parameter "object"');
40073 }
40074
40075 if (!Object(is["u" /* isIndexNode */])(index)) {
40076 throw new TypeError('IndexNode expected for parameter "index"');
40077 }
40078
40079 this.object = object || null;
40080 this.index = index; // readonly property name
40081
40082 Object.defineProperty(this, 'name', {
40083 get: function () {
40084 if (this.index) {
40085 return this.index.isObjectProperty() ? this.index.getObjectProperty() : '';
40086 } else {
40087 return this.object.name || '';
40088 }
40089 }.bind(this),
40090 set: function set() {
40091 throw new Error('Cannot assign a new name, name is read-only');
40092 }
40093 });
40094 }
40095
40096 AccessorNode.prototype = new Node();
40097 AccessorNode.prototype.type = 'AccessorNode';
40098 AccessorNode.prototype.isAccessorNode = true;
40099 /**
40100 * Compile a node into a JavaScript function.
40101 * This basically pre-calculates as much as possible and only leaves open
40102 * calculations which depend on a dynamic scope with variables.
40103 * @param {Object} math Math.js namespace with functions and constants.
40104 * @param {Object} argNames An object with argument names as key and `true`
40105 * as value. Used in the SymbolNode to optimize
40106 * for arguments from user assigned functions
40107 * (see FunctionAssignmentNode) or special symbols
40108 * like `end` (see IndexNode).
40109 * @return {function} Returns a function which can be called like:
40110 * evalNode(scope: Object, args: Object, context: *)
40111 */
40112
40113 AccessorNode.prototype._compile = function (math, argNames) {
40114 var evalObject = this.object._compile(math, argNames);
40115
40116 var evalIndex = this.index._compile(math, argNames);
40117
40118 if (this.index.isObjectProperty()) {
40119 var prop = this.index.getObjectProperty();
40120 return function evalAccessorNode(scope, args, context) {
40121 return getSafeProperty(evalObject(scope, args, context), prop);
40122 };
40123 } else {
40124 return function evalAccessorNode(scope, args, context) {
40125 var object = evalObject(scope, args, context);
40126 var index = evalIndex(scope, args, object); // we pass object here instead of context
40127
40128 return access(object, index);
40129 };
40130 }
40131 };
40132 /**
40133 * Execute a callback for each of the child nodes of this node
40134 * @param {function(child: Node, path: string, parent: Node)} callback
40135 */
40136
40137
40138 AccessorNode.prototype.forEach = function (callback) {
40139 callback(this.object, 'object', this);
40140 callback(this.index, 'index', this);
40141 };
40142 /**
40143 * Create a new AccessorNode having it's childs be the results of calling
40144 * the provided callback function for each of the childs of the original node.
40145 * @param {function(child: Node, path: string, parent: Node): Node} callback
40146 * @returns {AccessorNode} Returns a transformed copy of the node
40147 */
40148
40149
40150 AccessorNode.prototype.map = function (callback) {
40151 return new AccessorNode(this._ifNode(callback(this.object, 'object', this)), this._ifNode(callback(this.index, 'index', this)));
40152 };
40153 /**
40154 * Create a clone of this node, a shallow copy
40155 * @return {AccessorNode}
40156 */
40157
40158
40159 AccessorNode.prototype.clone = function () {
40160 return new AccessorNode(this.object, this.index);
40161 };
40162 /**
40163 * Get string representation
40164 * @param {Object} options
40165 * @return {string}
40166 */
40167
40168
40169 AccessorNode.prototype._toString = function (options) {
40170 var object = this.object.toString(options);
40171
40172 if (needParenthesis(this.object)) {
40173 object = '(' + object + ')';
40174 }
40175
40176 return object + this.index.toString(options);
40177 };
40178 /**
40179 * Get HTML representation
40180 * @param {Object} options
40181 * @return {string}
40182 */
40183
40184
40185 AccessorNode.prototype.toHTML = function (options) {
40186 var object = this.object.toHTML(options);
40187
40188 if (needParenthesis(this.object)) {
40189 object = '<span class="math-parenthesis math-round-parenthesis">(</span>' + object + '<span class="math-parenthesis math-round-parenthesis">)</span>';
40190 }
40191
40192 return object + this.index.toHTML(options);
40193 };
40194 /**
40195 * Get LaTeX representation
40196 * @param {Object} options
40197 * @return {string}
40198 */
40199
40200
40201 AccessorNode.prototype._toTex = function (options) {
40202 var object = this.object.toTex(options);
40203
40204 if (needParenthesis(this.object)) {
40205 object = '\\left(\' + object + \'\\right)';
40206 }
40207
40208 return object + this.index.toTex(options);
40209 };
40210 /**
40211 * Get a JSON representation of the node
40212 * @returns {Object}
40213 */
40214
40215
40216 AccessorNode.prototype.toJSON = function () {
40217 return {
40218 mathjs: 'AccessorNode',
40219 object: this.object,
40220 index: this.index
40221 };
40222 };
40223 /**
40224 * Instantiate an AccessorNode from its JSON representation
40225 * @param {Object} json An object structured like
40226 * `{"mathjs": "AccessorNode", object: ..., index: ...}`,
40227 * where mathjs is optional
40228 * @returns {AccessorNode}
40229 */
40230
40231
40232 AccessorNode.fromJSON = function (json) {
40233 return new AccessorNode(json.object, json.index);
40234 };
40235 /**
40236 * Are parenthesis needed?
40237 * @private
40238 */
40239
40240
40241 function needParenthesis(node) {
40242 // TODO: maybe make a method on the nodes which tells whether they need parenthesis?
40243 return !(Object(is["a" /* isAccessorNode */])(node) || Object(is["c" /* isArrayNode */])(node) || Object(is["l" /* isConstantNode */])(node) || Object(is["r" /* isFunctionNode */])(node) || Object(is["A" /* isObjectNode */])(node) || Object(is["C" /* isParenthesisNode */])(node) || Object(is["J" /* isSymbolNode */])(node));
40244 }
40245
40246 return AccessorNode;
40247}, {
40248 isClass: true,
40249 isNode: true
40250});
40251// CONCATENATED MODULE: ./src/expression/node/ArrayNode.js
40252
40253
40254
40255var ArrayNode_name = 'ArrayNode';
40256var ArrayNode_dependencies = ['Node'];
40257var createArrayNode =
40258/* #__PURE__ */
40259Object(factory["a" /* factory */])(ArrayNode_name, ArrayNode_dependencies, function (_ref) {
40260 var Node = _ref.Node;
40261
40262 /**
40263 * @constructor ArrayNode
40264 * @extends {Node}
40265 * Holds an 1-dimensional array with items
40266 * @param {Node[]} [items] 1 dimensional array with items
40267 */
40268 function ArrayNode(items) {
40269 if (!(this instanceof ArrayNode)) {
40270 throw new SyntaxError('Constructor must be called with the new operator');
40271 }
40272
40273 this.items = items || []; // validate input
40274
40275 if (!Array.isArray(this.items) || !this.items.every(is["w" /* isNode */])) {
40276 throw new TypeError('Array containing Nodes expected');
40277 } // TODO: deprecated since v3, remove some day
40278
40279
40280 var deprecated = function deprecated() {
40281 throw new Error('Property `ArrayNode.nodes` is deprecated, use `ArrayNode.items` instead');
40282 };
40283
40284 Object.defineProperty(this, 'nodes', {
40285 get: deprecated,
40286 set: deprecated
40287 });
40288 }
40289
40290 ArrayNode.prototype = new Node();
40291 ArrayNode.prototype.type = 'ArrayNode';
40292 ArrayNode.prototype.isArrayNode = true;
40293 /**
40294 * Compile a node into a JavaScript function.
40295 * This basically pre-calculates as much as possible and only leaves open
40296 * calculations which depend on a dynamic scope with variables.
40297 * @param {Object} math Math.js namespace with functions and constants.
40298 * @param {Object} argNames An object with argument names as key and `true`
40299 * as value. Used in the SymbolNode to optimize
40300 * for arguments from user assigned functions
40301 * (see FunctionAssignmentNode) or special symbols
40302 * like `end` (see IndexNode).
40303 * @return {function} Returns a function which can be called like:
40304 * evalNode(scope: Object, args: Object, context: *)
40305 */
40306
40307 ArrayNode.prototype._compile = function (math, argNames) {
40308 var evalItems = Object(utils_array["m" /* map */])(this.items, function (item) {
40309 return item._compile(math, argNames);
40310 });
40311 var asMatrix = math.config.matrix !== 'Array';
40312
40313 if (asMatrix) {
40314 var matrix = math.matrix;
40315 return function evalArrayNode(scope, args, context) {
40316 return matrix(Object(utils_array["m" /* map */])(evalItems, function (evalItem) {
40317 return evalItem(scope, args, context);
40318 }));
40319 };
40320 } else {
40321 return function evalArrayNode(scope, args, context) {
40322 return Object(utils_array["m" /* map */])(evalItems, function (evalItem) {
40323 return evalItem(scope, args, context);
40324 });
40325 };
40326 }
40327 };
40328 /**
40329 * Execute a callback for each of the child nodes of this node
40330 * @param {function(child: Node, path: string, parent: Node)} callback
40331 */
40332
40333
40334 ArrayNode.prototype.forEach = function (callback) {
40335 for (var i = 0; i < this.items.length; i++) {
40336 var node = this.items[i];
40337 callback(node, 'items[' + i + ']', this);
40338 }
40339 };
40340 /**
40341 * Create a new ArrayNode having it's childs be the results of calling
40342 * the provided callback function for each of the childs of the original node.
40343 * @param {function(child: Node, path: string, parent: Node): Node} callback
40344 * @returns {ArrayNode} Returns a transformed copy of the node
40345 */
40346
40347
40348 ArrayNode.prototype.map = function (callback) {
40349 var items = [];
40350
40351 for (var i = 0; i < this.items.length; i++) {
40352 items[i] = this._ifNode(callback(this.items[i], 'items[' + i + ']', this));
40353 }
40354
40355 return new ArrayNode(items);
40356 };
40357 /**
40358 * Create a clone of this node, a shallow copy
40359 * @return {ArrayNode}
40360 */
40361
40362
40363 ArrayNode.prototype.clone = function () {
40364 return new ArrayNode(this.items.slice(0));
40365 };
40366 /**
40367 * Get string representation
40368 * @param {Object} options
40369 * @return {string} str
40370 * @override
40371 */
40372
40373
40374 ArrayNode.prototype._toString = function (options) {
40375 var items = this.items.map(function (node) {
40376 return node.toString(options);
40377 });
40378 return '[' + items.join(', ') + ']';
40379 };
40380 /**
40381 * Get a JSON representation of the node
40382 * @returns {Object}
40383 */
40384
40385
40386 ArrayNode.prototype.toJSON = function () {
40387 return {
40388 mathjs: 'ArrayNode',
40389 items: this.items
40390 };
40391 };
40392 /**
40393 * Instantiate an ArrayNode from its JSON representation
40394 * @param {Object} json An object structured like
40395 * `{"mathjs": "ArrayNode", items: [...]}`,
40396 * where mathjs is optional
40397 * @returns {ArrayNode}
40398 */
40399
40400
40401 ArrayNode.fromJSON = function (json) {
40402 return new ArrayNode(json.items);
40403 };
40404 /**
40405 * Get HTML representation
40406 * @param {Object} options
40407 * @return {string} str
40408 * @override
40409 */
40410
40411
40412 ArrayNode.prototype.toHTML = function (options) {
40413 var items = this.items.map(function (node) {
40414 return node.toHTML(options);
40415 });
40416 return '<span class="math-parenthesis math-square-parenthesis">[</span>' + items.join('<span class="math-separator">,</span>') + '<span class="math-parenthesis math-square-parenthesis">]</span>';
40417 };
40418 /**
40419 * Get LaTeX representation
40420 * @param {Object} options
40421 * @return {string} str
40422 */
40423
40424
40425 ArrayNode.prototype._toTex = function (options) {
40426 var s = '\\begin{bmatrix}';
40427 this.items.forEach(function (node) {
40428 if (node.items) {
40429 s += node.items.map(function (childNode) {
40430 return childNode.toTex(options);
40431 }).join('&');
40432 } else {
40433 s += node.toTex(options);
40434 } // new line
40435
40436
40437 s += '\\\\';
40438 });
40439 s += '\\end{bmatrix}';
40440 return s;
40441 };
40442
40443 return ArrayNode;
40444}, {
40445 isClass: true,
40446 isNode: true
40447});
40448// CONCATENATED MODULE: ./src/expression/node/utils/assign.js
40449function assign_typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { assign_typeof = function _typeof(obj) { return typeof obj; }; } else { assign_typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return assign_typeof(obj); }
40450
40451
40452
40453function assignFactory(_ref) {
40454 var subset = _ref.subset,
40455 matrix = _ref.matrix;
40456
40457 /**
40458 * Replace part of an object:
40459 *
40460 * - Assign a property to an object
40461 * - Replace a part of a string
40462 * - Replace a matrix subset
40463 *
40464 * @param {Object | Array | Matrix | string} object
40465 * @param {Index} index
40466 * @param {*} value
40467 * @return {Object | Array | Matrix | string} Returns the original object
40468 * except in case of a string
40469 */
40470 // TODO: change assign to return the value instead of the object
40471 return function assign(object, index, value) {
40472 try {
40473 if (Array.isArray(object)) {
40474 // we use matrix.subset here instead of the function subset because we must not clone the contents
40475 return matrix(object).subset(index, value).valueOf();
40476 } else if (object && typeof object.subset === 'function') {
40477 // Matrix
40478 return object.subset(index, value);
40479 } else if (typeof object === 'string') {
40480 // TODO: move setStringSubset into a separate util file, use that
40481 return subset(object, index, value);
40482 } else if (assign_typeof(object) === 'object') {
40483 if (!index.isObjectProperty()) {
40484 throw TypeError('Cannot apply a numeric index as object property');
40485 }
40486
40487 setSafeProperty(object, index.getObjectProperty(), value);
40488 return object;
40489 } else {
40490 throw new TypeError('Cannot apply index: unsupported type of object');
40491 }
40492 } catch (err) {
40493 throw errorTransform(err);
40494 }
40495 };
40496}
40497// CONCATENATED MODULE: ./src/expression/operators.js
40498// list of identifiers of nodes in order of their precedence
40499// also contains information about left/right associativity
40500// and which other operator the operator is associative with
40501// Example:
40502// addition is associative with addition and subtraction, because:
40503// (a+b)+c=a+(b+c)
40504// (a+b)-c=a+(b-c)
40505//
40506// postfix operators are left associative, prefix operators
40507// are right associative
40508//
40509// It's also possible to set the following properties:
40510// latexParens: if set to false, this node doesn't need to be enclosed
40511// in parentheses when using LaTeX
40512// latexLeftParens: if set to false, this !OperatorNode's!
40513// left argument doesn't need to be enclosed
40514// in parentheses
40515// latexRightParens: the same for the right argument
40516
40517var operators_properties = [{
40518 // assignment
40519 AssignmentNode: {},
40520 FunctionAssignmentNode: {}
40521}, {
40522 // conditional expression
40523 ConditionalNode: {
40524 latexLeftParens: false,
40525 latexRightParens: false,
40526 latexParens: false // conditionals don't need parentheses in LaTeX because
40527 // they are 2 dimensional
40528
40529 }
40530}, {
40531 // logical or
40532 'OperatorNode:or': {
40533 associativity: 'left',
40534 associativeWith: []
40535 }
40536}, {
40537 // logical xor
40538 'OperatorNode:xor': {
40539 associativity: 'left',
40540 associativeWith: []
40541 }
40542}, {
40543 // logical and
40544 'OperatorNode:and': {
40545 associativity: 'left',
40546 associativeWith: []
40547 }
40548}, {
40549 // bitwise or
40550 'OperatorNode:bitOr': {
40551 associativity: 'left',
40552 associativeWith: []
40553 }
40554}, {
40555 // bitwise xor
40556 'OperatorNode:bitXor': {
40557 associativity: 'left',
40558 associativeWith: []
40559 }
40560}, {
40561 // bitwise and
40562 'OperatorNode:bitAnd': {
40563 associativity: 'left',
40564 associativeWith: []
40565 }
40566}, {
40567 // relational operators
40568 'OperatorNode:equal': {
40569 associativity: 'left',
40570 associativeWith: []
40571 },
40572 'OperatorNode:unequal': {
40573 associativity: 'left',
40574 associativeWith: []
40575 },
40576 'OperatorNode:smaller': {
40577 associativity: 'left',
40578 associativeWith: []
40579 },
40580 'OperatorNode:larger': {
40581 associativity: 'left',
40582 associativeWith: []
40583 },
40584 'OperatorNode:smallerEq': {
40585 associativity: 'left',
40586 associativeWith: []
40587 },
40588 'OperatorNode:largerEq': {
40589 associativity: 'left',
40590 associativeWith: []
40591 },
40592 RelationalNode: {
40593 associativity: 'left',
40594 associativeWith: []
40595 }
40596}, {
40597 // bitshift operators
40598 'OperatorNode:leftShift': {
40599 associativity: 'left',
40600 associativeWith: []
40601 },
40602 'OperatorNode:rightArithShift': {
40603 associativity: 'left',
40604 associativeWith: []
40605 },
40606 'OperatorNode:rightLogShift': {
40607 associativity: 'left',
40608 associativeWith: []
40609 }
40610}, {
40611 // unit conversion
40612 'OperatorNode:to': {
40613 associativity: 'left',
40614 associativeWith: []
40615 }
40616}, {
40617 // range
40618 RangeNode: {}
40619}, {
40620 // addition, subtraction
40621 'OperatorNode:add': {
40622 associativity: 'left',
40623 associativeWith: ['OperatorNode:add', 'OperatorNode:subtract']
40624 },
40625 'OperatorNode:subtract': {
40626 associativity: 'left',
40627 associativeWith: []
40628 }
40629}, {
40630 // multiply, divide, modulus
40631 'OperatorNode:multiply': {
40632 associativity: 'left',
40633 associativeWith: ['OperatorNode:multiply', 'OperatorNode:divide', 'Operator:dotMultiply', 'Operator:dotDivide']
40634 },
40635 'OperatorNode:divide': {
40636 associativity: 'left',
40637 associativeWith: [],
40638 latexLeftParens: false,
40639 latexRightParens: false,
40640 latexParens: false // fractions don't require parentheses because
40641 // they're 2 dimensional, so parens aren't needed
40642 // in LaTeX
40643
40644 },
40645 'OperatorNode:dotMultiply': {
40646 associativity: 'left',
40647 associativeWith: ['OperatorNode:multiply', 'OperatorNode:divide', 'OperatorNode:dotMultiply', 'OperatorNode:doDivide']
40648 },
40649 'OperatorNode:dotDivide': {
40650 associativity: 'left',
40651 associativeWith: []
40652 },
40653 'OperatorNode:mod': {
40654 associativity: 'left',
40655 associativeWith: []
40656 }
40657}, {
40658 // unary prefix operators
40659 'OperatorNode:unaryPlus': {
40660 associativity: 'right'
40661 },
40662 'OperatorNode:unaryMinus': {
40663 associativity: 'right'
40664 },
40665 'OperatorNode:bitNot': {
40666 associativity: 'right'
40667 },
40668 'OperatorNode:not': {
40669 associativity: 'right'
40670 }
40671}, {
40672 // exponentiation
40673 'OperatorNode:pow': {
40674 associativity: 'right',
40675 associativeWith: [],
40676 latexRightParens: false // the exponent doesn't need parentheses in
40677 // LaTeX because it's 2 dimensional
40678 // (it's on top)
40679
40680 },
40681 'OperatorNode:dotPow': {
40682 associativity: 'right',
40683 associativeWith: []
40684 }
40685}, {
40686 // factorial
40687 'OperatorNode:factorial': {
40688 associativity: 'left'
40689 }
40690}, {
40691 // matrix transpose
40692 'OperatorNode:transpose': {
40693 associativity: 'left'
40694 }
40695}];
40696/**
40697 * Get the precedence of a Node.
40698 * Higher number for higher precedence, starting with 0.
40699 * Returns null if the precedence is undefined.
40700 *
40701 * @param {Node} _node
40702 * @param {string} parenthesis
40703 * @return {number | null}
40704 */
40705
40706function getPrecedence(_node, parenthesis) {
40707 var node = _node;
40708
40709 if (parenthesis !== 'keep') {
40710 // ParenthesisNodes are only ignored when not in 'keep' mode
40711 node = _node.getContent();
40712 }
40713
40714 var identifier = node.getIdentifier();
40715
40716 for (var i = 0; i < operators_properties.length; i++) {
40717 if (identifier in operators_properties[i]) {
40718 return i;
40719 }
40720 }
40721
40722 return null;
40723}
40724/**
40725 * Get the associativity of an operator (left or right).
40726 * Returns a string containing 'left' or 'right' or null if
40727 * the associativity is not defined.
40728 *
40729 * @param {Node}
40730 * @param {string} parenthesis
40731 * @return {string|null}
40732 * @throws {Error}
40733 */
40734
40735function getAssociativity(_node, parenthesis) {
40736 var node = _node;
40737
40738 if (parenthesis !== 'keep') {
40739 // ParenthesisNodes are only ignored when not in 'keep' mode
40740 node = _node.getContent();
40741 }
40742
40743 var identifier = node.getIdentifier();
40744 var index = getPrecedence(node, parenthesis);
40745
40746 if (index === null) {
40747 // node isn't in the list
40748 return null;
40749 }
40750
40751 var property = operators_properties[index][identifier];
40752
40753 if (Object(utils_object["f" /* hasOwnProperty */])(property, 'associativity')) {
40754 if (property.associativity === 'left') {
40755 return 'left';
40756 }
40757
40758 if (property.associativity === 'right') {
40759 return 'right';
40760 } // associativity is invalid
40761
40762
40763 throw Error('\'' + identifier + '\' has the invalid associativity \'' + property.associativity + '\'.');
40764 } // associativity is undefined
40765
40766
40767 return null;
40768}
40769/**
40770 * Check if an operator is associative with another operator.
40771 * Returns either true or false or null if not defined.
40772 *
40773 * @param {Node} nodeA
40774 * @param {Node} nodeB
40775 * @param {string} parenthesis
40776 * @return {boolean | null}
40777 */
40778
40779function isAssociativeWith(nodeA, nodeB, parenthesis) {
40780 // ParenthesisNodes are only ignored when not in 'keep' mode
40781 var a = parenthesis !== 'keep' ? nodeA.getContent() : nodeA;
40782 var b = parenthesis !== 'keep' ? nodeA.getContent() : nodeB;
40783 var identifierA = a.getIdentifier();
40784 var identifierB = b.getIdentifier();
40785 var index = getPrecedence(a, parenthesis);
40786
40787 if (index === null) {
40788 // node isn't in the list
40789 return null;
40790 }
40791
40792 var property = operators_properties[index][identifierA];
40793
40794 if (Object(utils_object["f" /* hasOwnProperty */])(property, 'associativeWith') && property.associativeWith instanceof Array) {
40795 for (var i = 0; i < property.associativeWith.length; i++) {
40796 if (property.associativeWith[i] === identifierB) {
40797 return true;
40798 }
40799 }
40800
40801 return false;
40802 } // associativeWith is not defined
40803
40804
40805 return null;
40806}
40807// CONCATENATED MODULE: ./src/expression/node/AssignmentNode.js
40808
40809
40810
40811
40812
40813
40814var AssignmentNode_name = 'AssignmentNode';
40815var AssignmentNode_dependencies = ['subset', '?matrix', // FIXME: should not be needed at all, should be handled by subset
40816'Node'];
40817var createAssignmentNode =
40818/* #__PURE__ */
40819Object(factory["a" /* factory */])(AssignmentNode_name, AssignmentNode_dependencies, function (_ref) {
40820 var subset = _ref.subset,
40821 matrix = _ref.matrix,
40822 Node = _ref.Node;
40823 var access = accessFactory({
40824 subset: subset
40825 });
40826 var assign = assignFactory({
40827 subset: subset,
40828 matrix: matrix
40829 });
40830 /**
40831 * @constructor AssignmentNode
40832 * @extends {Node}
40833 *
40834 * Define a symbol, like `a=3.2`, update a property like `a.b=3.2`, or
40835 * replace a subset of a matrix like `A[2,2]=42`.
40836 *
40837 * Syntax:
40838 *
40839 * new AssignmentNode(symbol, value)
40840 * new AssignmentNode(object, index, value)
40841 *
40842 * Usage:
40843 *
40844 * new AssignmentNode(new SymbolNode('a'), new ConstantNode(2)) // a=2
40845 * new AssignmentNode(new SymbolNode('a'), new IndexNode('b'), new ConstantNode(2)) // a.b=2
40846 * new AssignmentNode(new SymbolNode('a'), new IndexNode(1, 2), new ConstantNode(3)) // a[1,2]=3
40847 *
40848 * @param {SymbolNode | AccessorNode} object Object on which to assign a value
40849 * @param {IndexNode} [index=null] Index, property name or matrix
40850 * index. Optional. If not provided
40851 * and `object` is a SymbolNode,
40852 * the property is assigned to the
40853 * global scope.
40854 * @param {Node} value The value to be assigned
40855 */
40856
40857 function AssignmentNode(object, index, value) {
40858 if (!(this instanceof AssignmentNode)) {
40859 throw new SyntaxError('Constructor must be called with the new operator');
40860 }
40861
40862 this.object = object;
40863 this.index = value ? index : null;
40864 this.value = value || index; // validate input
40865
40866 if (!Object(is["J" /* isSymbolNode */])(object) && !Object(is["a" /* isAccessorNode */])(object)) {
40867 throw new TypeError('SymbolNode or AccessorNode expected as "object"');
40868 }
40869
40870 if (Object(is["J" /* isSymbolNode */])(object) && object.name === 'end') {
40871 throw new Error('Cannot assign to symbol "end"');
40872 }
40873
40874 if (this.index && !Object(is["u" /* isIndexNode */])(this.index)) {
40875 // index is optional
40876 throw new TypeError('IndexNode expected as "index"');
40877 }
40878
40879 if (!Object(is["w" /* isNode */])(this.value)) {
40880 throw new TypeError('Node expected as "value"');
40881 } // readonly property name
40882
40883
40884 Object.defineProperty(this, 'name', {
40885 get: function () {
40886 if (this.index) {
40887 return this.index.isObjectProperty() ? this.index.getObjectProperty() : '';
40888 } else {
40889 return this.object.name || '';
40890 }
40891 }.bind(this),
40892 set: function set() {
40893 throw new Error('Cannot assign a new name, name is read-only');
40894 }
40895 });
40896 }
40897
40898 AssignmentNode.prototype = new Node();
40899 AssignmentNode.prototype.type = 'AssignmentNode';
40900 AssignmentNode.prototype.isAssignmentNode = true;
40901 /**
40902 * Compile a node into a JavaScript function.
40903 * This basically pre-calculates as much as possible and only leaves open
40904 * calculations which depend on a dynamic scope with variables.
40905 * @param {Object} math Math.js namespace with functions and constants.
40906 * @param {Object} argNames An object with argument names as key and `true`
40907 * as value. Used in the SymbolNode to optimize
40908 * for arguments from user assigned functions
40909 * (see FunctionAssignmentNode) or special symbols
40910 * like `end` (see IndexNode).
40911 * @return {function} Returns a function which can be called like:
40912 * evalNode(scope: Object, args: Object, context: *)
40913 */
40914
40915 AssignmentNode.prototype._compile = function (math, argNames) {
40916 var evalObject = this.object._compile(math, argNames);
40917
40918 var evalIndex = this.index ? this.index._compile(math, argNames) : null;
40919
40920 var evalValue = this.value._compile(math, argNames);
40921
40922 var name = this.object.name;
40923
40924 if (!this.index) {
40925 // apply a variable to the scope, for example `a=2`
40926 if (!Object(is["J" /* isSymbolNode */])(this.object)) {
40927 throw new TypeError('SymbolNode expected as object');
40928 }
40929
40930 return function evalAssignmentNode(scope, args, context) {
40931 return setSafeProperty(scope, name, evalValue(scope, args, context));
40932 };
40933 } else if (this.index.isObjectProperty()) {
40934 // apply an object property for example `a.b=2`
40935 var prop = this.index.getObjectProperty();
40936 return function evalAssignmentNode(scope, args, context) {
40937 var object = evalObject(scope, args, context);
40938 var value = evalValue(scope, args, context);
40939 return setSafeProperty(object, prop, value);
40940 };
40941 } else if (Object(is["J" /* isSymbolNode */])(this.object)) {
40942 // update a matrix subset, for example `a[2]=3`
40943 return function evalAssignmentNode(scope, args, context) {
40944 var childObject = evalObject(scope, args, context);
40945 var value = evalValue(scope, args, context);
40946 var index = evalIndex(scope, args, childObject); // Important: we pass childObject instead of context
40947
40948 setSafeProperty(scope, name, assign(childObject, index, value));
40949 return value;
40950 };
40951 } else {
40952 // isAccessorNode(node.object) === true
40953 // update a matrix subset, for example `a.b[2]=3`
40954 // we will not use the compile function of the AccessorNode, but compile it
40955 // ourselves here as we need the parent object of the AccessorNode:
40956 // wee need to apply the updated object to parent object
40957 var evalParentObject = this.object.object._compile(math, argNames);
40958
40959 if (this.object.index.isObjectProperty()) {
40960 var parentProp = this.object.index.getObjectProperty();
40961 return function evalAssignmentNode(scope, args, context) {
40962 var parent = evalParentObject(scope, args, context);
40963 var childObject = getSafeProperty(parent, parentProp);
40964 var index = evalIndex(scope, args, childObject); // Important: we pass childObject instead of context
40965
40966 var value = evalValue(scope, args, context);
40967 setSafeProperty(parent, parentProp, assign(childObject, index, value));
40968 return value;
40969 };
40970 } else {
40971 // if some parameters use the 'end' parameter, we need to calculate the size
40972 var evalParentIndex = this.object.index._compile(math, argNames);
40973
40974 return function evalAssignmentNode(scope, args, context) {
40975 var parent = evalParentObject(scope, args, context);
40976 var parentIndex = evalParentIndex(scope, args, parent); // Important: we pass parent instead of context
40977
40978 var childObject = access(parent, parentIndex);
40979 var index = evalIndex(scope, args, childObject); // Important: we pass childObject instead of context
40980
40981 var value = evalValue(scope, args, context);
40982 assign(parent, parentIndex, assign(childObject, index, value));
40983 return value;
40984 };
40985 }
40986 }
40987 };
40988 /**
40989 * Execute a callback for each of the child nodes of this node
40990 * @param {function(child: Node, path: string, parent: Node)} callback
40991 */
40992
40993
40994 AssignmentNode.prototype.forEach = function (callback) {
40995 callback(this.object, 'object', this);
40996
40997 if (this.index) {
40998 callback(this.index, 'index', this);
40999 }
41000
41001 callback(this.value, 'value', this);
41002 };
41003 /**
41004 * Create a new AssignmentNode having it's childs be the results of calling
41005 * the provided callback function for each of the childs of the original node.
41006 * @param {function(child: Node, path: string, parent: Node): Node} callback
41007 * @returns {AssignmentNode} Returns a transformed copy of the node
41008 */
41009
41010
41011 AssignmentNode.prototype.map = function (callback) {
41012 var object = this._ifNode(callback(this.object, 'object', this));
41013
41014 var index = this.index ? this._ifNode(callback(this.index, 'index', this)) : null;
41015
41016 var value = this._ifNode(callback(this.value, 'value', this));
41017
41018 return new AssignmentNode(object, index, value);
41019 };
41020 /**
41021 * Create a clone of this node, a shallow copy
41022 * @return {AssignmentNode}
41023 */
41024
41025
41026 AssignmentNode.prototype.clone = function () {
41027 return new AssignmentNode(this.object, this.index, this.value);
41028 };
41029 /*
41030 * Is parenthesis needed?
41031 * @param {node} node
41032 * @param {string} [parenthesis='keep']
41033 * @private
41034 */
41035
41036
41037 function needParenthesis(node, parenthesis) {
41038 if (!parenthesis) {
41039 parenthesis = 'keep';
41040 }
41041
41042 var precedence = getPrecedence(node, parenthesis);
41043 var exprPrecedence = getPrecedence(node.value, parenthesis);
41044 return parenthesis === 'all' || exprPrecedence !== null && exprPrecedence <= precedence;
41045 }
41046 /**
41047 * Get string representation
41048 * @param {Object} options
41049 * @return {string}
41050 */
41051
41052
41053 AssignmentNode.prototype._toString = function (options) {
41054 var object = this.object.toString(options);
41055 var index = this.index ? this.index.toString(options) : '';
41056 var value = this.value.toString(options);
41057
41058 if (needParenthesis(this, options && options.parenthesis)) {
41059 value = '(' + value + ')';
41060 }
41061
41062 return object + index + ' = ' + value;
41063 };
41064 /**
41065 * Get a JSON representation of the node
41066 * @returns {Object}
41067 */
41068
41069
41070 AssignmentNode.prototype.toJSON = function () {
41071 return {
41072 mathjs: 'AssignmentNode',
41073 object: this.object,
41074 index: this.index,
41075 value: this.value
41076 };
41077 };
41078 /**
41079 * Instantiate an AssignmentNode from its JSON representation
41080 * @param {Object} json An object structured like
41081 * `{"mathjs": "AssignmentNode", object: ..., index: ..., value: ...}`,
41082 * where mathjs is optional
41083 * @returns {AssignmentNode}
41084 */
41085
41086
41087 AssignmentNode.fromJSON = function (json) {
41088 return new AssignmentNode(json.object, json.index, json.value);
41089 };
41090 /**
41091 * Get HTML representation
41092 * @param {Object} options
41093 * @return {string}
41094 */
41095
41096
41097 AssignmentNode.prototype.toHTML = function (options) {
41098 var object = this.object.toHTML(options);
41099 var index = this.index ? this.index.toHTML(options) : '';
41100 var value = this.value.toHTML(options);
41101
41102 if (needParenthesis(this, options && options.parenthesis)) {
41103 value = '<span class="math-paranthesis math-round-parenthesis">(</span>' + value + '<span class="math-paranthesis math-round-parenthesis">)</span>';
41104 }
41105
41106 return object + index + '<span class="math-operator math-assignment-operator math-variable-assignment-operator math-binary-operator">=</span>' + value;
41107 };
41108 /**
41109 * Get LaTeX representation
41110 * @param {Object} options
41111 * @return {string}
41112 */
41113
41114
41115 AssignmentNode.prototype._toTex = function (options) {
41116 var object = this.object.toTex(options);
41117 var index = this.index ? this.index.toTex(options) : '';
41118 var value = this.value.toTex(options);
41119
41120 if (needParenthesis(this, options && options.parenthesis)) {
41121 value = "\\left(".concat(value, "\\right)");
41122 }
41123
41124 return object + index + ':=' + value;
41125 };
41126
41127 return AssignmentNode;
41128}, {
41129 isClass: true,
41130 isNode: true
41131});
41132// CONCATENATED MODULE: ./src/expression/node/BlockNode.js
41133
41134
41135
41136var BlockNode_name = 'BlockNode';
41137var BlockNode_dependencies = ['ResultSet', 'Node'];
41138var createBlockNode =
41139/* #__PURE__ */
41140Object(factory["a" /* factory */])(BlockNode_name, BlockNode_dependencies, function (_ref) {
41141 var ResultSet = _ref.ResultSet,
41142 Node = _ref.Node;
41143
41144 /**
41145 * @constructor BlockNode
41146 * @extends {Node}
41147 * Holds a set with blocks
41148 * @param {Array.<{node: Node} | {node: Node, visible: boolean}>} blocks
41149 * An array with blocks, where a block is constructed as an Object
41150 * with properties block, which is a Node, and visible, which is
41151 * a boolean. The property visible is optional and is true by default
41152 */
41153 function BlockNode(blocks) {
41154 if (!(this instanceof BlockNode)) {
41155 throw new SyntaxError('Constructor must be called with the new operator');
41156 } // validate input, copy blocks
41157
41158
41159 if (!Array.isArray(blocks)) throw new Error('Array expected');
41160 this.blocks = blocks.map(function (block) {
41161 var node = block && block.node;
41162 var visible = block && block.visible !== undefined ? block.visible : true;
41163 if (!Object(is["w" /* isNode */])(node)) throw new TypeError('Property "node" must be a Node');
41164 if (typeof visible !== 'boolean') throw new TypeError('Property "visible" must be a boolean');
41165 return {
41166 node: node,
41167 visible: visible
41168 };
41169 });
41170 }
41171
41172 BlockNode.prototype = new Node();
41173 BlockNode.prototype.type = 'BlockNode';
41174 BlockNode.prototype.isBlockNode = true;
41175 /**
41176 * Compile a node into a JavaScript function.
41177 * This basically pre-calculates as much as possible and only leaves open
41178 * calculations which depend on a dynamic scope with variables.
41179 * @param {Object} math Math.js namespace with functions and constants.
41180 * @param {Object} argNames An object with argument names as key and `true`
41181 * as value. Used in the SymbolNode to optimize
41182 * for arguments from user assigned functions
41183 * (see FunctionAssignmentNode) or special symbols
41184 * like `end` (see IndexNode).
41185 * @return {function} Returns a function which can be called like:
41186 * evalNode(scope: Object, args: Object, context: *)
41187 */
41188
41189 BlockNode.prototype._compile = function (math, argNames) {
41190 var evalBlocks = Object(utils_array["m" /* map */])(this.blocks, function (block) {
41191 return {
41192 evaluate: block.node._compile(math, argNames),
41193 visible: block.visible
41194 };
41195 });
41196 return function evalBlockNodes(scope, args, context) {
41197 var results = [];
41198 Object(utils_array["f" /* forEach */])(evalBlocks, function evalBlockNode(block) {
41199 var result = block.evaluate(scope, args, context);
41200
41201 if (block.visible) {
41202 results.push(result);
41203 }
41204 });
41205 return new ResultSet(results);
41206 };
41207 };
41208 /**
41209 * Execute a callback for each of the child blocks of this node
41210 * @param {function(child: Node, path: string, parent: Node)} callback
41211 */
41212
41213
41214 BlockNode.prototype.forEach = function (callback) {
41215 for (var i = 0; i < this.blocks.length; i++) {
41216 callback(this.blocks[i].node, 'blocks[' + i + '].node', this);
41217 }
41218 };
41219 /**
41220 * Create a new BlockNode having it's childs be the results of calling
41221 * the provided callback function for each of the childs of the original node.
41222 * @param {function(child: Node, path: string, parent: Node): Node} callback
41223 * @returns {BlockNode} Returns a transformed copy of the node
41224 */
41225
41226
41227 BlockNode.prototype.map = function (callback) {
41228 var blocks = [];
41229
41230 for (var i = 0; i < this.blocks.length; i++) {
41231 var block = this.blocks[i];
41232
41233 var node = this._ifNode(callback(block.node, 'blocks[' + i + '].node', this));
41234
41235 blocks[i] = {
41236 node: node,
41237 visible: block.visible
41238 };
41239 }
41240
41241 return new BlockNode(blocks);
41242 };
41243 /**
41244 * Create a clone of this node, a shallow copy
41245 * @return {BlockNode}
41246 */
41247
41248
41249 BlockNode.prototype.clone = function () {
41250 var blocks = this.blocks.map(function (block) {
41251 return {
41252 node: block.node,
41253 visible: block.visible
41254 };
41255 });
41256 return new BlockNode(blocks);
41257 };
41258 /**
41259 * Get string representation
41260 * @param {Object} options
41261 * @return {string} str
41262 * @override
41263 */
41264
41265
41266 BlockNode.prototype._toString = function (options) {
41267 return this.blocks.map(function (param) {
41268 return param.node.toString(options) + (param.visible ? '' : ';');
41269 }).join('\n');
41270 };
41271 /**
41272 * Get a JSON representation of the node
41273 * @returns {Object}
41274 */
41275
41276
41277 BlockNode.prototype.toJSON = function () {
41278 return {
41279 mathjs: 'BlockNode',
41280 blocks: this.blocks
41281 };
41282 };
41283 /**
41284 * Instantiate an BlockNode from its JSON representation
41285 * @param {Object} json An object structured like
41286 * `{"mathjs": "BlockNode", blocks: [{node: ..., visible: false}, ...]}`,
41287 * where mathjs is optional
41288 * @returns {BlockNode}
41289 */
41290
41291
41292 BlockNode.fromJSON = function (json) {
41293 return new BlockNode(json.blocks);
41294 };
41295 /**
41296 * Get HTML representation
41297 * @param {Object} options
41298 * @return {string} str
41299 * @override
41300 */
41301
41302
41303 BlockNode.prototype.toHTML = function (options) {
41304 return this.blocks.map(function (param) {
41305 return param.node.toHTML(options) + (param.visible ? '' : '<span class="math-separator">;</span>');
41306 }).join('<span class="math-separator"><br /></span>');
41307 };
41308 /**
41309 * Get LaTeX representation
41310 * @param {Object} options
41311 * @return {string} str
41312 */
41313
41314
41315 BlockNode.prototype._toTex = function (options) {
41316 return this.blocks.map(function (param) {
41317 return param.node.toTex(options) + (param.visible ? '' : ';');
41318 }).join('\\;\\;\n');
41319 };
41320
41321 return BlockNode;
41322}, {
41323 isClass: true,
41324 isNode: true
41325});
41326// CONCATENATED MODULE: ./src/expression/node/ConditionalNode.js
41327
41328
41329
41330var ConditionalNode_name = 'ConditionalNode';
41331var ConditionalNode_dependencies = ['Node'];
41332var createConditionalNode =
41333/* #__PURE__ */
41334Object(factory["a" /* factory */])(ConditionalNode_name, ConditionalNode_dependencies, function (_ref) {
41335 var Node = _ref.Node;
41336
41337 /**
41338 * A lazy evaluating conditional operator: 'condition ? trueExpr : falseExpr'
41339 *
41340 * @param {Node} condition Condition, must result in a boolean
41341 * @param {Node} trueExpr Expression evaluated when condition is true
41342 * @param {Node} falseExpr Expression evaluated when condition is true
41343 *
41344 * @constructor ConditionalNode
41345 * @extends {Node}
41346 */
41347 function ConditionalNode(condition, trueExpr, falseExpr) {
41348 if (!(this instanceof ConditionalNode)) {
41349 throw new SyntaxError('Constructor must be called with the new operator');
41350 }
41351
41352 if (!Object(is["w" /* isNode */])(condition)) throw new TypeError('Parameter condition must be a Node');
41353 if (!Object(is["w" /* isNode */])(trueExpr)) throw new TypeError('Parameter trueExpr must be a Node');
41354 if (!Object(is["w" /* isNode */])(falseExpr)) throw new TypeError('Parameter falseExpr must be a Node');
41355 this.condition = condition;
41356 this.trueExpr = trueExpr;
41357 this.falseExpr = falseExpr;
41358 }
41359
41360 ConditionalNode.prototype = new Node();
41361 ConditionalNode.prototype.type = 'ConditionalNode';
41362 ConditionalNode.prototype.isConditionalNode = true;
41363 /**
41364 * Compile a node into a JavaScript function.
41365 * This basically pre-calculates as much as possible and only leaves open
41366 * calculations which depend on a dynamic scope with variables.
41367 * @param {Object} math Math.js namespace with functions and constants.
41368 * @param {Object} argNames An object with argument names as key and `true`
41369 * as value. Used in the SymbolNode to optimize
41370 * for arguments from user assigned functions
41371 * (see FunctionAssignmentNode) or special symbols
41372 * like `end` (see IndexNode).
41373 * @return {function} Returns a function which can be called like:
41374 * evalNode(scope: Object, args: Object, context: *)
41375 */
41376
41377 ConditionalNode.prototype._compile = function (math, argNames) {
41378 var evalCondition = this.condition._compile(math, argNames);
41379
41380 var evalTrueExpr = this.trueExpr._compile(math, argNames);
41381
41382 var evalFalseExpr = this.falseExpr._compile(math, argNames);
41383
41384 return function evalConditionalNode(scope, args, context) {
41385 return testCondition(evalCondition(scope, args, context)) ? evalTrueExpr(scope, args, context) : evalFalseExpr(scope, args, context);
41386 };
41387 };
41388 /**
41389 * Execute a callback for each of the child nodes of this node
41390 * @param {function(child: Node, path: string, parent: Node)} callback
41391 */
41392
41393
41394 ConditionalNode.prototype.forEach = function (callback) {
41395 callback(this.condition, 'condition', this);
41396 callback(this.trueExpr, 'trueExpr', this);
41397 callback(this.falseExpr, 'falseExpr', this);
41398 };
41399 /**
41400 * Create a new ConditionalNode having it's childs be the results of calling
41401 * the provided callback function for each of the childs of the original node.
41402 * @param {function(child: Node, path: string, parent: Node): Node} callback
41403 * @returns {ConditionalNode} Returns a transformed copy of the node
41404 */
41405
41406
41407 ConditionalNode.prototype.map = function (callback) {
41408 return new ConditionalNode(this._ifNode(callback(this.condition, 'condition', this)), this._ifNode(callback(this.trueExpr, 'trueExpr', this)), this._ifNode(callback(this.falseExpr, 'falseExpr', this)));
41409 };
41410 /**
41411 * Create a clone of this node, a shallow copy
41412 * @return {ConditionalNode}
41413 */
41414
41415
41416 ConditionalNode.prototype.clone = function () {
41417 return new ConditionalNode(this.condition, this.trueExpr, this.falseExpr);
41418 };
41419 /**
41420 * Get string representation
41421 * @param {Object} options
41422 * @return {string} str
41423 */
41424
41425
41426 ConditionalNode.prototype._toString = function (options) {
41427 var parenthesis = options && options.parenthesis ? options.parenthesis : 'keep';
41428 var precedence = getPrecedence(this, parenthesis); // Enclose Arguments in parentheses if they are an OperatorNode
41429 // or have lower or equal precedence
41430 // NOTE: enclosing all OperatorNodes in parentheses is a decision
41431 // purely based on aesthetics and readability
41432
41433 var condition = this.condition.toString(options);
41434 var conditionPrecedence = getPrecedence(this.condition, parenthesis);
41435
41436 if (parenthesis === 'all' || this.condition.type === 'OperatorNode' || conditionPrecedence !== null && conditionPrecedence <= precedence) {
41437 condition = '(' + condition + ')';
41438 }
41439
41440 var trueExpr = this.trueExpr.toString(options);
41441 var truePrecedence = getPrecedence(this.trueExpr, parenthesis);
41442
41443 if (parenthesis === 'all' || this.trueExpr.type === 'OperatorNode' || truePrecedence !== null && truePrecedence <= precedence) {
41444 trueExpr = '(' + trueExpr + ')';
41445 }
41446
41447 var falseExpr = this.falseExpr.toString(options);
41448 var falsePrecedence = getPrecedence(this.falseExpr, parenthesis);
41449
41450 if (parenthesis === 'all' || this.falseExpr.type === 'OperatorNode' || falsePrecedence !== null && falsePrecedence <= precedence) {
41451 falseExpr = '(' + falseExpr + ')';
41452 }
41453
41454 return condition + ' ? ' + trueExpr + ' : ' + falseExpr;
41455 };
41456 /**
41457 * Get a JSON representation of the node
41458 * @returns {Object}
41459 */
41460
41461
41462 ConditionalNode.prototype.toJSON = function () {
41463 return {
41464 mathjs: 'ConditionalNode',
41465 condition: this.condition,
41466 trueExpr: this.trueExpr,
41467 falseExpr: this.falseExpr
41468 };
41469 };
41470 /**
41471 * Instantiate an ConditionalNode from its JSON representation
41472 * @param {Object} json An object structured like
41473 * `{"mathjs": "ConditionalNode", "condition": ..., "trueExpr": ..., "falseExpr": ...}`,
41474 * where mathjs is optional
41475 * @returns {ConditionalNode}
41476 */
41477
41478
41479 ConditionalNode.fromJSON = function (json) {
41480 return new ConditionalNode(json.condition, json.trueExpr, json.falseExpr);
41481 };
41482 /**
41483 * Get HTML representation
41484 * @param {Object} options
41485 * @return {string} str
41486 */
41487
41488
41489 ConditionalNode.prototype.toHTML = function (options) {
41490 var parenthesis = options && options.parenthesis ? options.parenthesis : 'keep';
41491 var precedence = getPrecedence(this, parenthesis); // Enclose Arguments in parentheses if they are an OperatorNode
41492 // or have lower or equal precedence
41493 // NOTE: enclosing all OperatorNodes in parentheses is a decision
41494 // purely based on aesthetics and readability
41495
41496 var condition = this.condition.toHTML(options);
41497 var conditionPrecedence = getPrecedence(this.condition, parenthesis);
41498
41499 if (parenthesis === 'all' || this.condition.type === 'OperatorNode' || conditionPrecedence !== null && conditionPrecedence <= precedence) {
41500 condition = '<span class="math-parenthesis math-round-parenthesis">(</span>' + condition + '<span class="math-parenthesis math-round-parenthesis">)</span>';
41501 }
41502
41503 var trueExpr = this.trueExpr.toHTML(options);
41504 var truePrecedence = getPrecedence(this.trueExpr, parenthesis);
41505
41506 if (parenthesis === 'all' || this.trueExpr.type === 'OperatorNode' || truePrecedence !== null && truePrecedence <= precedence) {
41507 trueExpr = '<span class="math-parenthesis math-round-parenthesis">(</span>' + trueExpr + '<span class="math-parenthesis math-round-parenthesis">)</span>';
41508 }
41509
41510 var falseExpr = this.falseExpr.toHTML(options);
41511 var falsePrecedence = getPrecedence(this.falseExpr, parenthesis);
41512
41513 if (parenthesis === 'all' || this.falseExpr.type === 'OperatorNode' || falsePrecedence !== null && falsePrecedence <= precedence) {
41514 falseExpr = '<span class="math-parenthesis math-round-parenthesis">(</span>' + falseExpr + '<span class="math-parenthesis math-round-parenthesis">)</span>';
41515 }
41516
41517 return condition + '<span class="math-operator math-conditional-operator">?</span>' + trueExpr + '<span class="math-operator math-conditional-operator">:</span>' + falseExpr;
41518 };
41519 /**
41520 * Get LaTeX representation
41521 * @param {Object} options
41522 * @return {string} str
41523 */
41524
41525
41526 ConditionalNode.prototype._toTex = function (options) {
41527 return '\\begin{cases} {' + this.trueExpr.toTex(options) + '}, &\\quad{\\text{if }\\;' + this.condition.toTex(options) + '}\\\\{' + this.falseExpr.toTex(options) + '}, &\\quad{\\text{otherwise}}\\end{cases}';
41528 };
41529 /**
41530 * Test whether a condition is met
41531 * @param {*} condition
41532 * @returns {boolean} true if condition is true or non-zero, else false
41533 */
41534
41535
41536 function testCondition(condition) {
41537 if (typeof condition === 'number' || typeof condition === 'boolean' || typeof condition === 'string') {
41538 return !!condition;
41539 }
41540
41541 if (condition) {
41542 if (Object(is["e" /* isBigNumber */])(condition)) {
41543 return !condition.isZero();
41544 }
41545
41546 if (Object(is["j" /* isComplex */])(condition)) {
41547 return !!(condition.re || condition.im);
41548 }
41549
41550 if (Object(is["L" /* isUnit */])(condition)) {
41551 return !!condition.value;
41552 }
41553 }
41554
41555 if (condition === null || condition === undefined) {
41556 return false;
41557 }
41558
41559 throw new TypeError('Unsupported type of condition "' + Object(is["M" /* typeOf */])(condition) + '"');
41560 }
41561
41562 return ConditionalNode;
41563}, {
41564 isClass: true,
41565 isNode: true
41566});
41567// EXTERNAL MODULE: ./node_modules/escape-latex/dist/index.js
41568var dist = __webpack_require__(17);
41569var dist_default = /*#__PURE__*/__webpack_require__.n(dist);
41570
41571// CONCATENATED MODULE: ./src/utils/latex.js
41572/* eslint no-template-curly-in-string: "off" */
41573
41574
41575var latexSymbols = {
41576 // GREEK LETTERS
41577 Alpha: 'A',
41578 alpha: '\\alpha',
41579 Beta: 'B',
41580 beta: '\\beta',
41581 Gamma: '\\Gamma',
41582 gamma: '\\gamma',
41583 Delta: '\\Delta',
41584 delta: '\\delta',
41585 Epsilon: 'E',
41586 epsilon: '\\epsilon',
41587 varepsilon: '\\varepsilon',
41588 Zeta: 'Z',
41589 zeta: '\\zeta',
41590 Eta: 'H',
41591 eta: '\\eta',
41592 Theta: '\\Theta',
41593 theta: '\\theta',
41594 vartheta: '\\vartheta',
41595 Iota: 'I',
41596 iota: '\\iota',
41597 Kappa: 'K',
41598 kappa: '\\kappa',
41599 varkappa: '\\varkappa',
41600 Lambda: '\\Lambda',
41601 lambda: '\\lambda',
41602 Mu: 'M',
41603 mu: '\\mu',
41604 Nu: 'N',
41605 nu: '\\nu',
41606 Xi: '\\Xi',
41607 xi: '\\xi',
41608 Omicron: 'O',
41609 omicron: 'o',
41610 Pi: '\\Pi',
41611 pi: '\\pi',
41612 varpi: '\\varpi',
41613 Rho: 'P',
41614 rho: '\\rho',
41615 varrho: '\\varrho',
41616 Sigma: '\\Sigma',
41617 sigma: '\\sigma',
41618 varsigma: '\\varsigma',
41619 Tau: 'T',
41620 tau: '\\tau',
41621 Upsilon: "\\Upsilon",
41622 upsilon: "\\upsilon",
41623 Phi: '\\Phi',
41624 phi: '\\phi',
41625 varphi: '\\varphi',
41626 Chi: 'X',
41627 chi: '\\chi',
41628 Psi: '\\Psi',
41629 psi: '\\psi',
41630 Omega: '\\Omega',
41631 omega: '\\omega',
41632 // logic
41633 "true": '\\mathrm{True}',
41634 "false": '\\mathrm{False}',
41635 // other
41636 i: 'i',
41637 // TODO use \i ??
41638 inf: '\\infty',
41639 Inf: '\\infty',
41640 infinity: '\\infty',
41641 Infinity: '\\infty',
41642 oo: '\\infty',
41643 lim: '\\lim',
41644 undefined: '\\mathbf{?}'
41645};
41646var latexOperators = {
41647 transpose: '^\\top',
41648 ctranspose: '^H',
41649 factorial: '!',
41650 pow: '^',
41651 dotPow: '.^\\wedge',
41652 // TODO find ideal solution
41653 unaryPlus: '+',
41654 unaryMinus: '-',
41655 bitNot: '\\~',
41656 // TODO find ideal solution
41657 not: '\\neg',
41658 multiply: '\\cdot',
41659 divide: '\\frac',
41660 // TODO how to handle that properly?
41661 dotMultiply: '.\\cdot',
41662 // TODO find ideal solution
41663 dotDivide: '.:',
41664 // TODO find ideal solution
41665 mod: '\\mod',
41666 add: '+',
41667 subtract: '-',
41668 to: '\\rightarrow',
41669 leftShift: '<<',
41670 rightArithShift: '>>',
41671 rightLogShift: '>>>',
41672 equal: '=',
41673 unequal: '\\neq',
41674 smaller: '<',
41675 larger: '>',
41676 smallerEq: '\\leq',
41677 largerEq: '\\geq',
41678 bitAnd: '\\&',
41679 bitXor: "\\underline{|}",
41680 bitOr: '|',
41681 and: '\\wedge',
41682 xor: '\\veebar',
41683 or: '\\vee'
41684};
41685var latexFunctions = {
41686 // arithmetic
41687 abs: {
41688 1: '\\left|${args[0]}\\right|'
41689 },
41690 add: {
41691 2: "\\left(${args[0]}".concat(latexOperators.add, "${args[1]}\\right)")
41692 },
41693 cbrt: {
41694 1: '\\sqrt[3]{${args[0]}}'
41695 },
41696 ceil: {
41697 1: '\\left\\lceil${args[0]}\\right\\rceil'
41698 },
41699 cube: {
41700 1: '\\left(${args[0]}\\right)^3'
41701 },
41702 divide: {
41703 2: '\\frac{${args[0]}}{${args[1]}}'
41704 },
41705 dotDivide: {
41706 2: "\\left(${args[0]}".concat(latexOperators.dotDivide, "${args[1]}\\right)")
41707 },
41708 dotMultiply: {
41709 2: "\\left(${args[0]}".concat(latexOperators.dotMultiply, "${args[1]}\\right)")
41710 },
41711 dotPow: {
41712 2: "\\left(${args[0]}".concat(latexOperators.dotPow, "${args[1]}\\right)")
41713 },
41714 exp: {
41715 1: '\\exp\\left(${args[0]}\\right)'
41716 },
41717 expm1: "\\left(e".concat(latexOperators.pow, "{${args[0]}}-1\\right)"),
41718 fix: {
41719 1: '\\mathrm{${name}}\\left(${args[0]}\\right)'
41720 },
41721 floor: {
41722 1: '\\left\\lfloor${args[0]}\\right\\rfloor'
41723 },
41724 gcd: '\\gcd\\left(${args}\\right)',
41725 hypot: '\\hypot\\left(${args}\\right)',
41726 log: {
41727 1: '\\ln\\left(${args[0]}\\right)',
41728 2: '\\log_{${args[1]}}\\left(${args[0]}\\right)'
41729 },
41730 log10: {
41731 1: '\\log_{10}\\left(${args[0]}\\right)'
41732 },
41733 log1p: {
41734 1: '\\ln\\left(${args[0]}+1\\right)',
41735 2: '\\log_{${args[1]}}\\left(${args[0]}+1\\right)'
41736 },
41737 log2: '\\log_{2}\\left(${args[0]}\\right)',
41738 mod: {
41739 2: "\\left(${args[0]}".concat(latexOperators.mod, "${args[1]}\\right)")
41740 },
41741 multiply: {
41742 2: "\\left(${args[0]}".concat(latexOperators.multiply, "${args[1]}\\right)")
41743 },
41744 norm: {
41745 1: '\\left\\|${args[0]}\\right\\|',
41746 2: undefined // use default template
41747
41748 },
41749 nthRoot: {
41750 2: '\\sqrt[${args[1]}]{${args[0]}}'
41751 },
41752 nthRoots: {
41753 2: '\\{y : $y^{args[1]} = {${args[0]}}\\}'
41754 },
41755 pow: {
41756 2: "\\left(${args[0]}\\right)".concat(latexOperators.pow, "{${args[1]}}")
41757 },
41758 round: {
41759 1: '\\left\\lfloor${args[0]}\\right\\rceil',
41760 2: undefined // use default template
41761
41762 },
41763 sign: {
41764 1: '\\mathrm{${name}}\\left(${args[0]}\\right)'
41765 },
41766 sqrt: {
41767 1: '\\sqrt{${args[0]}}'
41768 },
41769 square: {
41770 1: '\\left(${args[0]}\\right)^2'
41771 },
41772 subtract: {
41773 2: "\\left(${args[0]}".concat(latexOperators.subtract, "${args[1]}\\right)")
41774 },
41775 unaryMinus: {
41776 1: "".concat(latexOperators.unaryMinus, "\\left(${args[0]}\\right)")
41777 },
41778 unaryPlus: {
41779 1: "".concat(latexOperators.unaryPlus, "\\left(${args[0]}\\right)")
41780 },
41781 // bitwise
41782 bitAnd: {
41783 2: "\\left(${args[0]}".concat(latexOperators.bitAnd, "${args[1]}\\right)")
41784 },
41785 bitNot: {
41786 1: latexOperators.bitNot + '\\left(${args[0]}\\right)'
41787 },
41788 bitOr: {
41789 2: "\\left(${args[0]}".concat(latexOperators.bitOr, "${args[1]}\\right)")
41790 },
41791 bitXor: {
41792 2: "\\left(${args[0]}".concat(latexOperators.bitXor, "${args[1]}\\right)")
41793 },
41794 leftShift: {
41795 2: "\\left(${args[0]}".concat(latexOperators.leftShift, "${args[1]}\\right)")
41796 },
41797 rightArithShift: {
41798 2: "\\left(${args[0]}".concat(latexOperators.rightArithShift, "${args[1]}\\right)")
41799 },
41800 rightLogShift: {
41801 2: "\\left(${args[0]}".concat(latexOperators.rightLogShift, "${args[1]}\\right)")
41802 },
41803 // combinatorics
41804 bellNumbers: {
41805 1: '\\mathrm{B}_{${args[0]}}'
41806 },
41807 catalan: {
41808 1: '\\mathrm{C}_{${args[0]}}'
41809 },
41810 stirlingS2: {
41811 2: '\\mathrm{S}\\left(${args}\\right)'
41812 },
41813 // complex
41814 arg: {
41815 1: '\\arg\\left(${args[0]}\\right)'
41816 },
41817 conj: {
41818 1: '\\left(${args[0]}\\right)^*'
41819 },
41820 im: {
41821 1: '\\Im\\left\\lbrace${args[0]}\\right\\rbrace'
41822 },
41823 re: {
41824 1: '\\Re\\left\\lbrace${args[0]}\\right\\rbrace'
41825 },
41826 // logical
41827 and: {
41828 2: "\\left(${args[0]}".concat(latexOperators.and, "${args[1]}\\right)")
41829 },
41830 not: {
41831 1: latexOperators.not + '\\left(${args[0]}\\right)'
41832 },
41833 or: {
41834 2: "\\left(${args[0]}".concat(latexOperators.or, "${args[1]}\\right)")
41835 },
41836 xor: {
41837 2: "\\left(${args[0]}".concat(latexOperators.xor, "${args[1]}\\right)")
41838 },
41839 // matrix
41840 cross: {
41841 2: '\\left(${args[0]}\\right)\\times\\left(${args[1]}\\right)'
41842 },
41843 ctranspose: {
41844 1: "\\left(${args[0]}\\right)".concat(latexOperators.ctranspose)
41845 },
41846 det: {
41847 1: '\\det\\left(${args[0]}\\right)'
41848 },
41849 dot: {
41850 2: '\\left(${args[0]}\\cdot${args[1]}\\right)'
41851 },
41852 expm: {
41853 1: '\\exp\\left(${args[0]}\\right)'
41854 },
41855 inv: {
41856 1: '\\left(${args[0]}\\right)^{-1}'
41857 },
41858 sqrtm: {
41859 1: "{${args[0]}}".concat(latexOperators.pow, "{\\frac{1}{2}}")
41860 },
41861 trace: {
41862 1: '\\mathrm{tr}\\left(${args[0]}\\right)'
41863 },
41864 transpose: {
41865 1: "\\left(${args[0]}\\right)".concat(latexOperators.transpose)
41866 },
41867 // probability
41868 combinations: {
41869 2: '\\binom{${args[0]}}{${args[1]}}'
41870 },
41871 combinationsWithRep: {
41872 2: '\\left(\\!\\!{\\binom{${args[0]}}{${args[1]}}}\\!\\!\\right)'
41873 },
41874 factorial: {
41875 1: "\\left(${args[0]}\\right)".concat(latexOperators.factorial)
41876 },
41877 gamma: {
41878 1: '\\Gamma\\left(${args[0]}\\right)'
41879 },
41880 // relational
41881 equal: {
41882 2: "\\left(${args[0]}".concat(latexOperators.equal, "${args[1]}\\right)")
41883 },
41884 larger: {
41885 2: "\\left(${args[0]}".concat(latexOperators.larger, "${args[1]}\\right)")
41886 },
41887 largerEq: {
41888 2: "\\left(${args[0]}".concat(latexOperators.largerEq, "${args[1]}\\right)")
41889 },
41890 smaller: {
41891 2: "\\left(${args[0]}".concat(latexOperators.smaller, "${args[1]}\\right)")
41892 },
41893 smallerEq: {
41894 2: "\\left(${args[0]}".concat(latexOperators.smallerEq, "${args[1]}\\right)")
41895 },
41896 unequal: {
41897 2: "\\left(${args[0]}".concat(latexOperators.unequal, "${args[1]}\\right)")
41898 },
41899 // special
41900 erf: {
41901 1: 'erf\\left(${args[0]}\\right)'
41902 },
41903 // statistics
41904 max: '\\max\\left(${args}\\right)',
41905 min: '\\min\\left(${args}\\right)',
41906 variance: '\\mathrm{Var}\\left(${args}\\right)',
41907 // trigonometry
41908 acos: {
41909 1: '\\cos^{-1}\\left(${args[0]}\\right)'
41910 },
41911 acosh: {
41912 1: '\\cosh^{-1}\\left(${args[0]}\\right)'
41913 },
41914 acot: {
41915 1: '\\cot^{-1}\\left(${args[0]}\\right)'
41916 },
41917 acoth: {
41918 1: '\\coth^{-1}\\left(${args[0]}\\right)'
41919 },
41920 acsc: {
41921 1: '\\csc^{-1}\\left(${args[0]}\\right)'
41922 },
41923 acsch: {
41924 1: '\\mathrm{csch}^{-1}\\left(${args[0]}\\right)'
41925 },
41926 asec: {
41927 1: '\\sec^{-1}\\left(${args[0]}\\right)'
41928 },
41929 asech: {
41930 1: '\\mathrm{sech}^{-1}\\left(${args[0]}\\right)'
41931 },
41932 asin: {
41933 1: '\\sin^{-1}\\left(${args[0]}\\right)'
41934 },
41935 asinh: {
41936 1: '\\sinh^{-1}\\left(${args[0]}\\right)'
41937 },
41938 atan: {
41939 1: '\\tan^{-1}\\left(${args[0]}\\right)'
41940 },
41941 atan2: {
41942 2: '\\mathrm{atan2}\\left(${args}\\right)'
41943 },
41944 atanh: {
41945 1: '\\tanh^{-1}\\left(${args[0]}\\right)'
41946 },
41947 cos: {
41948 1: '\\cos\\left(${args[0]}\\right)'
41949 },
41950 cosh: {
41951 1: '\\cosh\\left(${args[0]}\\right)'
41952 },
41953 cot: {
41954 1: '\\cot\\left(${args[0]}\\right)'
41955 },
41956 coth: {
41957 1: '\\coth\\left(${args[0]}\\right)'
41958 },
41959 csc: {
41960 1: '\\csc\\left(${args[0]}\\right)'
41961 },
41962 csch: {
41963 1: '\\mathrm{csch}\\left(${args[0]}\\right)'
41964 },
41965 sec: {
41966 1: '\\sec\\left(${args[0]}\\right)'
41967 },
41968 sech: {
41969 1: '\\mathrm{sech}\\left(${args[0]}\\right)'
41970 },
41971 sin: {
41972 1: '\\sin\\left(${args[0]}\\right)'
41973 },
41974 sinh: {
41975 1: '\\sinh\\left(${args[0]}\\right)'
41976 },
41977 tan: {
41978 1: '\\tan\\left(${args[0]}\\right)'
41979 },
41980 tanh: {
41981 1: '\\tanh\\left(${args[0]}\\right)'
41982 },
41983 // unit
41984 to: {
41985 2: "\\left(${args[0]}".concat(latexOperators.to, "${args[1]}\\right)")
41986 },
41987 // utils
41988 numeric: function numeric(node, options) {
41989 // Not sure if this is strictly right but should work correctly for the vast majority of use cases.
41990 return node.args[0].toTex();
41991 },
41992 // type
41993 number: {
41994 0: '0',
41995 1: '\\left(${args[0]}\\right)',
41996 2: '\\left(\\left(${args[0]}\\right)${args[1]}\\right)'
41997 },
41998 string: {
41999 0: '\\mathtt{""}',
42000 1: '\\mathrm{string}\\left(${args[0]}\\right)'
42001 },
42002 bignumber: {
42003 0: '0',
42004 1: '\\left(${args[0]}\\right)'
42005 },
42006 complex: {
42007 0: '0',
42008 1: '\\left(${args[0]}\\right)',
42009 2: "\\left(\\left(${args[0]}\\right)+".concat(latexSymbols.i, "\\cdot\\left(${args[1]}\\right)\\right)")
42010 },
42011 matrix: {
42012 0: '\\begin{bmatrix}\\end{bmatrix}',
42013 1: '\\left(${args[0]}\\right)',
42014 2: '\\left(${args[0]}\\right)'
42015 },
42016 sparse: {
42017 0: '\\begin{bsparse}\\end{bsparse}',
42018 1: '\\left(${args[0]}\\right)'
42019 },
42020 unit: {
42021 1: '\\left(${args[0]}\\right)',
42022 2: '\\left(\\left(${args[0]}\\right)${args[1]}\\right)'
42023 }
42024};
42025var defaultTemplate = '\\mathrm{${name}}\\left(${args}\\right)';
42026var latexUnits = {
42027 deg: '^\\circ'
42028};
42029function escapeLatex(string) {
42030 return dist_default()(string, {
42031 preserveFormatting: true
42032 });
42033} // @param {string} name
42034// @param {boolean} isUnit
42035
42036function toSymbol(name, isUnit) {
42037 isUnit = typeof isUnit === 'undefined' ? false : isUnit;
42038
42039 if (isUnit) {
42040 if (Object(utils_object["f" /* hasOwnProperty */])(latexUnits, name)) {
42041 return latexUnits[name];
42042 }
42043
42044 return '\\mathrm{' + escapeLatex(name) + '}';
42045 }
42046
42047 if (Object(utils_object["f" /* hasOwnProperty */])(latexSymbols, name)) {
42048 return latexSymbols[name];
42049 }
42050
42051 return escapeLatex(name);
42052}
42053// CONCATENATED MODULE: ./src/expression/node/ConstantNode.js
42054
42055
42056
42057
42058var ConstantNode_name = 'ConstantNode';
42059var ConstantNode_dependencies = ['Node'];
42060var ConstantNode_createConstantNode =
42061/* #__PURE__ */
42062Object(factory["a" /* factory */])(ConstantNode_name, ConstantNode_dependencies, function (_ref) {
42063 var Node = _ref.Node;
42064
42065 /**
42066 * A ConstantNode holds a constant value like a number or string.
42067 *
42068 * Usage:
42069 *
42070 * new ConstantNode(2.3)
42071 * new ConstantNode('hello')
42072 *
42073 * @param {*} value Value can be any type (number, BigNumber, string, ...)
42074 * @constructor ConstantNode
42075 * @extends {Node}
42076 */
42077 function ConstantNode(value) {
42078 if (!(this instanceof ConstantNode)) {
42079 throw new SyntaxError('Constructor must be called with the new operator');
42080 }
42081
42082 if (arguments.length === 2) {
42083 // TODO: remove deprecation error some day (created 2018-01-23)
42084 throw new SyntaxError('new ConstantNode(valueStr, valueType) is not supported anymore since math v4.0.0. Use new ConstantNode(value) instead, where value is a non-stringified value.');
42085 }
42086
42087 this.value = value;
42088 }
42089
42090 ConstantNode.prototype = new Node();
42091 ConstantNode.prototype.type = 'ConstantNode';
42092 ConstantNode.prototype.isConstantNode = true;
42093 /**
42094 * Compile a node into a JavaScript function.
42095 * This basically pre-calculates as much as possible and only leaves open
42096 * calculations which depend on a dynamic scope with variables.
42097 * @param {Object} math Math.js namespace with functions and constants.
42098 * @param {Object} argNames An object with argument names as key and `true`
42099 * as value. Used in the SymbolNode to optimize
42100 * for arguments from user assigned functions
42101 * (see FunctionAssignmentNode) or special symbols
42102 * like `end` (see IndexNode).
42103 * @return {function} Returns a function which can be called like:
42104 * evalNode(scope: Object, args: Object, context: *)
42105 */
42106
42107 ConstantNode.prototype._compile = function (math, argNames) {
42108 var value = this.value;
42109 return function evalConstantNode() {
42110 return value;
42111 };
42112 };
42113 /**
42114 * Execute a callback for each of the child nodes of this node
42115 * @param {function(child: Node, path: string, parent: Node)} callback
42116 */
42117
42118
42119 ConstantNode.prototype.forEach = function (callback) {} // nothing to do, we don't have childs
42120
42121 /**
42122 * Create a new ConstantNode having it's childs be the results of calling
42123 * the provided callback function for each of the childs of the original node.
42124 * @param {function(child: Node, path: string, parent: Node) : Node} callback
42125 * @returns {ConstantNode} Returns a clone of the node
42126 */
42127 ;
42128
42129 ConstantNode.prototype.map = function (callback) {
42130 return this.clone();
42131 };
42132 /**
42133 * Create a clone of this node, a shallow copy
42134 * @return {ConstantNode}
42135 */
42136
42137
42138 ConstantNode.prototype.clone = function () {
42139 return new ConstantNode(this.value);
42140 };
42141 /**
42142 * Get string representation
42143 * @param {Object} options
42144 * @return {string} str
42145 */
42146
42147
42148 ConstantNode.prototype._toString = function (options) {
42149 return Object(utils_string["d" /* format */])(this.value, options);
42150 };
42151 /**
42152 * Get HTML representation
42153 * @param {Object} options
42154 * @return {string} str
42155 */
42156
42157
42158 ConstantNode.prototype.toHTML = function (options) {
42159 var value = this._toString(options);
42160
42161 switch (Object(is["M" /* typeOf */])(this.value)) {
42162 case 'number':
42163 case 'BigNumber':
42164 case 'Fraction':
42165 return '<span class="math-number">' + value + '</span>';
42166
42167 case 'string':
42168 return '<span class="math-string">' + value + '</span>';
42169
42170 case 'boolean':
42171 return '<span class="math-boolean">' + value + '</span>';
42172
42173 case 'null':
42174 return '<span class="math-null-symbol">' + value + '</span>';
42175
42176 case 'undefined':
42177 return '<span class="math-undefined">' + value + '</span>';
42178
42179 default:
42180 return '<span class="math-symbol">' + value + '</span>';
42181 }
42182 };
42183 /**
42184 * Get a JSON representation of the node
42185 * @returns {Object}
42186 */
42187
42188
42189 ConstantNode.prototype.toJSON = function () {
42190 return {
42191 mathjs: 'ConstantNode',
42192 value: this.value
42193 };
42194 };
42195 /**
42196 * Instantiate a ConstantNode from its JSON representation
42197 * @param {Object} json An object structured like
42198 * `{"mathjs": "SymbolNode", value: 2.3}`,
42199 * where mathjs is optional
42200 * @returns {ConstantNode}
42201 */
42202
42203
42204 ConstantNode.fromJSON = function (json) {
42205 return new ConstantNode(json.value);
42206 };
42207 /**
42208 * Get LaTeX representation
42209 * @param {Object} options
42210 * @return {string} str
42211 */
42212
42213
42214 ConstantNode.prototype._toTex = function (options) {
42215 var value = this._toString(options);
42216
42217 switch (Object(is["M" /* typeOf */])(this.value)) {
42218 case 'string':
42219 return '\\mathtt{' + escapeLatex(value) + '}';
42220
42221 case 'number':
42222 case 'BigNumber':
42223 {
42224 var index = value.toLowerCase().indexOf('e');
42225
42226 if (index !== -1) {
42227 return value.substring(0, index) + '\\cdot10^{' + value.substring(index + 1) + '}';
42228 }
42229 }
42230 return value;
42231
42232 case 'Fraction':
42233 return this.value.toLatex();
42234
42235 default:
42236 return value;
42237 }
42238 };
42239
42240 return ConstantNode;
42241}, {
42242 isClass: true,
42243 isNode: true
42244});
42245// CONCATENATED MODULE: ./src/expression/node/FunctionAssignmentNode.js
42246
42247
42248
42249
42250
42251
42252
42253
42254var FunctionAssignmentNode_name = 'FunctionAssignmentNode';
42255var FunctionAssignmentNode_dependencies = ['typed', 'Node'];
42256var createFunctionAssignmentNode =
42257/* #__PURE__ */
42258Object(factory["a" /* factory */])(FunctionAssignmentNode_name, FunctionAssignmentNode_dependencies, function (_ref) {
42259 var typed = _ref.typed,
42260 Node = _ref.Node;
42261
42262 /**
42263 * @constructor FunctionAssignmentNode
42264 * @extends {Node}
42265 * Function assignment
42266 *
42267 * @param {string} name Function name
42268 * @param {string[] | Array.<{name: string, type: string}>} params
42269 * Array with function parameter names, or an
42270 * array with objects containing the name
42271 * and type of the parameter
42272 * @param {Node} expr The function expression
42273 */
42274 function FunctionAssignmentNode(name, params, expr) {
42275 if (!(this instanceof FunctionAssignmentNode)) {
42276 throw new SyntaxError('Constructor must be called with the new operator');
42277 } // validate input
42278
42279
42280 if (typeof name !== 'string') throw new TypeError('String expected for parameter "name"');
42281 if (!Array.isArray(params)) throw new TypeError('Array containing strings or objects expected for parameter "params"');
42282 if (!Object(is["w" /* isNode */])(expr)) throw new TypeError('Node expected for parameter "expr"');
42283 if (name in keywords) throw new Error('Illegal function name, "' + name + '" is a reserved keyword');
42284 this.name = name;
42285 this.params = params.map(function (param) {
42286 return param && param.name || param;
42287 });
42288 this.types = params.map(function (param) {
42289 return param && param.type || 'any';
42290 });
42291 this.expr = expr;
42292 }
42293
42294 FunctionAssignmentNode.prototype = new Node();
42295 FunctionAssignmentNode.prototype.type = 'FunctionAssignmentNode';
42296 FunctionAssignmentNode.prototype.isFunctionAssignmentNode = true;
42297 /**
42298 * Compile a node into a JavaScript function.
42299 * This basically pre-calculates as much as possible and only leaves open
42300 * calculations which depend on a dynamic scope with variables.
42301 * @param {Object} math Math.js namespace with functions and constants.
42302 * @param {Object} argNames An object with argument names as key and `true`
42303 * as value. Used in the SymbolNode to optimize
42304 * for arguments from user assigned functions
42305 * (see FunctionAssignmentNode) or special symbols
42306 * like `end` (see IndexNode).
42307 * @return {function} Returns a function which can be called like:
42308 * evalNode(scope: Object, args: Object, context: *)
42309 */
42310
42311 FunctionAssignmentNode.prototype._compile = function (math, argNames) {
42312 var childArgNames = Object.create(argNames);
42313 Object(utils_array["f" /* forEach */])(this.params, function (param) {
42314 childArgNames[param] = true;
42315 }); // compile the function expression with the child args
42316
42317 var evalExpr = this.expr._compile(math, childArgNames);
42318
42319 var name = this.name;
42320 var params = this.params;
42321 var signature = Object(utils_array["k" /* join */])(this.types, ',');
42322 var syntax = name + '(' + Object(utils_array["k" /* join */])(this.params, ', ') + ')';
42323 return function evalFunctionAssignmentNode(scope, args, context) {
42324 var signatures = {};
42325
42326 signatures[signature] = function () {
42327 var childArgs = Object.create(args);
42328
42329 for (var i = 0; i < params.length; i++) {
42330 childArgs[params[i]] = arguments[i];
42331 }
42332
42333 return evalExpr(scope, childArgs, context);
42334 };
42335
42336 var fn = typed(name, signatures);
42337 fn.syntax = syntax;
42338 setSafeProperty(scope, name, fn);
42339 return fn;
42340 };
42341 };
42342 /**
42343 * Execute a callback for each of the child nodes of this node
42344 * @param {function(child: Node, path: string, parent: Node)} callback
42345 */
42346
42347
42348 FunctionAssignmentNode.prototype.forEach = function (callback) {
42349 callback(this.expr, 'expr', this);
42350 };
42351 /**
42352 * Create a new FunctionAssignmentNode having it's childs be the results of calling
42353 * the provided callback function for each of the childs of the original node.
42354 * @param {function(child: Node, path: string, parent: Node): Node} callback
42355 * @returns {FunctionAssignmentNode} Returns a transformed copy of the node
42356 */
42357
42358
42359 FunctionAssignmentNode.prototype.map = function (callback) {
42360 var expr = this._ifNode(callback(this.expr, 'expr', this));
42361
42362 return new FunctionAssignmentNode(this.name, this.params.slice(0), expr);
42363 };
42364 /**
42365 * Create a clone of this node, a shallow copy
42366 * @return {FunctionAssignmentNode}
42367 */
42368
42369
42370 FunctionAssignmentNode.prototype.clone = function () {
42371 return new FunctionAssignmentNode(this.name, this.params.slice(0), this.expr);
42372 };
42373 /**
42374 * Is parenthesis needed?
42375 * @param {Node} node
42376 * @param {Object} parenthesis
42377 * @private
42378 */
42379
42380
42381 function needParenthesis(node, parenthesis) {
42382 var precedence = getPrecedence(node, parenthesis);
42383 var exprPrecedence = getPrecedence(node.expr, parenthesis);
42384 return parenthesis === 'all' || exprPrecedence !== null && exprPrecedence <= precedence;
42385 }
42386 /**
42387 * get string representation
42388 * @param {Object} options
42389 * @return {string} str
42390 */
42391
42392
42393 FunctionAssignmentNode.prototype._toString = function (options) {
42394 var parenthesis = options && options.parenthesis ? options.parenthesis : 'keep';
42395 var expr = this.expr.toString(options);
42396
42397 if (needParenthesis(this, parenthesis)) {
42398 expr = '(' + expr + ')';
42399 }
42400
42401 return this.name + '(' + this.params.join(', ') + ') = ' + expr;
42402 };
42403 /**
42404 * Get a JSON representation of the node
42405 * @returns {Object}
42406 */
42407
42408
42409 FunctionAssignmentNode.prototype.toJSON = function () {
42410 var types = this.types;
42411 return {
42412 mathjs: 'FunctionAssignmentNode',
42413 name: this.name,
42414 params: this.params.map(function (param, index) {
42415 return {
42416 name: param,
42417 type: types[index]
42418 };
42419 }),
42420 expr: this.expr
42421 };
42422 };
42423 /**
42424 * Instantiate an FunctionAssignmentNode from its JSON representation
42425 * @param {Object} json An object structured like
42426 * `{"mathjs": "FunctionAssignmentNode", name: ..., params: ..., expr: ...}`,
42427 * where mathjs is optional
42428 * @returns {FunctionAssignmentNode}
42429 */
42430
42431
42432 FunctionAssignmentNode.fromJSON = function (json) {
42433 return new FunctionAssignmentNode(json.name, json.params, json.expr);
42434 };
42435 /**
42436 * get HTML representation
42437 * @param {Object} options
42438 * @return {string} str
42439 */
42440
42441
42442 FunctionAssignmentNode.prototype.toHTML = function (options) {
42443 var parenthesis = options && options.parenthesis ? options.parenthesis : 'keep';
42444 var params = [];
42445
42446 for (var i = 0; i < this.params.length; i++) {
42447 params.push('<span class="math-symbol math-parameter">' + Object(utils_string["c" /* escape */])(this.params[i]) + '</span>');
42448 }
42449
42450 var expr = this.expr.toHTML(options);
42451
42452 if (needParenthesis(this, parenthesis)) {
42453 expr = '<span class="math-parenthesis math-round-parenthesis">(</span>' + expr + '<span class="math-parenthesis math-round-parenthesis">)</span>';
42454 }
42455
42456 return '<span class="math-function">' + Object(utils_string["c" /* escape */])(this.name) + '</span>' + '<span class="math-parenthesis math-round-parenthesis">(</span>' + params.join('<span class="math-separator">,</span>') + '<span class="math-parenthesis math-round-parenthesis">)</span><span class="math-operator math-assignment-operator math-variable-assignment-operator math-binary-operator">=</span>' + expr;
42457 };
42458 /**
42459 * get LaTeX representation
42460 * @param {Object} options
42461 * @return {string} str
42462 */
42463
42464
42465 FunctionAssignmentNode.prototype._toTex = function (options) {
42466 var parenthesis = options && options.parenthesis ? options.parenthesis : 'keep';
42467 var expr = this.expr.toTex(options);
42468
42469 if (needParenthesis(this, parenthesis)) {
42470 expr = "\\left(".concat(expr, "\\right)");
42471 }
42472
42473 return '\\mathrm{' + this.name + '}\\left(' + this.params.map(toSymbol).join(',') + '\\right):=' + expr;
42474 };
42475
42476 return FunctionAssignmentNode;
42477}, {
42478 isClass: true,
42479 isNode: true
42480});
42481// CONCATENATED MODULE: ./src/expression/transform/index.transform.js
42482
42483
42484var index_transform_name = 'index';
42485var index_transform_dependencies = ['Index'];
42486var createIndexTransform =
42487/* #__PURE__ */
42488Object(factory["a" /* factory */])(index_transform_name, index_transform_dependencies, function (_ref) {
42489 var Index = _ref.Index;
42490
42491 /**
42492 * Attach a transform function to math.index
42493 * Adds a property transform containing the transform function.
42494 *
42495 * This transform creates a one-based index instead of a zero-based index
42496 */
42497 return function indexTransform() {
42498 var args = [];
42499
42500 for (var i = 0, ii = arguments.length; i < ii; i++) {
42501 var arg = arguments[i]; // change from one-based to zero based, and convert BigNumber to number
42502
42503 if (Object(is["D" /* isRange */])(arg)) {
42504 arg.start--;
42505 arg.end -= arg.step > 0 ? 0 : 2;
42506 } else if (arg && arg.isSet === true) {
42507 arg = arg.map(function (v) {
42508 return v - 1;
42509 });
42510 } else if (Object(is["b" /* isArray */])(arg) || Object(is["v" /* isMatrix */])(arg)) {
42511 arg = arg.map(function (v) {
42512 return v - 1;
42513 });
42514 } else if (Object(is["y" /* isNumber */])(arg)) {
42515 arg--;
42516 } else if (Object(is["e" /* isBigNumber */])(arg)) {
42517 arg = arg.toNumber() - 1;
42518 } else if (typeof arg === 'string') {// leave as is
42519 } else {
42520 throw new TypeError('Dimension must be an Array, Matrix, number, string, or Range');
42521 }
42522
42523 args[i] = arg;
42524 }
42525
42526 var res = new Index();
42527 Index.apply(res, args);
42528 return res;
42529 };
42530}, {
42531 isTransformFunction: true
42532});
42533// CONCATENATED MODULE: ./src/expression/node/IndexNode.js
42534function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); }
42535
42536function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance"); }
42537
42538function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); }
42539
42540function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } }
42541
42542
42543
42544
42545
42546
42547var IndexNode_name = 'IndexNode';
42548var IndexNode_dependencies = ['Range', 'Node', 'Index', 'size'];
42549var createIndexNode =
42550/* #__PURE__ */
42551Object(factory["a" /* factory */])(IndexNode_name, IndexNode_dependencies, function (_ref) {
42552 var Range = _ref.Range,
42553 Node = _ref.Node,
42554 Index = _ref.Index,
42555 size = _ref.size;
42556 var index = createIndexTransform({
42557 Index: Index
42558 });
42559 /**
42560 * @constructor IndexNode
42561 * @extends Node
42562 *
42563 * Describes a subset of a matrix or an object property.
42564 * Cannot be used on its own, needs to be used within an AccessorNode or
42565 * AssignmentNode.
42566 *
42567 * @param {Node[]} dimensions
42568 * @param {boolean} [dotNotation=false] Optional property describing whether
42569 * this index was written using dot
42570 * notation like `a.b`, or using bracket
42571 * notation like `a["b"]` (default).
42572 * Used to stringify an IndexNode.
42573 */
42574
42575 function IndexNode(dimensions, dotNotation) {
42576 if (!(this instanceof IndexNode)) {
42577 throw new SyntaxError('Constructor must be called with the new operator');
42578 }
42579
42580 this.dimensions = dimensions;
42581 this.dotNotation = dotNotation || false; // validate input
42582
42583 if (!Array.isArray(dimensions) || !dimensions.every(is["w" /* isNode */])) {
42584 throw new TypeError('Array containing Nodes expected for parameter "dimensions"');
42585 }
42586
42587 if (this.dotNotation && !this.isObjectProperty()) {
42588 throw new Error('dotNotation only applicable for object properties');
42589 } // TODO: deprecated since v3, remove some day
42590
42591
42592 var deprecated = function deprecated() {
42593 throw new Error('Property `IndexNode.object` is deprecated, use `IndexNode.fn` instead');
42594 };
42595
42596 Object.defineProperty(this, 'object', {
42597 get: deprecated,
42598 set: deprecated
42599 });
42600 }
42601
42602 IndexNode.prototype = new Node();
42603 IndexNode.prototype.type = 'IndexNode';
42604 IndexNode.prototype.isIndexNode = true;
42605 /**
42606 * Compile a node into a JavaScript function.
42607 * This basically pre-calculates as much as possible and only leaves open
42608 * calculations which depend on a dynamic scope with variables.
42609 * @param {Object} math Math.js namespace with functions and constants.
42610 * @param {Object} argNames An object with argument names as key and `true`
42611 * as value. Used in the SymbolNode to optimize
42612 * for arguments from user assigned functions
42613 * (see FunctionAssignmentNode) or special symbols
42614 * like `end` (see IndexNode).
42615 * @return {function} Returns a function which can be called like:
42616 * evalNode(scope: Object, args: Object, context: *)
42617 */
42618
42619 IndexNode.prototype._compile = function (math, argNames) {
42620 // TODO: implement support for bignumber (currently bignumbers are silently
42621 // reduced to numbers when changing the value to zero-based)
42622 // TODO: Optimization: when the range values are ConstantNodes,
42623 // we can beforehand resolve the zero-based value
42624 // optimization for a simple object property
42625 var evalDimensions = Object(utils_array["m" /* map */])(this.dimensions, function (range, i) {
42626 if (Object(is["E" /* isRangeNode */])(range)) {
42627 if (range.needsEnd()) {
42628 // create a range containing end (like '4:end')
42629 var childArgNames = Object.create(argNames);
42630 childArgNames.end = true;
42631
42632 var evalStart = range.start._compile(math, childArgNames);
42633
42634 var evalEnd = range.end._compile(math, childArgNames);
42635
42636 var evalStep = range.step ? range.step._compile(math, childArgNames) : function () {
42637 return 1;
42638 };
42639 return function evalDimension(scope, args, context) {
42640 var s = size(context).valueOf();
42641 var childArgs = Object.create(args);
42642 childArgs.end = s[i];
42643 return createRange(evalStart(scope, childArgs, context), evalEnd(scope, childArgs, context), evalStep(scope, childArgs, context));
42644 };
42645 } else {
42646 // create range
42647 var _evalStart = range.start._compile(math, argNames);
42648
42649 var _evalEnd = range.end._compile(math, argNames);
42650
42651 var _evalStep = range.step ? range.step._compile(math, argNames) : function () {
42652 return 1;
42653 };
42654
42655 return function evalDimension(scope, args, context) {
42656 return createRange(_evalStart(scope, args, context), _evalEnd(scope, args, context), _evalStep(scope, args, context));
42657 };
42658 }
42659 } else if (Object(is["J" /* isSymbolNode */])(range) && range.name === 'end') {
42660 // SymbolNode 'end'
42661 var _childArgNames = Object.create(argNames);
42662
42663 _childArgNames.end = true;
42664
42665 var evalRange = range._compile(math, _childArgNames);
42666
42667 return function evalDimension(scope, args, context) {
42668 var s = size(context).valueOf();
42669 var childArgs = Object.create(args);
42670 childArgs.end = s[i];
42671 return evalRange(scope, childArgs, context);
42672 };
42673 } else {
42674 // ConstantNode
42675 var _evalRange = range._compile(math, argNames);
42676
42677 return function evalDimension(scope, args, context) {
42678 return _evalRange(scope, args, context);
42679 };
42680 }
42681 });
42682 return function evalIndexNode(scope, args, context) {
42683 var dimensions = Object(utils_array["m" /* map */])(evalDimensions, function (evalDimension) {
42684 return evalDimension(scope, args, context);
42685 });
42686 return index.apply(void 0, _toConsumableArray(dimensions));
42687 };
42688 };
42689 /**
42690 * Execute a callback for each of the child nodes of this node
42691 * @param {function(child: Node, path: string, parent: Node)} callback
42692 */
42693
42694
42695 IndexNode.prototype.forEach = function (callback) {
42696 for (var i = 0; i < this.dimensions.length; i++) {
42697 callback(this.dimensions[i], 'dimensions[' + i + ']', this);
42698 }
42699 };
42700 /**
42701 * Create a new IndexNode having it's childs be the results of calling
42702 * the provided callback function for each of the childs of the original node.
42703 * @param {function(child: Node, path: string, parent: Node): Node} callback
42704 * @returns {IndexNode} Returns a transformed copy of the node
42705 */
42706
42707
42708 IndexNode.prototype.map = function (callback) {
42709 var dimensions = [];
42710
42711 for (var i = 0; i < this.dimensions.length; i++) {
42712 dimensions[i] = this._ifNode(callback(this.dimensions[i], 'dimensions[' + i + ']', this));
42713 }
42714
42715 return new IndexNode(dimensions, this.dotNotation);
42716 };
42717 /**
42718 * Create a clone of this node, a shallow copy
42719 * @return {IndexNode}
42720 */
42721
42722
42723 IndexNode.prototype.clone = function () {
42724 return new IndexNode(this.dimensions.slice(0), this.dotNotation);
42725 };
42726 /**
42727 * Test whether this IndexNode contains a single property name
42728 * @return {boolean}
42729 */
42730
42731
42732 IndexNode.prototype.isObjectProperty = function () {
42733 return this.dimensions.length === 1 && Object(is["l" /* isConstantNode */])(this.dimensions[0]) && typeof this.dimensions[0].value === 'string';
42734 };
42735 /**
42736 * Returns the property name if IndexNode contains a property.
42737 * If not, returns null.
42738 * @return {string | null}
42739 */
42740
42741
42742 IndexNode.prototype.getObjectProperty = function () {
42743 return this.isObjectProperty() ? this.dimensions[0].value : null;
42744 };
42745 /**
42746 * Get string representation
42747 * @param {Object} options
42748 * @return {string} str
42749 */
42750
42751
42752 IndexNode.prototype._toString = function (options) {
42753 // format the parameters like "[1, 0:5]"
42754 return this.dotNotation ? '.' + this.getObjectProperty() : '[' + this.dimensions.join(', ') + ']';
42755 };
42756 /**
42757 * Get a JSON representation of the node
42758 * @returns {Object}
42759 */
42760
42761
42762 IndexNode.prototype.toJSON = function () {
42763 return {
42764 mathjs: 'IndexNode',
42765 dimensions: this.dimensions,
42766 dotNotation: this.dotNotation
42767 };
42768 };
42769 /**
42770 * Instantiate an IndexNode from its JSON representation
42771 * @param {Object} json An object structured like
42772 * `{"mathjs": "IndexNode", dimensions: [...], dotNotation: false}`,
42773 * where mathjs is optional
42774 * @returns {IndexNode}
42775 */
42776
42777
42778 IndexNode.fromJSON = function (json) {
42779 return new IndexNode(json.dimensions, json.dotNotation);
42780 };
42781 /**
42782 * Get HTML representation
42783 * @param {Object} options
42784 * @return {string} str
42785 */
42786
42787
42788 IndexNode.prototype.toHTML = function (options) {
42789 // format the parameters like "[1, 0:5]"
42790 var dimensions = [];
42791
42792 for (var i = 0; i < this.dimensions.length; i++) {
42793 dimensions[i] = this.dimensions[i].toHTML();
42794 }
42795
42796 if (this.dotNotation) {
42797 return '<span class="math-operator math-accessor-operator">.</span>' + '<span class="math-symbol math-property">' + Object(utils_string["c" /* escape */])(this.getObjectProperty()) + '</span>';
42798 } else {
42799 return '<span class="math-parenthesis math-square-parenthesis">[</span>' + dimensions.join('<span class="math-separator">,</span>') + '<span class="math-parenthesis math-square-parenthesis">]</span>';
42800 }
42801 };
42802 /**
42803 * Get LaTeX representation
42804 * @param {Object} options
42805 * @return {string} str
42806 */
42807
42808
42809 IndexNode.prototype._toTex = function (options) {
42810 var dimensions = this.dimensions.map(function (range) {
42811 return range.toTex(options);
42812 });
42813 return this.dotNotation ? '.' + this.getObjectProperty() + '' : '_{' + dimensions.join(',') + '}';
42814 }; // helper function to create a Range from start, step and end
42815
42816
42817 function createRange(start, end, step) {
42818 return new Range(Object(is["e" /* isBigNumber */])(start) ? start.toNumber() : start, Object(is["e" /* isBigNumber */])(end) ? end.toNumber() : end, Object(is["e" /* isBigNumber */])(step) ? step.toNumber() : step);
42819 }
42820
42821 return IndexNode;
42822}, {
42823 isClass: true,
42824 isNode: true
42825});
42826// CONCATENATED MODULE: ./src/expression/node/ObjectNode.js
42827function ObjectNode_typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { ObjectNode_typeof = function _typeof(obj) { return typeof obj; }; } else { ObjectNode_typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return ObjectNode_typeof(obj); }
42828
42829
42830
42831
42832
42833
42834var ObjectNode_name = 'ObjectNode';
42835var ObjectNode_dependencies = ['Node'];
42836var createObjectNode =
42837/* #__PURE__ */
42838Object(factory["a" /* factory */])(ObjectNode_name, ObjectNode_dependencies, function (_ref) {
42839 var Node = _ref.Node;
42840
42841 /**
42842 * @constructor ObjectNode
42843 * @extends {Node}
42844 * Holds an object with keys/values
42845 * @param {Object.<string, Node>} [properties] object with key/value pairs
42846 */
42847 function ObjectNode(properties) {
42848 if (!(this instanceof ObjectNode)) {
42849 throw new SyntaxError('Constructor must be called with the new operator');
42850 }
42851
42852 this.properties = properties || {}; // validate input
42853
42854 if (properties) {
42855 if (!(ObjectNode_typeof(properties) === 'object') || !Object.keys(properties).every(function (key) {
42856 return Object(is["w" /* isNode */])(properties[key]);
42857 })) {
42858 throw new TypeError('Object containing Nodes expected');
42859 }
42860 }
42861 }
42862
42863 ObjectNode.prototype = new Node();
42864 ObjectNode.prototype.type = 'ObjectNode';
42865 ObjectNode.prototype.isObjectNode = true;
42866 /**
42867 * Compile a node into a JavaScript function.
42868 * This basically pre-calculates as much as possible and only leaves open
42869 * calculations which depend on a dynamic scope with variables.
42870 * @param {Object} math Math.js namespace with functions and constants.
42871 * @param {Object} argNames An object with argument names as key and `true`
42872 * as value. Used in the SymbolNode to optimize
42873 * for arguments from user assigned functions
42874 * (see FunctionAssignmentNode) or special symbols
42875 * like `end` (see IndexNode).
42876 * @return {function} Returns a function which can be called like:
42877 * evalNode(scope: Object, args: Object, context: *)
42878 */
42879
42880 ObjectNode.prototype._compile = function (math, argNames) {
42881 var evalEntries = {};
42882
42883 for (var key in this.properties) {
42884 if (Object(utils_object["f" /* hasOwnProperty */])(this.properties, key)) {
42885 // we stringify/parse the key here to resolve unicode characters,
42886 // so you cannot create a key like {"co\\u006Estructor": null}
42887 var stringifiedKey = Object(utils_string["e" /* stringify */])(key);
42888 var parsedKey = JSON.parse(stringifiedKey);
42889
42890 if (!isSafeProperty(this.properties, parsedKey)) {
42891 throw new Error('No access to property "' + parsedKey + '"');
42892 }
42893
42894 evalEntries[parsedKey] = this.properties[key]._compile(math, argNames);
42895 }
42896 }
42897
42898 return function evalObjectNode(scope, args, context) {
42899 var obj = {};
42900
42901 for (var _key in evalEntries) {
42902 if (Object(utils_object["f" /* hasOwnProperty */])(evalEntries, _key)) {
42903 obj[_key] = evalEntries[_key](scope, args, context);
42904 }
42905 }
42906
42907 return obj;
42908 };
42909 };
42910 /**
42911 * Execute a callback for each of the child nodes of this node
42912 * @param {function(child: Node, path: string, parent: Node)} callback
42913 */
42914
42915
42916 ObjectNode.prototype.forEach = function (callback) {
42917 for (var key in this.properties) {
42918 if (Object(utils_object["f" /* hasOwnProperty */])(this.properties, key)) {
42919 callback(this.properties[key], 'properties[' + Object(utils_string["e" /* stringify */])(key) + ']', this);
42920 }
42921 }
42922 };
42923 /**
42924 * Create a new ObjectNode having it's childs be the results of calling
42925 * the provided callback function for each of the childs of the original node.
42926 * @param {function(child: Node, path: string, parent: Node): Node} callback
42927 * @returns {ObjectNode} Returns a transformed copy of the node
42928 */
42929
42930
42931 ObjectNode.prototype.map = function (callback) {
42932 var properties = {};
42933
42934 for (var key in this.properties) {
42935 if (Object(utils_object["f" /* hasOwnProperty */])(this.properties, key)) {
42936 properties[key] = this._ifNode(callback(this.properties[key], 'properties[' + Object(utils_string["e" /* stringify */])(key) + ']', this));
42937 }
42938 }
42939
42940 return new ObjectNode(properties);
42941 };
42942 /**
42943 * Create a clone of this node, a shallow copy
42944 * @return {ObjectNode}
42945 */
42946
42947
42948 ObjectNode.prototype.clone = function () {
42949 var properties = {};
42950
42951 for (var key in this.properties) {
42952 if (Object(utils_object["f" /* hasOwnProperty */])(this.properties, key)) {
42953 properties[key] = this.properties[key];
42954 }
42955 }
42956
42957 return new ObjectNode(properties);
42958 };
42959 /**
42960 * Get string representation
42961 * @param {Object} options
42962 * @return {string} str
42963 * @override
42964 */
42965
42966
42967 ObjectNode.prototype._toString = function (options) {
42968 var entries = [];
42969
42970 for (var key in this.properties) {
42971 if (Object(utils_object["f" /* hasOwnProperty */])(this.properties, key)) {
42972 entries.push(Object(utils_string["e" /* stringify */])(key) + ': ' + this.properties[key].toString(options));
42973 }
42974 }
42975
42976 return '{' + entries.join(', ') + '}';
42977 };
42978 /**
42979 * Get a JSON representation of the node
42980 * @returns {Object}
42981 */
42982
42983
42984 ObjectNode.prototype.toJSON = function () {
42985 return {
42986 mathjs: 'ObjectNode',
42987 properties: this.properties
42988 };
42989 };
42990 /**
42991 * Instantiate an OperatorNode from its JSON representation
42992 * @param {Object} json An object structured like
42993 * `{"mathjs": "ObjectNode", "properties": {...}}`,
42994 * where mathjs is optional
42995 * @returns {ObjectNode}
42996 */
42997
42998
42999 ObjectNode.fromJSON = function (json) {
43000 return new ObjectNode(json.properties);
43001 };
43002 /**
43003 * Get HTML representation
43004 * @param {Object} options
43005 * @return {string} str
43006 * @override
43007 */
43008
43009
43010 ObjectNode.prototype.toHTML = function (options) {
43011 var entries = [];
43012
43013 for (var key in this.properties) {
43014 if (Object(utils_object["f" /* hasOwnProperty */])(this.properties, key)) {
43015 entries.push('<span class="math-symbol math-property">' + Object(utils_string["c" /* escape */])(key) + '</span>' + '<span class="math-operator math-assignment-operator math-property-assignment-operator math-binary-operator">:</span>' + this.properties[key].toHTML(options));
43016 }
43017 }
43018
43019 return '<span class="math-parenthesis math-curly-parenthesis">{</span>' + entries.join('<span class="math-separator">,</span>') + '<span class="math-parenthesis math-curly-parenthesis">}</span>';
43020 };
43021 /**
43022 * Get LaTeX representation
43023 * @param {Object} options
43024 * @return {string} str
43025 */
43026
43027
43028 ObjectNode.prototype._toTex = function (options) {
43029 var entries = [];
43030
43031 for (var key in this.properties) {
43032 if (Object(utils_object["f" /* hasOwnProperty */])(this.properties, key)) {
43033 entries.push('\\mathbf{' + key + ':} & ' + this.properties[key].toTex(options) + '\\\\');
43034 }
43035 }
43036
43037 return "\\left\\{\\begin{array}{ll}".concat(entries.join('\n'), "\\end{array}\\right\\}");
43038 };
43039
43040 return ObjectNode;
43041}, {
43042 isClass: true,
43043 isNode: true
43044});
43045// CONCATENATED MODULE: ./src/expression/node/OperatorNode.js
43046
43047
43048
43049
43050
43051
43052
43053var OperatorNode_name = 'OperatorNode';
43054var OperatorNode_dependencies = ['Node'];
43055var createOperatorNode =
43056/* #__PURE__ */
43057Object(factory["a" /* factory */])(OperatorNode_name, OperatorNode_dependencies, function (_ref) {
43058 var Node = _ref.Node;
43059
43060 /**
43061 * @constructor OperatorNode
43062 * @extends {Node}
43063 * An operator with two arguments, like 2+3
43064 *
43065 * @param {string} op Operator name, for example '+'
43066 * @param {string} fn Function name, for example 'add'
43067 * @param {Node[]} args Operator arguments
43068 * @param {boolean} [implicit] Is this an implicit multiplication?
43069 */
43070 function OperatorNode(op, fn, args, implicit) {
43071 if (!(this instanceof OperatorNode)) {
43072 throw new SyntaxError('Constructor must be called with the new operator');
43073 } // validate input
43074
43075
43076 if (typeof op !== 'string') {
43077 throw new TypeError('string expected for parameter "op"');
43078 }
43079
43080 if (typeof fn !== 'string') {
43081 throw new TypeError('string expected for parameter "fn"');
43082 }
43083
43084 if (!Array.isArray(args) || !args.every(is["w" /* isNode */])) {
43085 throw new TypeError('Array containing Nodes expected for parameter "args"');
43086 }
43087
43088 this.implicit = implicit === true;
43089 this.op = op;
43090 this.fn = fn;
43091 this.args = args || [];
43092 }
43093
43094 OperatorNode.prototype = new Node();
43095 OperatorNode.prototype.type = 'OperatorNode';
43096 OperatorNode.prototype.isOperatorNode = true;
43097 /**
43098 * Compile a node into a JavaScript function.
43099 * This basically pre-calculates as much as possible and only leaves open
43100 * calculations which depend on a dynamic scope with variables.
43101 * @param {Object} math Math.js namespace with functions and constants.
43102 * @param {Object} argNames An object with argument names as key and `true`
43103 * as value. Used in the SymbolNode to optimize
43104 * for arguments from user assigned functions
43105 * (see FunctionAssignmentNode) or special symbols
43106 * like `end` (see IndexNode).
43107 * @return {function} Returns a function which can be called like:
43108 * evalNode(scope: Object, args: Object, context: *)
43109 */
43110
43111 OperatorNode.prototype._compile = function (math, argNames) {
43112 // validate fn
43113 if (typeof this.fn !== 'string' || !isSafeMethod(math, this.fn)) {
43114 if (!math[this.fn]) {
43115 throw new Error('Function ' + this.fn + ' missing in provided namespace "math"');
43116 } else {
43117 throw new Error('No access to function "' + this.fn + '"');
43118 }
43119 }
43120
43121 var fn = getSafeProperty(math, this.fn);
43122 var evalArgs = Object(utils_array["m" /* map */])(this.args, function (arg) {
43123 return arg._compile(math, argNames);
43124 });
43125
43126 if (evalArgs.length === 1) {
43127 var evalArg0 = evalArgs[0];
43128 return function evalOperatorNode(scope, args, context) {
43129 return fn(evalArg0(scope, args, context));
43130 };
43131 } else if (evalArgs.length === 2) {
43132 var _evalArg = evalArgs[0];
43133 var evalArg1 = evalArgs[1];
43134 return function evalOperatorNode(scope, args, context) {
43135 return fn(_evalArg(scope, args, context), evalArg1(scope, args, context));
43136 };
43137 } else {
43138 return function evalOperatorNode(scope, args, context) {
43139 return fn.apply(null, Object(utils_array["m" /* map */])(evalArgs, function (evalArg) {
43140 return evalArg(scope, args, context);
43141 }));
43142 };
43143 }
43144 };
43145 /**
43146 * Execute a callback for each of the child nodes of this node
43147 * @param {function(child: Node, path: string, parent: Node)} callback
43148 */
43149
43150
43151 OperatorNode.prototype.forEach = function (callback) {
43152 for (var i = 0; i < this.args.length; i++) {
43153 callback(this.args[i], 'args[' + i + ']', this);
43154 }
43155 };
43156 /**
43157 * Create a new OperatorNode having it's childs be the results of calling
43158 * the provided callback function for each of the childs of the original node.
43159 * @param {function(child: Node, path: string, parent: Node): Node} callback
43160 * @returns {OperatorNode} Returns a transformed copy of the node
43161 */
43162
43163
43164 OperatorNode.prototype.map = function (callback) {
43165 var args = [];
43166
43167 for (var i = 0; i < this.args.length; i++) {
43168 args[i] = this._ifNode(callback(this.args[i], 'args[' + i + ']', this));
43169 }
43170
43171 return new OperatorNode(this.op, this.fn, args, this.implicit);
43172 };
43173 /**
43174 * Create a clone of this node, a shallow copy
43175 * @return {OperatorNode}
43176 */
43177
43178
43179 OperatorNode.prototype.clone = function () {
43180 return new OperatorNode(this.op, this.fn, this.args.slice(0), this.implicit);
43181 };
43182 /**
43183 * Check whether this is an unary OperatorNode:
43184 * has exactly one argument, like `-a`.
43185 * @return {boolean} Returns true when an unary operator node, false otherwise.
43186 */
43187
43188
43189 OperatorNode.prototype.isUnary = function () {
43190 return this.args.length === 1;
43191 };
43192 /**
43193 * Check whether this is a binary OperatorNode:
43194 * has exactly two arguments, like `a + b`.
43195 * @return {boolean} Returns true when a binary operator node, false otherwise.
43196 */
43197
43198
43199 OperatorNode.prototype.isBinary = function () {
43200 return this.args.length === 2;
43201 };
43202 /**
43203 * Calculate which parentheses are necessary. Gets an OperatorNode
43204 * (which is the root of the tree) and an Array of Nodes
43205 * (this.args) and returns an array where 'true' means that an argument
43206 * has to be enclosed in parentheses whereas 'false' means the opposite.
43207 *
43208 * @param {OperatorNode} root
43209 * @param {string} parenthesis
43210 * @param {Node[]} args
43211 * @param {boolean} latex
43212 * @return {boolean[]}
43213 * @private
43214 */
43215
43216
43217 function calculateNecessaryParentheses(root, parenthesis, implicit, args, latex) {
43218 // precedence of the root OperatorNode
43219 var precedence = getPrecedence(root, parenthesis);
43220 var associativity = getAssociativity(root, parenthesis);
43221
43222 if (parenthesis === 'all' || args.length > 2 && root.getIdentifier() !== 'OperatorNode:add' && root.getIdentifier() !== 'OperatorNode:multiply') {
43223 return args.map(function (arg) {
43224 switch (arg.getContent().type) {
43225 // Nodes that don't need extra parentheses
43226 case 'ArrayNode':
43227 case 'ConstantNode':
43228 case 'SymbolNode':
43229 case 'ParenthesisNode':
43230 return false;
43231
43232 default:
43233 return true;
43234 }
43235 });
43236 }
43237
43238 var result;
43239
43240 switch (args.length) {
43241 case 0:
43242 result = [];
43243 break;
43244
43245 case 1:
43246 // unary operators
43247 {
43248 // precedence of the operand
43249 var operandPrecedence = getPrecedence(args[0], parenthesis); // handle special cases for LaTeX, where some of the parentheses aren't needed
43250
43251 if (latex && operandPrecedence !== null) {
43252 var operandIdentifier;
43253 var rootIdentifier;
43254
43255 if (parenthesis === 'keep') {
43256 operandIdentifier = args[0].getIdentifier();
43257 rootIdentifier = root.getIdentifier();
43258 } else {
43259 // Ignore Parenthesis Nodes when not in 'keep' mode
43260 operandIdentifier = args[0].getContent().getIdentifier();
43261 rootIdentifier = root.getContent().getIdentifier();
43262 }
43263
43264 if (operators_properties[precedence][rootIdentifier].latexLeftParens === false) {
43265 result = [false];
43266 break;
43267 }
43268
43269 if (operators_properties[operandPrecedence][operandIdentifier].latexParens === false) {
43270 result = [false];
43271 break;
43272 }
43273 }
43274
43275 if (operandPrecedence === null) {
43276 // if the operand has no defined precedence, no parens are needed
43277 result = [false];
43278 break;
43279 }
43280
43281 if (operandPrecedence <= precedence) {
43282 // if the operands precedence is lower, parens are needed
43283 result = [true];
43284 break;
43285 } // otherwise, no parens needed
43286
43287
43288 result = [false];
43289 }
43290 break;
43291
43292 case 2:
43293 // binary operators
43294 {
43295 var lhsParens; // left hand side needs parenthesis?
43296 // precedence of the left hand side
43297
43298 var lhsPrecedence = getPrecedence(args[0], parenthesis); // is the root node associative with the left hand side
43299
43300 var assocWithLhs = isAssociativeWith(root, args[0], parenthesis);
43301
43302 if (lhsPrecedence === null) {
43303 // if the left hand side has no defined precedence, no parens are needed
43304 // FunctionNode for example
43305 lhsParens = false;
43306 } else if (lhsPrecedence === precedence && associativity === 'right' && !assocWithLhs) {
43307 // In case of equal precedence, if the root node is left associative
43308 // parens are **never** necessary for the left hand side.
43309 // If it is right associative however, parens are necessary
43310 // if the root node isn't associative with the left hand side
43311 lhsParens = true;
43312 } else if (lhsPrecedence < precedence) {
43313 lhsParens = true;
43314 } else {
43315 lhsParens = false;
43316 }
43317
43318 var rhsParens; // right hand side needs parenthesis?
43319 // precedence of the right hand side
43320
43321 var rhsPrecedence = getPrecedence(args[1], parenthesis); // is the root node associative with the right hand side?
43322
43323 var assocWithRhs = isAssociativeWith(root, args[1], parenthesis);
43324
43325 if (rhsPrecedence === null) {
43326 // if the right hand side has no defined precedence, no parens are needed
43327 // FunctionNode for example
43328 rhsParens = false;
43329 } else if (rhsPrecedence === precedence && associativity === 'left' && !assocWithRhs) {
43330 // In case of equal precedence, if the root node is right associative
43331 // parens are **never** necessary for the right hand side.
43332 // If it is left associative however, parens are necessary
43333 // if the root node isn't associative with the right hand side
43334 rhsParens = true;
43335 } else if (rhsPrecedence < precedence) {
43336 rhsParens = true;
43337 } else {
43338 rhsParens = false;
43339 } // handle special cases for LaTeX, where some of the parentheses aren't needed
43340
43341
43342 if (latex) {
43343 var _rootIdentifier;
43344
43345 var lhsIdentifier;
43346 var rhsIdentifier;
43347
43348 if (parenthesis === 'keep') {
43349 _rootIdentifier = root.getIdentifier();
43350 lhsIdentifier = root.args[0].getIdentifier();
43351 rhsIdentifier = root.args[1].getIdentifier();
43352 } else {
43353 // Ignore ParenthesisNodes when not in 'keep' mode
43354 _rootIdentifier = root.getContent().getIdentifier();
43355 lhsIdentifier = root.args[0].getContent().getIdentifier();
43356 rhsIdentifier = root.args[1].getContent().getIdentifier();
43357 }
43358
43359 if (lhsPrecedence !== null) {
43360 if (operators_properties[precedence][_rootIdentifier].latexLeftParens === false) {
43361 lhsParens = false;
43362 }
43363
43364 if (operators_properties[lhsPrecedence][lhsIdentifier].latexParens === false) {
43365 lhsParens = false;
43366 }
43367 }
43368
43369 if (rhsPrecedence !== null) {
43370 if (operators_properties[precedence][_rootIdentifier].latexRightParens === false) {
43371 rhsParens = false;
43372 }
43373
43374 if (operators_properties[rhsPrecedence][rhsIdentifier].latexParens === false) {
43375 rhsParens = false;
43376 }
43377 }
43378 }
43379
43380 result = [lhsParens, rhsParens];
43381 }
43382 break;
43383
43384 default:
43385 if (root.getIdentifier() === 'OperatorNode:add' || root.getIdentifier() === 'OperatorNode:multiply') {
43386 result = args.map(function (arg) {
43387 var argPrecedence = getPrecedence(arg, parenthesis);
43388 var assocWithArg = isAssociativeWith(root, arg, parenthesis);
43389 var argAssociativity = getAssociativity(arg, parenthesis);
43390
43391 if (argPrecedence === null) {
43392 // if the argument has no defined precedence, no parens are needed
43393 return false;
43394 } else if (precedence === argPrecedence && associativity === argAssociativity && !assocWithArg) {
43395 return true;
43396 } else if (argPrecedence < precedence) {
43397 return true;
43398 }
43399
43400 return false;
43401 });
43402 }
43403
43404 break;
43405 } // handles an edge case of 'auto' parentheses with implicit multiplication of ConstantNode
43406 // In that case print parentheses for ParenthesisNodes even though they normally wouldn't be
43407 // printed.
43408
43409
43410 if (args.length >= 2 && root.getIdentifier() === 'OperatorNode:multiply' && root.implicit && parenthesis === 'auto' && implicit === 'hide') {
43411 result = args.map(function (arg, index) {
43412 var isParenthesisNode = arg.getIdentifier() === 'ParenthesisNode';
43413
43414 if (result[index] || isParenthesisNode) {
43415 // put in parenthesis?
43416 return true;
43417 }
43418
43419 return false;
43420 });
43421 }
43422
43423 return result;
43424 }
43425 /**
43426 * Get string representation.
43427 * @param {Object} options
43428 * @return {string} str
43429 */
43430
43431
43432 OperatorNode.prototype._toString = function (options) {
43433 var parenthesis = options && options.parenthesis ? options.parenthesis : 'keep';
43434 var implicit = options && options.implicit ? options.implicit : 'hide';
43435 var args = this.args;
43436 var parens = calculateNecessaryParentheses(this, parenthesis, implicit, args, false);
43437
43438 if (args.length === 1) {
43439 // unary operators
43440 var assoc = getAssociativity(this, parenthesis);
43441 var operand = args[0].toString(options);
43442
43443 if (parens[0]) {
43444 operand = '(' + operand + ')';
43445 } // for example for "not", we want a space between operand and argument
43446
43447
43448 var opIsNamed = /[a-zA-Z]+/.test(this.op);
43449
43450 if (assoc === 'right') {
43451 // prefix operator
43452 return this.op + (opIsNamed ? ' ' : '') + operand;
43453 } else if (assoc === 'left') {
43454 // postfix
43455 return operand + (opIsNamed ? ' ' : '') + this.op;
43456 } // fall back to postfix
43457
43458
43459 return operand + this.op;
43460 } else if (args.length === 2) {
43461 var lhs = args[0].toString(options); // left hand side
43462
43463 var rhs = args[1].toString(options); // right hand side
43464
43465 if (parens[0]) {
43466 // left hand side in parenthesis?
43467 lhs = '(' + lhs + ')';
43468 }
43469
43470 if (parens[1]) {
43471 // right hand side in parenthesis?
43472 rhs = '(' + rhs + ')';
43473 }
43474
43475 if (this.implicit && this.getIdentifier() === 'OperatorNode:multiply' && implicit === 'hide') {
43476 return lhs + ' ' + rhs;
43477 }
43478
43479 return lhs + ' ' + this.op + ' ' + rhs;
43480 } else if (args.length > 2 && (this.getIdentifier() === 'OperatorNode:add' || this.getIdentifier() === 'OperatorNode:multiply')) {
43481 var stringifiedArgs = args.map(function (arg, index) {
43482 arg = arg.toString(options);
43483
43484 if (parens[index]) {
43485 // put in parenthesis?
43486 arg = '(' + arg + ')';
43487 }
43488
43489 return arg;
43490 });
43491
43492 if (this.implicit && this.getIdentifier() === 'OperatorNode:multiply' && implicit === 'hide') {
43493 return stringifiedArgs.join(' ');
43494 }
43495
43496 return stringifiedArgs.join(' ' + this.op + ' ');
43497 } else {
43498 // fallback to formatting as a function call
43499 return this.fn + '(' + this.args.join(', ') + ')';
43500 }
43501 };
43502 /**
43503 * Get a JSON representation of the node
43504 * @returns {Object}
43505 */
43506
43507
43508 OperatorNode.prototype.toJSON = function () {
43509 return {
43510 mathjs: 'OperatorNode',
43511 op: this.op,
43512 fn: this.fn,
43513 args: this.args,
43514 implicit: this.implicit
43515 };
43516 };
43517 /**
43518 * Instantiate an OperatorNode from its JSON representation
43519 * @param {Object} json An object structured like
43520 * `{"mathjs": "OperatorNode", "op": "+", "fn": "add", "args": [...], "implicit": false}`,
43521 * where mathjs is optional
43522 * @returns {OperatorNode}
43523 */
43524
43525
43526 OperatorNode.fromJSON = function (json) {
43527 return new OperatorNode(json.op, json.fn, json.args, json.implicit);
43528 };
43529 /**
43530 * Get HTML representation.
43531 * @param {Object} options
43532 * @return {string} str
43533 */
43534
43535
43536 OperatorNode.prototype.toHTML = function (options) {
43537 var parenthesis = options && options.parenthesis ? options.parenthesis : 'keep';
43538 var implicit = options && options.implicit ? options.implicit : 'hide';
43539 var args = this.args;
43540 var parens = calculateNecessaryParentheses(this, parenthesis, implicit, args, false);
43541
43542 if (args.length === 1) {
43543 // unary operators
43544 var assoc = getAssociativity(this, parenthesis);
43545 var operand = args[0].toHTML(options);
43546
43547 if (parens[0]) {
43548 operand = '<span class="math-parenthesis math-round-parenthesis">(</span>' + operand + '<span class="math-parenthesis math-round-parenthesis">)</span>';
43549 }
43550
43551 if (assoc === 'right') {
43552 // prefix operator
43553 return '<span class="math-operator math-unary-operator math-lefthand-unary-operator">' + Object(utils_string["c" /* escape */])(this.op) + '</span>' + operand;
43554 } else {
43555 // postfix when assoc === 'left' or undefined
43556 return operand + '<span class="math-operator math-unary-operator math-righthand-unary-operator">' + Object(utils_string["c" /* escape */])(this.op) + '</span>';
43557 }
43558 } else if (args.length === 2) {
43559 // binary operatoes
43560 var lhs = args[0].toHTML(options); // left hand side
43561
43562 var rhs = args[1].toHTML(options); // right hand side
43563
43564 if (parens[0]) {
43565 // left hand side in parenthesis?
43566 lhs = '<span class="math-parenthesis math-round-parenthesis">(</span>' + lhs + '<span class="math-parenthesis math-round-parenthesis">)</span>';
43567 }
43568
43569 if (parens[1]) {
43570 // right hand side in parenthesis?
43571 rhs = '<span class="math-parenthesis math-round-parenthesis">(</span>' + rhs + '<span class="math-parenthesis math-round-parenthesis">)</span>';
43572 }
43573
43574 if (this.implicit && this.getIdentifier() === 'OperatorNode:multiply' && implicit === 'hide') {
43575 return lhs + '<span class="math-operator math-binary-operator math-implicit-binary-operator"></span>' + rhs;
43576 }
43577
43578 return lhs + '<span class="math-operator math-binary-operator math-explicit-binary-operator">' + Object(utils_string["c" /* escape */])(this.op) + '</span>' + rhs;
43579 } else {
43580 var stringifiedArgs = args.map(function (arg, index) {
43581 arg = arg.toHTML(options);
43582
43583 if (parens[index]) {
43584 // put in parenthesis?
43585 arg = '<span class="math-parenthesis math-round-parenthesis">(</span>' + arg + '<span class="math-parenthesis math-round-parenthesis">)</span>';
43586 }
43587
43588 return arg;
43589 });
43590
43591 if (args.length > 2 && (this.getIdentifier() === 'OperatorNode:add' || this.getIdentifier() === 'OperatorNode:multiply')) {
43592 if (this.implicit && this.getIdentifier() === 'OperatorNode:multiply' && implicit === 'hide') {
43593 return stringifiedArgs.join('<span class="math-operator math-binary-operator math-implicit-binary-operator"></span>');
43594 }
43595
43596 return stringifiedArgs.join('<span class="math-operator math-binary-operator math-explicit-binary-operator">' + Object(utils_string["c" /* escape */])(this.op) + '</span>');
43597 } else {
43598 // fallback to formatting as a function call
43599 return '<span class="math-function">' + Object(utils_string["c" /* escape */])(this.fn) + '</span><span class="math-paranthesis math-round-parenthesis">(</span>' + stringifiedArgs.join('<span class="math-separator">,</span>') + '<span class="math-paranthesis math-round-parenthesis">)</span>';
43600 }
43601 }
43602 };
43603 /**
43604 * Get LaTeX representation
43605 * @param {Object} options
43606 * @return {string} str
43607 */
43608
43609
43610 OperatorNode.prototype._toTex = function (options) {
43611 var parenthesis = options && options.parenthesis ? options.parenthesis : 'keep';
43612 var implicit = options && options.implicit ? options.implicit : 'hide';
43613 var args = this.args;
43614 var parens = calculateNecessaryParentheses(this, parenthesis, implicit, args, true);
43615 var op = latexOperators[this.fn];
43616 op = typeof op === 'undefined' ? this.op : op; // fall back to using this.op
43617
43618 if (args.length === 1) {
43619 // unary operators
43620 var assoc = getAssociativity(this, parenthesis);
43621 var operand = args[0].toTex(options);
43622
43623 if (parens[0]) {
43624 operand = "\\left(".concat(operand, "\\right)");
43625 }
43626
43627 if (assoc === 'right') {
43628 // prefix operator
43629 return op + operand;
43630 } else if (assoc === 'left') {
43631 // postfix operator
43632 return operand + op;
43633 } // fall back to postfix
43634
43635
43636 return operand + op;
43637 } else if (args.length === 2) {
43638 // binary operators
43639 var lhs = args[0]; // left hand side
43640
43641 var lhsTex = lhs.toTex(options);
43642
43643 if (parens[0]) {
43644 lhsTex = "\\left(".concat(lhsTex, "\\right)");
43645 }
43646
43647 var rhs = args[1]; // right hand side
43648
43649 var rhsTex = rhs.toTex(options);
43650
43651 if (parens[1]) {
43652 rhsTex = "\\left(".concat(rhsTex, "\\right)");
43653 } // handle some exceptions (due to the way LaTeX works)
43654
43655
43656 var lhsIdentifier;
43657
43658 if (parenthesis === 'keep') {
43659 lhsIdentifier = lhs.getIdentifier();
43660 } else {
43661 // Ignore ParenthesisNodes if in 'keep' mode
43662 lhsIdentifier = lhs.getContent().getIdentifier();
43663 }
43664
43665 switch (this.getIdentifier()) {
43666 case 'OperatorNode:divide':
43667 // op contains '\\frac' at this point
43668 return op + '{' + lhsTex + '}' + '{' + rhsTex + '}';
43669
43670 case 'OperatorNode:pow':
43671 lhsTex = '{' + lhsTex + '}';
43672 rhsTex = '{' + rhsTex + '}';
43673
43674 switch (lhsIdentifier) {
43675 case 'ConditionalNode': //
43676
43677 case 'OperatorNode:divide':
43678 lhsTex = "\\left(".concat(lhsTex, "\\right)");
43679 }
43680
43681 break;
43682
43683 case 'OperatorNode:multiply':
43684 if (this.implicit && implicit === 'hide') {
43685 return lhsTex + '~' + rhsTex;
43686 }
43687
43688 }
43689
43690 return lhsTex + op + rhsTex;
43691 } else if (args.length > 2 && (this.getIdentifier() === 'OperatorNode:add' || this.getIdentifier() === 'OperatorNode:multiply')) {
43692 var texifiedArgs = args.map(function (arg, index) {
43693 arg = arg.toTex(options);
43694
43695 if (parens[index]) {
43696 arg = "\\left(".concat(arg, "\\right)");
43697 }
43698
43699 return arg;
43700 });
43701
43702 if (this.getIdentifier() === 'OperatorNode:multiply' && this.implicit) {
43703 return texifiedArgs.join('~');
43704 }
43705
43706 return texifiedArgs.join(op);
43707 } else {
43708 // fall back to formatting as a function call
43709 // as this is a fallback, it doesn't use
43710 // fancy function names
43711 return '\\mathrm{' + this.fn + '}\\left(' + args.map(function (arg) {
43712 return arg.toTex(options);
43713 }).join(',') + '\\right)';
43714 }
43715 };
43716 /**
43717 * Get identifier.
43718 * @return {string}
43719 */
43720
43721
43722 OperatorNode.prototype.getIdentifier = function () {
43723 return this.type + ':' + this.fn;
43724 };
43725
43726 return OperatorNode;
43727}, {
43728 isClass: true,
43729 isNode: true
43730});
43731// CONCATENATED MODULE: ./src/expression/node/ParenthesisNode.js
43732
43733
43734var ParenthesisNode_name = 'ParenthesisNode';
43735var ParenthesisNode_dependencies = ['Node'];
43736var createParenthesisNode =
43737/* #__PURE__ */
43738Object(factory["a" /* factory */])(ParenthesisNode_name, ParenthesisNode_dependencies, function (_ref) {
43739 var Node = _ref.Node;
43740
43741 /**
43742 * @constructor ParenthesisNode
43743 * @extends {Node}
43744 * A parenthesis node describes manual parenthesis from the user input
43745 * @param {Node} content
43746 * @extends {Node}
43747 */
43748 function ParenthesisNode(content) {
43749 if (!(this instanceof ParenthesisNode)) {
43750 throw new SyntaxError('Constructor must be called with the new operator');
43751 } // validate input
43752
43753
43754 if (!Object(is["w" /* isNode */])(content)) {
43755 throw new TypeError('Node expected for parameter "content"');
43756 }
43757
43758 this.content = content;
43759 }
43760
43761 ParenthesisNode.prototype = new Node();
43762 ParenthesisNode.prototype.type = 'ParenthesisNode';
43763 ParenthesisNode.prototype.isParenthesisNode = true;
43764 /**
43765 * Compile a node into a JavaScript function.
43766 * This basically pre-calculates as much as possible and only leaves open
43767 * calculations which depend on a dynamic scope with variables.
43768 * @param {Object} math Math.js namespace with functions and constants.
43769 * @param {Object} argNames An object with argument names as key and `true`
43770 * as value. Used in the SymbolNode to optimize
43771 * for arguments from user assigned functions
43772 * (see FunctionAssignmentNode) or special symbols
43773 * like `end` (see IndexNode).
43774 * @return {function} Returns a function which can be called like:
43775 * evalNode(scope: Object, args: Object, context: *)
43776 */
43777
43778 ParenthesisNode.prototype._compile = function (math, argNames) {
43779 return this.content._compile(math, argNames);
43780 };
43781 /**
43782 * Get the content of the current Node.
43783 * @return {Node} content
43784 * @override
43785 **/
43786
43787
43788 ParenthesisNode.prototype.getContent = function () {
43789 return this.content.getContent();
43790 };
43791 /**
43792 * Execute a callback for each of the child nodes of this node
43793 * @param {function(child: Node, path: string, parent: Node)} callback
43794 */
43795
43796
43797 ParenthesisNode.prototype.forEach = function (callback) {
43798 callback(this.content, 'content', this);
43799 };
43800 /**
43801 * Create a new ParenthesisNode having it's childs be the results of calling
43802 * the provided callback function for each of the childs of the original node.
43803 * @param {function(child: Node, path: string, parent: Node) : Node} callback
43804 * @returns {ParenthesisNode} Returns a clone of the node
43805 */
43806
43807
43808 ParenthesisNode.prototype.map = function (callback) {
43809 var content = callback(this.content, 'content', this);
43810 return new ParenthesisNode(content);
43811 };
43812 /**
43813 * Create a clone of this node, a shallow copy
43814 * @return {ParenthesisNode}
43815 */
43816
43817
43818 ParenthesisNode.prototype.clone = function () {
43819 return new ParenthesisNode(this.content);
43820 };
43821 /**
43822 * Get string representation
43823 * @param {Object} options
43824 * @return {string} str
43825 * @override
43826 */
43827
43828
43829 ParenthesisNode.prototype._toString = function (options) {
43830 if (!options || options && !options.parenthesis || options && options.parenthesis === 'keep') {
43831 return '(' + this.content.toString(options) + ')';
43832 }
43833
43834 return this.content.toString(options);
43835 };
43836 /**
43837 * Get a JSON representation of the node
43838 * @returns {Object}
43839 */
43840
43841
43842 ParenthesisNode.prototype.toJSON = function () {
43843 return {
43844 mathjs: 'ParenthesisNode',
43845 content: this.content
43846 };
43847 };
43848 /**
43849 * Instantiate an ParenthesisNode from its JSON representation
43850 * @param {Object} json An object structured like
43851 * `{"mathjs": "ParenthesisNode", "content": ...}`,
43852 * where mathjs is optional
43853 * @returns {ParenthesisNode}
43854 */
43855
43856
43857 ParenthesisNode.fromJSON = function (json) {
43858 return new ParenthesisNode(json.content);
43859 };
43860 /**
43861 * Get HTML representation
43862 * @param {Object} options
43863 * @return {string} str
43864 * @override
43865 */
43866
43867
43868 ParenthesisNode.prototype.toHTML = function (options) {
43869 if (!options || options && !options.parenthesis || options && options.parenthesis === 'keep') {
43870 return '<span class="math-parenthesis math-round-parenthesis">(</span>' + this.content.toHTML(options) + '<span class="math-parenthesis math-round-parenthesis">)</span>';
43871 }
43872
43873 return this.content.toHTML(options);
43874 };
43875 /**
43876 * Get LaTeX representation
43877 * @param {Object} options
43878 * @return {string} str
43879 * @override
43880 */
43881
43882
43883 ParenthesisNode.prototype._toTex = function (options) {
43884 if (!options || options && !options.parenthesis || options && options.parenthesis === 'keep') {
43885 return "\\left(".concat(this.content.toTex(options), "\\right)");
43886 }
43887
43888 return this.content.toTex(options);
43889 };
43890
43891 return ParenthesisNode;
43892}, {
43893 isClass: true,
43894 isNode: true
43895});
43896// CONCATENATED MODULE: ./src/expression/node/RangeNode.js
43897
43898
43899
43900var RangeNode_name = 'RangeNode';
43901var RangeNode_dependencies = ['Node'];
43902var createRangeNode =
43903/* #__PURE__ */
43904Object(factory["a" /* factory */])(RangeNode_name, RangeNode_dependencies, function (_ref) {
43905 var Node = _ref.Node;
43906
43907 /**
43908 * @constructor RangeNode
43909 * @extends {Node}
43910 * create a range
43911 * @param {Node} start included lower-bound
43912 * @param {Node} end included upper-bound
43913 * @param {Node} [step] optional step
43914 */
43915 function RangeNode(start, end, step) {
43916 if (!(this instanceof RangeNode)) {
43917 throw new SyntaxError('Constructor must be called with the new operator');
43918 } // validate inputs
43919
43920
43921 if (!Object(is["w" /* isNode */])(start)) throw new TypeError('Node expected');
43922 if (!Object(is["w" /* isNode */])(end)) throw new TypeError('Node expected');
43923 if (step && !Object(is["w" /* isNode */])(step)) throw new TypeError('Node expected');
43924 if (arguments.length > 3) throw new Error('Too many arguments');
43925 this.start = start; // included lower-bound
43926
43927 this.end = end; // included upper-bound
43928
43929 this.step = step || null; // optional step
43930 }
43931
43932 RangeNode.prototype = new Node();
43933 RangeNode.prototype.type = 'RangeNode';
43934 RangeNode.prototype.isRangeNode = true;
43935 /**
43936 * Check whether the RangeNode needs the `end` symbol to be defined.
43937 * This end is the size of the Matrix in current dimension.
43938 * @return {boolean}
43939 */
43940
43941 RangeNode.prototype.needsEnd = function () {
43942 // find all `end` symbols in this RangeNode
43943 var endSymbols = this.filter(function (node) {
43944 return Object(is["J" /* isSymbolNode */])(node) && node.name === 'end';
43945 });
43946 return endSymbols.length > 0;
43947 };
43948 /**
43949 * Compile a node into a JavaScript function.
43950 * This basically pre-calculates as much as possible and only leaves open
43951 * calculations which depend on a dynamic scope with variables.
43952 * @param {Object} math Math.js namespace with functions and constants.
43953 * @param {Object} argNames An object with argument names as key and `true`
43954 * as value. Used in the SymbolNode to optimize
43955 * for arguments from user assigned functions
43956 * (see FunctionAssignmentNode) or special symbols
43957 * like `end` (see IndexNode).
43958 * @return {function} Returns a function which can be called like:
43959 * evalNode(scope: Object, args: Object, context: *)
43960 */
43961
43962
43963 RangeNode.prototype._compile = function (math, argNames) {
43964 var range = math.range;
43965
43966 var evalStart = this.start._compile(math, argNames);
43967
43968 var evalEnd = this.end._compile(math, argNames);
43969
43970 if (this.step) {
43971 var evalStep = this.step._compile(math, argNames);
43972
43973 return function evalRangeNode(scope, args, context) {
43974 return range(evalStart(scope, args, context), evalEnd(scope, args, context), evalStep(scope, args, context));
43975 };
43976 } else {
43977 return function evalRangeNode(scope, args, context) {
43978 return range(evalStart(scope, args, context), evalEnd(scope, args, context));
43979 };
43980 }
43981 };
43982 /**
43983 * Execute a callback for each of the child nodes of this node
43984 * @param {function(child: Node, path: string, parent: Node)} callback
43985 */
43986
43987
43988 RangeNode.prototype.forEach = function (callback) {
43989 callback(this.start, 'start', this);
43990 callback(this.end, 'end', this);
43991
43992 if (this.step) {
43993 callback(this.step, 'step', this);
43994 }
43995 };
43996 /**
43997 * Create a new RangeNode having it's childs be the results of calling
43998 * the provided callback function for each of the childs of the original node.
43999 * @param {function(child: Node, path: string, parent: Node): Node} callback
44000 * @returns {RangeNode} Returns a transformed copy of the node
44001 */
44002
44003
44004 RangeNode.prototype.map = function (callback) {
44005 return new RangeNode(this._ifNode(callback(this.start, 'start', this)), this._ifNode(callback(this.end, 'end', this)), this.step && this._ifNode(callback(this.step, 'step', this)));
44006 };
44007 /**
44008 * Create a clone of this node, a shallow copy
44009 * @return {RangeNode}
44010 */
44011
44012
44013 RangeNode.prototype.clone = function () {
44014 return new RangeNode(this.start, this.end, this.step && this.step);
44015 };
44016 /**
44017 * Calculate the necessary parentheses
44018 * @param {Node} node
44019 * @param {string} parenthesis
44020 * @return {Object} parentheses
44021 * @private
44022 */
44023
44024
44025 function calculateNecessaryParentheses(node, parenthesis) {
44026 var precedence = getPrecedence(node, parenthesis);
44027 var parens = {};
44028 var startPrecedence = getPrecedence(node.start, parenthesis);
44029 parens.start = startPrecedence !== null && startPrecedence <= precedence || parenthesis === 'all';
44030
44031 if (node.step) {
44032 var stepPrecedence = getPrecedence(node.step, parenthesis);
44033 parens.step = stepPrecedence !== null && stepPrecedence <= precedence || parenthesis === 'all';
44034 }
44035
44036 var endPrecedence = getPrecedence(node.end, parenthesis);
44037 parens.end = endPrecedence !== null && endPrecedence <= precedence || parenthesis === 'all';
44038 return parens;
44039 }
44040 /**
44041 * Get string representation
44042 * @param {Object} options
44043 * @return {string} str
44044 */
44045
44046
44047 RangeNode.prototype._toString = function (options) {
44048 var parenthesis = options && options.parenthesis ? options.parenthesis : 'keep';
44049 var parens = calculateNecessaryParentheses(this, parenthesis); // format string as start:step:stop
44050
44051 var str;
44052 var start = this.start.toString(options);
44053
44054 if (parens.start) {
44055 start = '(' + start + ')';
44056 }
44057
44058 str = start;
44059
44060 if (this.step) {
44061 var step = this.step.toString(options);
44062
44063 if (parens.step) {
44064 step = '(' + step + ')';
44065 }
44066
44067 str += ':' + step;
44068 }
44069
44070 var end = this.end.toString(options);
44071
44072 if (parens.end) {
44073 end = '(' + end + ')';
44074 }
44075
44076 str += ':' + end;
44077 return str;
44078 };
44079 /**
44080 * Get a JSON representation of the node
44081 * @returns {Object}
44082 */
44083
44084
44085 RangeNode.prototype.toJSON = function () {
44086 return {
44087 mathjs: 'RangeNode',
44088 start: this.start,
44089 end: this.end,
44090 step: this.step
44091 };
44092 };
44093 /**
44094 * Instantiate an RangeNode from its JSON representation
44095 * @param {Object} json An object structured like
44096 * `{"mathjs": "RangeNode", "start": ..., "end": ..., "step": ...}`,
44097 * where mathjs is optional
44098 * @returns {RangeNode}
44099 */
44100
44101
44102 RangeNode.fromJSON = function (json) {
44103 return new RangeNode(json.start, json.end, json.step);
44104 };
44105 /**
44106 * Get HTML representation
44107 * @param {Object} options
44108 * @return {string} str
44109 */
44110
44111
44112 RangeNode.prototype.toHTML = function (options) {
44113 var parenthesis = options && options.parenthesis ? options.parenthesis : 'keep';
44114 var parens = calculateNecessaryParentheses(this, parenthesis); // format string as start:step:stop
44115
44116 var str;
44117 var start = this.start.toHTML(options);
44118
44119 if (parens.start) {
44120 start = '<span class="math-parenthesis math-round-parenthesis">(</span>' + start + '<span class="math-parenthesis math-round-parenthesis">)</span>';
44121 }
44122
44123 str = start;
44124
44125 if (this.step) {
44126 var step = this.step.toHTML(options);
44127
44128 if (parens.step) {
44129 step = '<span class="math-parenthesis math-round-parenthesis">(</span>' + step + '<span class="math-parenthesis math-round-parenthesis">)</span>';
44130 }
44131
44132 str += '<span class="math-operator math-range-operator">:</span>' + step;
44133 }
44134
44135 var end = this.end.toHTML(options);
44136
44137 if (parens.end) {
44138 end = '<span class="math-parenthesis math-round-parenthesis">(</span>' + end + '<span class="math-parenthesis math-round-parenthesis">)</span>';
44139 }
44140
44141 str += '<span class="math-operator math-range-operator">:</span>' + end;
44142 return str;
44143 };
44144 /**
44145 * Get LaTeX representation
44146 * @params {Object} options
44147 * @return {string} str
44148 */
44149
44150
44151 RangeNode.prototype._toTex = function (options) {
44152 var parenthesis = options && options.parenthesis ? options.parenthesis : 'keep';
44153 var parens = calculateNecessaryParentheses(this, parenthesis);
44154 var str = this.start.toTex(options);
44155
44156 if (parens.start) {
44157 str = "\\left(".concat(str, "\\right)");
44158 }
44159
44160 if (this.step) {
44161 var step = this.step.toTex(options);
44162
44163 if (parens.step) {
44164 step = "\\left(".concat(step, "\\right)");
44165 }
44166
44167 str += ':' + step;
44168 }
44169
44170 var end = this.end.toTex(options);
44171
44172 if (parens.end) {
44173 end = "\\left(".concat(end, "\\right)");
44174 }
44175
44176 str += ':' + end;
44177 return str;
44178 };
44179
44180 return RangeNode;
44181}, {
44182 isClass: true,
44183 isNode: true
44184});
44185// CONCATENATED MODULE: ./src/expression/node/RelationalNode.js
44186
44187
44188
44189
44190
44191var RelationalNode_name = 'RelationalNode';
44192var RelationalNode_dependencies = ['Node'];
44193var createRelationalNode =
44194/* #__PURE__ */
44195Object(factory["a" /* factory */])(RelationalNode_name, RelationalNode_dependencies, function (_ref) {
44196 var Node = _ref.Node;
44197
44198 /**
44199 * A node representing a chained conditional expression, such as 'x > y > z'
44200 *
44201 * @param {String[]} conditionals An array of conditional operators used to compare the parameters
44202 * @param {Node[]} params The parameters that will be compared
44203 *
44204 * @constructor RelationalNode
44205 * @extends {Node}
44206 */
44207 function RelationalNode(conditionals, params) {
44208 if (!(this instanceof RelationalNode)) {
44209 throw new SyntaxError('Constructor must be called with the new operator');
44210 }
44211
44212 if (!Array.isArray(conditionals)) throw new TypeError('Parameter conditionals must be an array');
44213 if (!Array.isArray(params)) throw new TypeError('Parameter params must be an array');
44214 if (conditionals.length !== params.length - 1) throw new TypeError('Parameter params must contain exactly one more element than parameter conditionals');
44215 this.conditionals = conditionals;
44216 this.params = params;
44217 }
44218
44219 RelationalNode.prototype = new Node();
44220 RelationalNode.prototype.type = 'RelationalNode';
44221 RelationalNode.prototype.isRelationalNode = true;
44222 /**
44223 * Compile a node into a JavaScript function.
44224 * This basically pre-calculates as much as possible and only leaves open
44225 * calculations which depend on a dynamic scope with variables.
44226 * @param {Object} math Math.js namespace with functions and constants.
44227 * @param {Object} argNames An object with argument names as key and `true`
44228 * as value. Used in the SymbolNode to optimize
44229 * for arguments from user assigned functions
44230 * (see FunctionAssignmentNode) or special symbols
44231 * like `end` (see IndexNode).
44232 * @return {function} Returns a function which can be called like:
44233 * evalNode(scope: Object, args: Object, context: *)
44234 */
44235
44236 RelationalNode.prototype._compile = function (math, argNames) {
44237 var self = this;
44238 var compiled = this.params.map(function (p) {
44239 return p._compile(math, argNames);
44240 });
44241 return function evalRelationalNode(scope, args, context) {
44242 var evalLhs;
44243 var evalRhs = compiled[0](scope, args, context);
44244
44245 for (var i = 0; i < self.conditionals.length; i++) {
44246 evalLhs = evalRhs;
44247 evalRhs = compiled[i + 1](scope, args, context);
44248 var condFn = getSafeProperty(math, self.conditionals[i]);
44249
44250 if (!condFn(evalLhs, evalRhs)) {
44251 return false;
44252 }
44253 }
44254
44255 return true;
44256 };
44257 };
44258 /**
44259 * Execute a callback for each of the child nodes of this node
44260 * @param {function(child: Node, path: string, parent: Node)} callback
44261 */
44262
44263
44264 RelationalNode.prototype.forEach = function (callback) {
44265 var _this = this;
44266
44267 this.params.forEach(function (n, i) {
44268 return callback(n, 'params[' + i + ']', _this);
44269 }, this);
44270 };
44271 /**
44272 * Create a new RelationalNode having its childs be the results of calling
44273 * the provided callback function for each of the childs of the original node.
44274 * @param {function(child: Node, path: string, parent: Node): Node} callback
44275 * @returns {RelationalNode} Returns a transformed copy of the node
44276 */
44277
44278
44279 RelationalNode.prototype.map = function (callback) {
44280 var _this2 = this;
44281
44282 return new RelationalNode(this.conditionals.slice(), this.params.map(function (n, i) {
44283 return _this2._ifNode(callback(n, 'params[' + i + ']', _this2));
44284 }, this));
44285 };
44286 /**
44287 * Create a clone of this node, a shallow copy
44288 * @return {RelationalNode}
44289 */
44290
44291
44292 RelationalNode.prototype.clone = function () {
44293 return new RelationalNode(this.conditionals, this.params);
44294 };
44295 /**
44296 * Get string representation.
44297 * @param {Object} options
44298 * @return {string} str
44299 */
44300
44301
44302 RelationalNode.prototype._toString = function (options) {
44303 var parenthesis = options && options.parenthesis ? options.parenthesis : 'keep';
44304 var precedence = getPrecedence(this, parenthesis);
44305 var paramStrings = this.params.map(function (p, index) {
44306 var paramPrecedence = getPrecedence(p, parenthesis);
44307 return parenthesis === 'all' || paramPrecedence !== null && paramPrecedence <= precedence ? '(' + p.toString(options) + ')' : p.toString(options);
44308 });
44309 var operatorMap = {
44310 equal: '==',
44311 unequal: '!=',
44312 smaller: '<',
44313 larger: '>',
44314 smallerEq: '<=',
44315 largerEq: '>='
44316 };
44317 var ret = paramStrings[0];
44318
44319 for (var i = 0; i < this.conditionals.length; i++) {
44320 ret += ' ' + operatorMap[this.conditionals[i]] + ' ' + paramStrings[i + 1];
44321 }
44322
44323 return ret;
44324 };
44325 /**
44326 * Get a JSON representation of the node
44327 * @returns {Object}
44328 */
44329
44330
44331 RelationalNode.prototype.toJSON = function () {
44332 return {
44333 mathjs: 'RelationalNode',
44334 conditionals: this.conditionals,
44335 params: this.params
44336 };
44337 };
44338 /**
44339 * Instantiate a RelationalNode from its JSON representation
44340 * @param {Object} json An object structured like
44341 * `{"mathjs": "RelationalNode", "condition": ..., "trueExpr": ..., "falseExpr": ...}`,
44342 * where mathjs is optional
44343 * @returns {RelationalNode}
44344 */
44345
44346
44347 RelationalNode.fromJSON = function (json) {
44348 return new RelationalNode(json.conditionals, json.params);
44349 };
44350 /**
44351 * Get HTML representation
44352 * @param {Object} options
44353 * @return {string} str
44354 */
44355
44356
44357 RelationalNode.prototype.toHTML = function (options) {
44358 var parenthesis = options && options.parenthesis ? options.parenthesis : 'keep';
44359 var precedence = getPrecedence(this, parenthesis);
44360 var paramStrings = this.params.map(function (p, index) {
44361 var paramPrecedence = getPrecedence(p, parenthesis);
44362 return parenthesis === 'all' || paramPrecedence !== null && paramPrecedence <= precedence ? '<span class="math-parenthesis math-round-parenthesis">(</span>' + p.toHTML(options) + '<span class="math-parenthesis math-round-parenthesis">)</span>' : p.toHTML(options);
44363 });
44364 var operatorMap = {
44365 equal: '==',
44366 unequal: '!=',
44367 smaller: '<',
44368 larger: '>',
44369 smallerEq: '<=',
44370 largerEq: '>='
44371 };
44372 var ret = paramStrings[0];
44373
44374 for (var i = 0; i < this.conditionals.length; i++) {
44375 ret += '<span class="math-operator math-binary-operator math-explicit-binary-operator">' + Object(utils_string["c" /* escape */])(operatorMap[this.conditionals[i]]) + '</span>' + paramStrings[i + 1];
44376 }
44377
44378 return ret;
44379 };
44380 /**
44381 * Get LaTeX representation
44382 * @param {Object} options
44383 * @return {string} str
44384 */
44385
44386
44387 RelationalNode.prototype._toTex = function (options) {
44388 var parenthesis = options && options.parenthesis ? options.parenthesis : 'keep';
44389 var precedence = getPrecedence(this, parenthesis);
44390 var paramStrings = this.params.map(function (p, index) {
44391 var paramPrecedence = getPrecedence(p, parenthesis);
44392 return parenthesis === 'all' || paramPrecedence !== null && paramPrecedence <= precedence ? '\\left(' + p.toTex(options) + '\right)' : p.toTex(options);
44393 });
44394 var ret = paramStrings[0];
44395
44396 for (var i = 0; i < this.conditionals.length; i++) {
44397 ret += latexOperators[this.conditionals[i]] + paramStrings[i + 1];
44398 }
44399
44400 return ret;
44401 };
44402
44403 return RelationalNode;
44404}, {
44405 isClass: true,
44406 isNode: true
44407});
44408// CONCATENATED MODULE: ./src/expression/node/SymbolNode.js
44409
44410
44411
44412
44413var SymbolNode_name = 'SymbolNode';
44414var SymbolNode_dependencies = ['math', '?Unit', 'Node'];
44415var createSymbolNode =
44416/* #__PURE__ */
44417Object(factory["a" /* factory */])(SymbolNode_name, SymbolNode_dependencies, function (_ref) {
44418 var math = _ref.math,
44419 Unit = _ref.Unit,
44420 Node = _ref.Node;
44421
44422 /**
44423 * Check whether some name is a valueless unit like "inch".
44424 * @param {string} name
44425 * @return {boolean}
44426 */
44427 function isValuelessUnit(name) {
44428 return Unit ? Unit.isValuelessUnit(name) : false;
44429 }
44430 /**
44431 * @constructor SymbolNode
44432 * @extends {Node}
44433 * A symbol node can hold and resolve a symbol
44434 * @param {string} name
44435 * @extends {Node}
44436 */
44437
44438
44439 function SymbolNode(name) {
44440 if (!(this instanceof SymbolNode)) {
44441 throw new SyntaxError('Constructor must be called with the new operator');
44442 } // validate input
44443
44444
44445 if (typeof name !== 'string') throw new TypeError('String expected for parameter "name"');
44446 this.name = name;
44447 }
44448
44449 SymbolNode.prototype = new Node();
44450 SymbolNode.prototype.type = 'SymbolNode';
44451 SymbolNode.prototype.isSymbolNode = true;
44452 /**
44453 * Compile a node into a JavaScript function.
44454 * This basically pre-calculates as much as possible and only leaves open
44455 * calculations which depend on a dynamic scope with variables.
44456 * @param {Object} math Math.js namespace with functions and constants.
44457 * @param {Object} argNames An object with argument names as key and `true`
44458 * as value. Used in the SymbolNode to optimize
44459 * for arguments from user assigned functions
44460 * (see FunctionAssignmentNode) or special symbols
44461 * like `end` (see IndexNode).
44462 * @return {function} Returns a function which can be called like:
44463 * evalNode(scope: Object, args: Object, context: *)
44464 */
44465
44466 SymbolNode.prototype._compile = function (math, argNames) {
44467 var name = this.name;
44468
44469 if (argNames[name] === true) {
44470 // this is a FunctionAssignment argument
44471 // (like an x when inside the expression of a function assignment `f(x) = ...`)
44472 return function (scope, args, context) {
44473 return args[name];
44474 };
44475 } else if (name in math) {
44476 return function (scope, args, context) {
44477 return name in scope ? getSafeProperty(scope, name) : getSafeProperty(math, name);
44478 };
44479 } else {
44480 var isUnit = isValuelessUnit(name);
44481 return function (scope, args, context) {
44482 return name in scope ? getSafeProperty(scope, name) : isUnit ? new Unit(null, name) : undef(name);
44483 };
44484 }
44485 };
44486 /**
44487 * Execute a callback for each of the child nodes of this node
44488 * @param {function(child: Node, path: string, parent: Node)} callback
44489 */
44490
44491
44492 SymbolNode.prototype.forEach = function (callback) {} // nothing to do, we don't have childs
44493
44494 /**
44495 * Create a new SymbolNode having it's childs be the results of calling
44496 * the provided callback function for each of the childs of the original node.
44497 * @param {function(child: Node, path: string, parent: Node) : Node} callback
44498 * @returns {SymbolNode} Returns a clone of the node
44499 */
44500 ;
44501
44502 SymbolNode.prototype.map = function (callback) {
44503 return this.clone();
44504 };
44505 /**
44506 * Throws an error 'Undefined symbol {name}'
44507 * @param {string} name
44508 */
44509
44510
44511 function undef(name) {
44512 throw new Error('Undefined symbol ' + name);
44513 }
44514 /**
44515 * Create a clone of this node, a shallow copy
44516 * @return {SymbolNode}
44517 */
44518
44519
44520 SymbolNode.prototype.clone = function () {
44521 return new SymbolNode(this.name);
44522 };
44523 /**
44524 * Get string representation
44525 * @param {Object} options
44526 * @return {string} str
44527 * @override
44528 */
44529
44530
44531 SymbolNode.prototype._toString = function (options) {
44532 return this.name;
44533 };
44534 /**
44535 * Get HTML representation
44536 * @param {Object} options
44537 * @return {string} str
44538 * @override
44539 */
44540
44541
44542 SymbolNode.prototype.toHTML = function (options) {
44543 var name = Object(utils_string["c" /* escape */])(this.name);
44544
44545 if (name === 'true' || name === 'false') {
44546 return '<span class="math-symbol math-boolean">' + name + '</span>';
44547 } else if (name === 'i') {
44548 return '<span class="math-symbol math-imaginary-symbol">' + name + '</span>';
44549 } else if (name === 'Infinity') {
44550 return '<span class="math-symbol math-infinity-symbol">' + name + '</span>';
44551 } else if (name === 'NaN') {
44552 return '<span class="math-symbol math-nan-symbol">' + name + '</span>';
44553 } else if (name === 'null') {
44554 return '<span class="math-symbol math-null-symbol">' + name + '</span>';
44555 } else if (name === 'undefined') {
44556 return '<span class="math-symbol math-undefined-symbol">' + name + '</span>';
44557 }
44558
44559 return '<span class="math-symbol">' + name + '</span>';
44560 };
44561 /**
44562 * Get a JSON representation of the node
44563 * @returns {Object}
44564 */
44565
44566
44567 SymbolNode.prototype.toJSON = function () {
44568 return {
44569 mathjs: 'SymbolNode',
44570 name: this.name
44571 };
44572 };
44573 /**
44574 * Instantiate a SymbolNode from its JSON representation
44575 * @param {Object} json An object structured like
44576 * `{"mathjs": "SymbolNode", name: "x"}`,
44577 * where mathjs is optional
44578 * @returns {SymbolNode}
44579 */
44580
44581
44582 SymbolNode.fromJSON = function (json) {
44583 return new SymbolNode(json.name);
44584 };
44585 /**
44586 * Get LaTeX representation
44587 * @param {Object} options
44588 * @return {string} str
44589 * @override
44590 */
44591
44592
44593 SymbolNode.prototype._toTex = function (options) {
44594 var isUnit = false;
44595
44596 if (typeof math[this.name] === 'undefined' && isValuelessUnit(this.name)) {
44597 isUnit = true;
44598 }
44599
44600 var symbol = toSymbol(this.name, isUnit);
44601
44602 if (symbol[0] === '\\') {
44603 // no space needed if the symbol starts with '\'
44604 return symbol;
44605 } // the space prevents symbols from breaking stuff like '\cdot' if it's written right before the symbol
44606
44607
44608 return ' ' + symbol;
44609 };
44610
44611 return SymbolNode;
44612}, {
44613 isClass: true,
44614 isNode: true
44615});
44616// CONCATENATED MODULE: ./src/expression/node/FunctionNode.js
44617function FunctionNode_typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { FunctionNode_typeof = function _typeof(obj) { return typeof obj; }; } else { FunctionNode_typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return FunctionNode_typeof(obj); }
44618
44619function FunctionNode_extends() { FunctionNode_extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return FunctionNode_extends.apply(this, arguments); }
44620
44621
44622
44623
44624
44625
44626
44627
44628var FunctionNode_name = 'FunctionNode';
44629var FunctionNode_dependencies = ['math', 'Node', 'SymbolNode'];
44630var createFunctionNode =
44631/* #__PURE__ */
44632Object(factory["a" /* factory */])(FunctionNode_name, FunctionNode_dependencies, function (_ref) {
44633 var math = _ref.math,
44634 Node = _ref.Node,
44635 SymbolNode = _ref.SymbolNode;
44636
44637 /**
44638 * @constructor FunctionNode
44639 * @extends {./Node}
44640 * invoke a list with arguments on a node
44641 * @param {./Node | string} fn Node resolving with a function on which to invoke
44642 * the arguments, typically a SymboNode or AccessorNode
44643 * @param {./Node[]} args
44644 */
44645 function FunctionNode(fn, args) {
44646 if (!(this instanceof FunctionNode)) {
44647 throw new SyntaxError('Constructor must be called with the new operator');
44648 }
44649
44650 if (typeof fn === 'string') {
44651 fn = new SymbolNode(fn);
44652 } // validate input
44653
44654
44655 if (!Object(is["w" /* isNode */])(fn)) throw new TypeError('Node expected as parameter "fn"');
44656
44657 if (!Array.isArray(args) || !args.every(is["w" /* isNode */])) {
44658 throw new TypeError('Array containing Nodes expected for parameter "args"');
44659 }
44660
44661 this.fn = fn;
44662 this.args = args || []; // readonly property name
44663
44664 Object.defineProperty(this, 'name', {
44665 get: function () {
44666 return this.fn.name || '';
44667 }.bind(this),
44668 set: function set() {
44669 throw new Error('Cannot assign a new name, name is read-only');
44670 }
44671 }); // TODO: deprecated since v3, remove some day
44672
44673 var deprecated = function deprecated() {
44674 throw new Error('Property `FunctionNode.object` is deprecated, use `FunctionNode.fn` instead');
44675 };
44676
44677 Object.defineProperty(this, 'object', {
44678 get: deprecated,
44679 set: deprecated
44680 });
44681 }
44682
44683 FunctionNode.prototype = new Node();
44684 FunctionNode.prototype.type = 'FunctionNode';
44685 FunctionNode.prototype.isFunctionNode = true;
44686 /**
44687 * Compile a node into a JavaScript function.
44688 * This basically pre-calculates as much as possible and only leaves open
44689 * calculations which depend on a dynamic scope with variables.
44690 * @param {Object} math Math.js namespace with functions and constants.
44691 * @param {Object} argNames An object with argument names as key and `true`
44692 * as value. Used in the SymbolNode to optimize
44693 * for arguments from user assigned functions
44694 * (see FunctionAssignmentNode) or special symbols
44695 * like `end` (see IndexNode).
44696 * @return {function} Returns a function which can be called like:
44697 * evalNode(scope: Object, args: Object, context: *)
44698 */
44699
44700 FunctionNode.prototype._compile = function (math, argNames) {
44701 if (!(this instanceof FunctionNode)) {
44702 throw new TypeError('No valid FunctionNode');
44703 } // compile arguments
44704
44705
44706 var evalArgs = Object(utils_array["m" /* map */])(this.args, function (arg) {
44707 return arg._compile(math, argNames);
44708 });
44709
44710 if (Object(is["J" /* isSymbolNode */])(this.fn)) {
44711 // we can statically determine whether the function has an rawArgs property
44712 var _name = this.fn.name;
44713 var fn = _name in math ? getSafeProperty(math, _name) : undefined;
44714 var isRaw = typeof fn === 'function' && fn.rawArgs === true;
44715
44716 if (isRaw) {
44717 // pass unevaluated parameters (nodes) to the function
44718 // "raw" evaluation
44719 var rawArgs = this.args;
44720 return function evalFunctionNode(scope, args, context) {
44721 return (_name in scope ? getSafeProperty(scope, _name) : fn)(rawArgs, math, FunctionNode_extends({}, scope, args));
44722 };
44723 } else {
44724 // "regular" evaluation
44725 if (evalArgs.length === 1) {
44726 var evalArg0 = evalArgs[0];
44727 return function evalFunctionNode(scope, args, context) {
44728 return (_name in scope ? getSafeProperty(scope, _name) : fn)(evalArg0(scope, args, context));
44729 };
44730 } else if (evalArgs.length === 2) {
44731 var _evalArg = evalArgs[0];
44732 var evalArg1 = evalArgs[1];
44733 return function evalFunctionNode(scope, args, context) {
44734 return (_name in scope ? getSafeProperty(scope, _name) : fn)(_evalArg(scope, args, context), evalArg1(scope, args, context));
44735 };
44736 } else {
44737 return function evalFunctionNode(scope, args, context) {
44738 return (_name in scope ? getSafeProperty(scope, _name) : fn).apply(null, Object(utils_array["m" /* map */])(evalArgs, function (evalArg) {
44739 return evalArg(scope, args, context);
44740 }));
44741 };
44742 }
44743 }
44744 } else if (Object(is["a" /* isAccessorNode */])(this.fn) && Object(is["u" /* isIndexNode */])(this.fn.index) && this.fn.index.isObjectProperty()) {
44745 // execute the function with the right context: the object of the AccessorNode
44746 var evalObject = this.fn.object._compile(math, argNames);
44747
44748 var prop = this.fn.index.getObjectProperty();
44749 var _rawArgs = this.args;
44750 return function evalFunctionNode(scope, args, context) {
44751 var object = evalObject(scope, args, context);
44752 validateSafeMethod(object, prop);
44753 var isRaw = object[prop] && object[prop].rawArgs;
44754 return isRaw ? object[prop](_rawArgs, math, FunctionNode_extends({}, scope, args)) // "raw" evaluation
44755 : object[prop].apply(object, Object(utils_array["m" /* map */])(evalArgs, function (evalArg) {
44756 // "regular" evaluation
44757 return evalArg(scope, args, context);
44758 }));
44759 };
44760 } else {
44761 // node.fn.isAccessorNode && !node.fn.index.isObjectProperty()
44762 // we have to dynamically determine whether the function has a rawArgs property
44763 var evalFn = this.fn._compile(math, argNames);
44764
44765 var _rawArgs2 = this.args;
44766 return function evalFunctionNode(scope, args, context) {
44767 var fn = evalFn(scope, args, context);
44768 var isRaw = fn && fn.rawArgs;
44769 return isRaw ? fn(_rawArgs2, math, FunctionNode_extends({}, scope, args)) // "raw" evaluation
44770 : fn.apply(fn, Object(utils_array["m" /* map */])(evalArgs, function (evalArg) {
44771 // "regular" evaluation
44772 return evalArg(scope, args, context);
44773 }));
44774 };
44775 }
44776 };
44777 /**
44778 * Execute a callback for each of the child nodes of this node
44779 * @param {function(child: Node, path: string, parent: Node)} callback
44780 */
44781
44782
44783 FunctionNode.prototype.forEach = function (callback) {
44784 callback(this.fn, 'fn', this);
44785
44786 for (var i = 0; i < this.args.length; i++) {
44787 callback(this.args[i], 'args[' + i + ']', this);
44788 }
44789 };
44790 /**
44791 * Create a new FunctionNode having it's childs be the results of calling
44792 * the provided callback function for each of the childs of the original node.
44793 * @param {function(child: Node, path: string, parent: Node): Node} callback
44794 * @returns {FunctionNode} Returns a transformed copy of the node
44795 */
44796
44797
44798 FunctionNode.prototype.map = function (callback) {
44799 var fn = this._ifNode(callback(this.fn, 'fn', this));
44800
44801 var args = [];
44802
44803 for (var i = 0; i < this.args.length; i++) {
44804 args[i] = this._ifNode(callback(this.args[i], 'args[' + i + ']', this));
44805 }
44806
44807 return new FunctionNode(fn, args);
44808 };
44809 /**
44810 * Create a clone of this node, a shallow copy
44811 * @return {FunctionNode}
44812 */
44813
44814
44815 FunctionNode.prototype.clone = function () {
44816 return new FunctionNode(this.fn, this.args.slice(0));
44817 }; // backup Node's toString function
44818 // @private
44819
44820
44821 var nodeToString = FunctionNode.prototype.toString;
44822 /**
44823 * Get string representation. (wrapper function)
44824 * This overrides parts of Node's toString function.
44825 * If callback is an object containing callbacks, it
44826 * calls the correct callback for the current node,
44827 * otherwise it falls back to calling Node's toString
44828 * function.
44829 *
44830 * @param {Object} options
44831 * @return {string} str
44832 * @override
44833 */
44834
44835 FunctionNode.prototype.toString = function (options) {
44836 var customString;
44837 var name = this.fn.toString(options);
44838
44839 if (options && FunctionNode_typeof(options.handler) === 'object' && Object(utils_object["f" /* hasOwnProperty */])(options.handler, name)) {
44840 // callback is a map of callback functions
44841 customString = options.handler[name](this, options);
44842 }
44843
44844 if (typeof customString !== 'undefined') {
44845 return customString;
44846 } // fall back to Node's toString
44847
44848
44849 return nodeToString.call(this, options);
44850 };
44851 /**
44852 * Get string representation
44853 * @param {Object} options
44854 * @return {string} str
44855 */
44856
44857
44858 FunctionNode.prototype._toString = function (options) {
44859 var args = this.args.map(function (arg) {
44860 return arg.toString(options);
44861 });
44862 var fn = Object(is["q" /* isFunctionAssignmentNode */])(this.fn) ? '(' + this.fn.toString(options) + ')' : this.fn.toString(options); // format the arguments like "add(2, 4.2)"
44863
44864 return fn + '(' + args.join(', ') + ')';
44865 };
44866 /**
44867 * Get a JSON representation of the node
44868 * @returns {Object}
44869 */
44870
44871
44872 FunctionNode.prototype.toJSON = function () {
44873 return {
44874 mathjs: 'FunctionNode',
44875 fn: this.fn,
44876 args: this.args
44877 };
44878 };
44879 /**
44880 * Instantiate an AssignmentNode from its JSON representation
44881 * @param {Object} json An object structured like
44882 * `{"mathjs": "FunctionNode", fn: ..., args: ...}`,
44883 * where mathjs is optional
44884 * @returns {FunctionNode}
44885 */
44886
44887
44888 FunctionNode.fromJSON = function (json) {
44889 return new FunctionNode(json.fn, json.args);
44890 };
44891 /**
44892 * Get HTML representation
44893 * @param {Object} options
44894 * @return {string} str
44895 */
44896
44897
44898 FunctionNode.prototype.toHTML = function (options) {
44899 var args = this.args.map(function (arg) {
44900 return arg.toHTML(options);
44901 }); // format the arguments like "add(2, 4.2)"
44902
44903 return '<span class="math-function">' + Object(utils_string["c" /* escape */])(this.fn) + '</span><span class="math-paranthesis math-round-parenthesis">(</span>' + args.join('<span class="math-separator">,</span>') + '<span class="math-paranthesis math-round-parenthesis">)</span>';
44904 };
44905 /*
44906 * Expand a LaTeX template
44907 *
44908 * @param {string} template
44909 * @param {Node} node
44910 * @param {Object} options
44911 * @private
44912 **/
44913
44914
44915 function expandTemplate(template, node, options) {
44916 var latex = ''; // Match everything of the form ${identifier} or ${identifier[2]} or $$
44917 // while submatching identifier and 2 (in the second case)
44918
44919 var regex = new RegExp('\\$(?:\\{([a-z_][a-z_0-9]*)(?:\\[([0-9]+)\\])?\\}|\\$)', 'ig');
44920 var inputPos = 0; // position in the input string
44921
44922 var match;
44923
44924 while ((match = regex.exec(template)) !== null) {
44925 // go through all matches
44926 // add everything in front of the match to the LaTeX string
44927 latex += template.substring(inputPos, match.index);
44928 inputPos = match.index;
44929
44930 if (match[0] === '$$') {
44931 // escaped dollar sign
44932 latex += '$';
44933 inputPos++;
44934 } else {
44935 // template parameter
44936 inputPos += match[0].length;
44937 var property = node[match[1]];
44938
44939 if (!property) {
44940 throw new ReferenceError('Template: Property ' + match[1] + ' does not exist.');
44941 }
44942
44943 if (match[2] === undefined) {
44944 // no square brackets
44945 switch (FunctionNode_typeof(property)) {
44946 case 'string':
44947 latex += property;
44948 break;
44949
44950 case 'object':
44951 if (Object(is["w" /* isNode */])(property)) {
44952 latex += property.toTex(options);
44953 } else if (Array.isArray(property)) {
44954 // make array of Nodes into comma separated list
44955 latex += property.map(function (arg, index) {
44956 if (Object(is["w" /* isNode */])(arg)) {
44957 return arg.toTex(options);
44958 }
44959
44960 throw new TypeError('Template: ' + match[1] + '[' + index + '] is not a Node.');
44961 }).join(',');
44962 } else {
44963 throw new TypeError('Template: ' + match[1] + ' has to be a Node, String or array of Nodes');
44964 }
44965
44966 break;
44967
44968 default:
44969 throw new TypeError('Template: ' + match[1] + ' has to be a Node, String or array of Nodes');
44970 }
44971 } else {
44972 // with square brackets
44973 if (Object(is["w" /* isNode */])(property[match[2]] && property[match[2]])) {
44974 latex += property[match[2]].toTex(options);
44975 } else {
44976 throw new TypeError('Template: ' + match[1] + '[' + match[2] + '] is not a Node.');
44977 }
44978 }
44979 }
44980 }
44981
44982 latex += template.slice(inputPos); // append rest of the template
44983
44984 return latex;
44985 } // backup Node's toTex function
44986 // @private
44987
44988
44989 var nodeToTex = FunctionNode.prototype.toTex;
44990 /**
44991 * Get LaTeX representation. (wrapper function)
44992 * This overrides parts of Node's toTex function.
44993 * If callback is an object containing callbacks, it
44994 * calls the correct callback for the current node,
44995 * otherwise it falls back to calling Node's toTex
44996 * function.
44997 *
44998 * @param {Object} options
44999 * @return {string}
45000 */
45001
45002 FunctionNode.prototype.toTex = function (options) {
45003 var customTex;
45004
45005 if (options && FunctionNode_typeof(options.handler) === 'object' && Object(utils_object["f" /* hasOwnProperty */])(options.handler, this.name)) {
45006 // callback is a map of callback functions
45007 customTex = options.handler[this.name](this, options);
45008 }
45009
45010 if (typeof customTex !== 'undefined') {
45011 return customTex;
45012 } // fall back to Node's toTex
45013
45014
45015 return nodeToTex.call(this, options);
45016 };
45017 /**
45018 * Get LaTeX representation
45019 * @param {Object} options
45020 * @return {string} str
45021 */
45022
45023
45024 FunctionNode.prototype._toTex = function (options) {
45025 var args = this.args.map(function (arg) {
45026 // get LaTeX of the arguments
45027 return arg.toTex(options);
45028 });
45029 var latexConverter;
45030
45031 if (latexFunctions[this.name]) {
45032 latexConverter = latexFunctions[this.name];
45033 } // toTex property on the function itself
45034
45035
45036 if (math[this.name] && (typeof math[this.name].toTex === 'function' || FunctionNode_typeof(math[this.name].toTex) === 'object' || typeof math[this.name].toTex === 'string')) {
45037 // .toTex is a callback function
45038 latexConverter = math[this.name].toTex;
45039 }
45040
45041 var customToTex;
45042
45043 switch (FunctionNode_typeof(latexConverter)) {
45044 case 'function':
45045 // a callback function
45046 customToTex = latexConverter(this, options);
45047 break;
45048
45049 case 'string':
45050 // a template string
45051 customToTex = expandTemplate(latexConverter, this, options);
45052 break;
45053
45054 case 'object':
45055 // an object with different "converters" for different numbers of arguments
45056 switch (FunctionNode_typeof(latexConverter[args.length])) {
45057 case 'function':
45058 customToTex = latexConverter[args.length](this, options);
45059 break;
45060
45061 case 'string':
45062 customToTex = expandTemplate(latexConverter[args.length], this, options);
45063 break;
45064 }
45065
45066 }
45067
45068 if (typeof customToTex !== 'undefined') {
45069 return customToTex;
45070 }
45071
45072 return expandTemplate(defaultTemplate, this, options);
45073 };
45074 /**
45075 * Get identifier.
45076 * @return {string}
45077 */
45078
45079
45080 FunctionNode.prototype.getIdentifier = function () {
45081 return this.type + ':' + this.name;
45082 };
45083
45084 return FunctionNode;
45085}, {
45086 isClass: true,
45087 isNode: true
45088});
45089// CONCATENATED MODULE: ./src/expression/parse.js
45090function parse_extends() { parse_extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return parse_extends.apply(this, arguments); }
45091
45092
45093
45094
45095
45096var parse_name = 'parse';
45097var parse_dependencies = ['typed', 'numeric', 'config', 'AccessorNode', 'ArrayNode', 'AssignmentNode', 'BlockNode', 'ConditionalNode', 'ConstantNode', 'FunctionAssignmentNode', 'FunctionNode', 'IndexNode', 'ObjectNode', 'OperatorNode', 'ParenthesisNode', 'RangeNode', 'RelationalNode', 'SymbolNode'];
45098var createParse =
45099/* #__PURE__ */
45100Object(factory["a" /* factory */])(parse_name, parse_dependencies, function (_ref) {
45101 var typed = _ref.typed,
45102 numeric = _ref.numeric,
45103 config = _ref.config,
45104 AccessorNode = _ref.AccessorNode,
45105 ArrayNode = _ref.ArrayNode,
45106 AssignmentNode = _ref.AssignmentNode,
45107 BlockNode = _ref.BlockNode,
45108 ConditionalNode = _ref.ConditionalNode,
45109 ConstantNode = _ref.ConstantNode,
45110 FunctionAssignmentNode = _ref.FunctionAssignmentNode,
45111 FunctionNode = _ref.FunctionNode,
45112 IndexNode = _ref.IndexNode,
45113 ObjectNode = _ref.ObjectNode,
45114 OperatorNode = _ref.OperatorNode,
45115 ParenthesisNode = _ref.ParenthesisNode,
45116 RangeNode = _ref.RangeNode,
45117 RelationalNode = _ref.RelationalNode,
45118 SymbolNode = _ref.SymbolNode;
45119
45120 /**
45121 * Parse an expression. Returns a node tree, which can be evaluated by
45122 * invoking node.evaluate().
45123 *
45124 * Note the evaluating arbitrary expressions may involve security risks,
45125 * see [https://mathjs.org/docs/expressions/security.html](https://mathjs.org/docs/expressions/security.html) for more information.
45126 *
45127 * Syntax:
45128 *
45129 * math.parse(expr)
45130 * math.parse(expr, options)
45131 * math.parse([expr1, expr2, expr3, ...])
45132 * math.parse([expr1, expr2, expr3, ...], options)
45133 *
45134 * Example:
45135 *
45136 * const node1 = math.parse('sqrt(3^2 + 4^2)')
45137 * node1.compile().evaluate() // 5
45138 *
45139 * let scope = {a:3, b:4}
45140 * const node2 = math.parse('a * b') // 12
45141 * const code2 = node2.compile()
45142 * code2.evaluate(scope) // 12
45143 * scope.a = 5
45144 * code2.evaluate(scope) // 20
45145 *
45146 * const nodes = math.parse(['a = 3', 'b = 4', 'a * b'])
45147 * nodes[2].compile().evaluate() // 12
45148 *
45149 * See also:
45150 *
45151 * evaluate, compile
45152 *
45153 * @param {string | string[] | Matrix} expr Expression to be parsed
45154 * @param {{nodes: Object<string, Node>}} [options] Available options:
45155 * - `nodes` a set of custom nodes
45156 * @return {Node | Node[]} node
45157 * @throws {Error}
45158 */
45159 var parse = typed(parse_name, {
45160 string: function string(expression) {
45161 return parseStart(expression, {});
45162 },
45163 'Array | Matrix': function ArrayMatrix(expressions) {
45164 return parseMultiple(expressions, {});
45165 },
45166 'string, Object': function stringObject(expression, options) {
45167 var extraNodes = options.nodes !== undefined ? options.nodes : {};
45168 return parseStart(expression, extraNodes);
45169 },
45170 'Array | Matrix, Object': parseMultiple
45171 });
45172
45173 function parseMultiple(expressions) {
45174 var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
45175 var extraNodes = options.nodes !== undefined ? options.nodes : {}; // parse an array or matrix with expressions
45176
45177 return deepMap(expressions, function (elem) {
45178 if (typeof elem !== 'string') throw new TypeError('String expected');
45179 return parseStart(elem, extraNodes);
45180 });
45181 } // token types enumeration
45182
45183
45184 var TOKENTYPE = {
45185 NULL: 0,
45186 DELIMITER: 1,
45187 NUMBER: 2,
45188 SYMBOL: 3,
45189 UNKNOWN: 4
45190 }; // map with all delimiters
45191
45192 var DELIMITERS = {
45193 ',': true,
45194 '(': true,
45195 ')': true,
45196 '[': true,
45197 ']': true,
45198 '{': true,
45199 '}': true,
45200 '"': true,
45201 '\'': true,
45202 ';': true,
45203 '+': true,
45204 '-': true,
45205 '*': true,
45206 '.*': true,
45207 '/': true,
45208 './': true,
45209 '%': true,
45210 '^': true,
45211 '.^': true,
45212 '~': true,
45213 '!': true,
45214 '&': true,
45215 '|': true,
45216 '^|': true,
45217 '=': true,
45218 ':': true,
45219 '?': true,
45220 '==': true,
45221 '!=': true,
45222 '<': true,
45223 '>': true,
45224 '<=': true,
45225 '>=': true,
45226 '<<': true,
45227 '>>': true,
45228 '>>>': true
45229 }; // map with all named delimiters
45230
45231 var NAMED_DELIMITERS = {
45232 mod: true,
45233 to: true,
45234 "in": true,
45235 and: true,
45236 xor: true,
45237 or: true,
45238 not: true
45239 };
45240 var CONSTANTS = {
45241 "true": true,
45242 "false": false,
45243 "null": null,
45244 undefined: undefined
45245 };
45246 var NUMERIC_CONSTANTS = ['NaN', 'Infinity'];
45247
45248 function initialState() {
45249 return {
45250 extraNodes: {},
45251 // current extra nodes, must be careful not to mutate
45252 expression: '',
45253 // current expression
45254 comment: '',
45255 // last parsed comment
45256 index: 0,
45257 // current index in expr
45258 token: '',
45259 // current token
45260 tokenType: TOKENTYPE.NULL,
45261 // type of the token
45262 nestingLevel: 0,
45263 // level of nesting inside parameters, used to ignore newline characters
45264 conditionalLevel: null // when a conditional is being parsed, the level of the conditional is stored here
45265
45266 };
45267 }
45268 /**
45269 * View upto `length` characters of the expression starting at the current character.
45270 *
45271 * @param {Object} state
45272 * @param {number} [length=1] Number of characters to view
45273 * @returns {string}
45274 * @private
45275 */
45276
45277
45278 function currentString(state, length) {
45279 return state.expression.substr(state.index, length);
45280 }
45281 /**
45282 * View the current character. Returns '' if end of expression is reached.
45283 *
45284 * @param {Object} state
45285 * @returns {string}
45286 * @private
45287 */
45288
45289
45290 function currentCharacter(state) {
45291 return currentString(state, 1);
45292 }
45293 /**
45294 * Get the next character from the expression.
45295 * The character is stored into the char c. If the end of the expression is
45296 * reached, the function puts an empty string in c.
45297 * @private
45298 */
45299
45300
45301 function next(state) {
45302 state.index++;
45303 }
45304 /**
45305 * Preview the previous character from the expression.
45306 * @return {string} cNext
45307 * @private
45308 */
45309
45310
45311 function prevCharacter(state) {
45312 return state.expression.charAt(state.index - 1);
45313 }
45314 /**
45315 * Preview the next character from the expression.
45316 * @return {string} cNext
45317 * @private
45318 */
45319
45320
45321 function nextCharacter(state) {
45322 return state.expression.charAt(state.index + 1);
45323 }
45324 /**
45325 * Get next token in the current string expr.
45326 * The token and token type are available as token and tokenType
45327 * @private
45328 */
45329
45330
45331 function getToken(state) {
45332 state.tokenType = TOKENTYPE.NULL;
45333 state.token = '';
45334 state.comment = ''; // skip over whitespaces
45335 // space, tab, and newline when inside parameters
45336
45337 while (parse.isWhitespace(currentCharacter(state), state.nestingLevel)) {
45338 next(state);
45339 } // skip comment
45340
45341
45342 if (currentCharacter(state) === '#') {
45343 while (currentCharacter(state) !== '\n' && currentCharacter(state) !== '') {
45344 state.comment += currentCharacter(state);
45345 next(state);
45346 }
45347 } // check for end of expression
45348
45349
45350 if (currentCharacter(state) === '') {
45351 // token is still empty
45352 state.tokenType = TOKENTYPE.DELIMITER;
45353 return;
45354 } // check for new line character
45355
45356
45357 if (currentCharacter(state) === '\n' && !state.nestingLevel) {
45358 state.tokenType = TOKENTYPE.DELIMITER;
45359 state.token = currentCharacter(state);
45360 next(state);
45361 return;
45362 }
45363
45364 var c1 = currentCharacter(state);
45365 var c2 = currentString(state, 2);
45366 var c3 = currentString(state, 3);
45367
45368 if (c3.length === 3 && DELIMITERS[c3]) {
45369 state.tokenType = TOKENTYPE.DELIMITER;
45370 state.token = c3;
45371 next(state);
45372 next(state);
45373 next(state);
45374 return;
45375 } // check for delimiters consisting of 2 characters
45376
45377
45378 if (c2.length === 2 && DELIMITERS[c2]) {
45379 state.tokenType = TOKENTYPE.DELIMITER;
45380 state.token = c2;
45381 next(state);
45382 next(state);
45383 return;
45384 } // check for delimiters consisting of 1 character
45385
45386
45387 if (DELIMITERS[c1]) {
45388 state.tokenType = TOKENTYPE.DELIMITER;
45389 state.token = c1;
45390 next(state);
45391 return;
45392 } // check for a number
45393
45394
45395 if (parse.isDigitDot(c1)) {
45396 state.tokenType = TOKENTYPE.NUMBER; // get number, can have a single dot
45397
45398 if (currentCharacter(state) === '.') {
45399 state.token += currentCharacter(state);
45400 next(state);
45401
45402 if (!parse.isDigit(currentCharacter(state))) {
45403 // this is no number, it is just a dot (can be dot notation)
45404 state.tokenType = TOKENTYPE.DELIMITER;
45405 }
45406 } else {
45407 while (parse.isDigit(currentCharacter(state))) {
45408 state.token += currentCharacter(state);
45409 next(state);
45410 }
45411
45412 if (parse.isDecimalMark(currentCharacter(state), nextCharacter(state))) {
45413 state.token += currentCharacter(state);
45414 next(state);
45415 }
45416 }
45417
45418 while (parse.isDigit(currentCharacter(state))) {
45419 state.token += currentCharacter(state);
45420 next(state);
45421 } // check for exponential notation like "2.3e-4", "1.23e50" or "2e+4"
45422
45423
45424 if (currentCharacter(state) === 'E' || currentCharacter(state) === 'e') {
45425 if (parse.isDigit(nextCharacter(state)) || nextCharacter(state) === '-' || nextCharacter(state) === '+') {
45426 state.token += currentCharacter(state);
45427 next(state);
45428
45429 if (currentCharacter(state) === '+' || currentCharacter(state) === '-') {
45430 state.token += currentCharacter(state);
45431 next(state);
45432 } // Scientific notation MUST be followed by an exponent
45433
45434
45435 if (!parse.isDigit(currentCharacter(state))) {
45436 throw createSyntaxError(state, 'Digit expected, got "' + currentCharacter(state) + '"');
45437 }
45438
45439 while (parse.isDigit(currentCharacter(state))) {
45440 state.token += currentCharacter(state);
45441 next(state);
45442 }
45443
45444 if (parse.isDecimalMark(currentCharacter(state), nextCharacter(state))) {
45445 throw createSyntaxError(state, 'Digit expected, got "' + currentCharacter(state) + '"');
45446 }
45447 } else if (nextCharacter(state) === '.') {
45448 next(state);
45449 throw createSyntaxError(state, 'Digit expected, got "' + currentCharacter(state) + '"');
45450 }
45451 }
45452
45453 return;
45454 } // check for variables, functions, named operators
45455
45456
45457 if (parse.isAlpha(currentCharacter(state), prevCharacter(state), nextCharacter(state))) {
45458 while (parse.isAlpha(currentCharacter(state), prevCharacter(state), nextCharacter(state)) || parse.isDigit(currentCharacter(state))) {
45459 state.token += currentCharacter(state);
45460 next(state);
45461 }
45462
45463 if (Object(utils_object["f" /* hasOwnProperty */])(NAMED_DELIMITERS, state.token)) {
45464 state.tokenType = TOKENTYPE.DELIMITER;
45465 } else {
45466 state.tokenType = TOKENTYPE.SYMBOL;
45467 }
45468
45469 return;
45470 } // something unknown is found, wrong characters -> a syntax error
45471
45472
45473 state.tokenType = TOKENTYPE.UNKNOWN;
45474
45475 while (currentCharacter(state) !== '') {
45476 state.token += currentCharacter(state);
45477 next(state);
45478 }
45479
45480 throw createSyntaxError(state, 'Syntax error in part "' + state.token + '"');
45481 }
45482 /**
45483 * Get next token and skip newline tokens
45484 */
45485
45486
45487 function getTokenSkipNewline(state) {
45488 do {
45489 getToken(state);
45490 } while (state.token === '\n'); // eslint-disable-line no-unmodified-loop-condition
45491
45492 }
45493 /**
45494 * Open parameters.
45495 * New line characters will be ignored until closeParams(state) is called
45496 */
45497
45498
45499 function openParams(state) {
45500 state.nestingLevel++;
45501 }
45502 /**
45503 * Close parameters.
45504 * New line characters will no longer be ignored
45505 */
45506
45507
45508 function closeParams(state) {
45509 state.nestingLevel--;
45510 }
45511 /**
45512 * Checks whether the current character `c` is a valid alpha character:
45513 *
45514 * - A latin letter (upper or lower case) Ascii: a-z, A-Z
45515 * - An underscore Ascii: _
45516 * - A dollar sign Ascii: $
45517 * - A latin letter with accents Unicode: \u00C0 - \u02AF
45518 * - A greek letter Unicode: \u0370 - \u03FF
45519 * - A mathematical alphanumeric symbol Unicode: \u{1D400} - \u{1D7FF} excluding invalid code points
45520 *
45521 * The previous and next characters are needed to determine whether
45522 * this character is part of a unicode surrogate pair.
45523 *
45524 * @param {string} c Current character in the expression
45525 * @param {string} cPrev Previous character
45526 * @param {string} cNext Next character
45527 * @return {boolean}
45528 */
45529
45530
45531 parse.isAlpha = function isAlpha(c, cPrev, cNext) {
45532 return parse.isValidLatinOrGreek(c) || parse.isValidMathSymbol(c, cNext) || parse.isValidMathSymbol(cPrev, c);
45533 };
45534 /**
45535 * Test whether a character is a valid latin, greek, or letter-like character
45536 * @param {string} c
45537 * @return {boolean}
45538 */
45539
45540
45541 parse.isValidLatinOrGreek = function isValidLatinOrGreek(c) {
45542 return /^[a-zA-Z_$\u00C0-\u02AF\u0370-\u03FF\u2100-\u214F]$/.test(c);
45543 };
45544 /**
45545 * Test whether two given 16 bit characters form a surrogate pair of a
45546 * unicode math symbol.
45547 *
45548 * https://unicode-table.com/en/
45549 * https://www.wikiwand.com/en/Mathematical_operators_and_symbols_in_Unicode
45550 *
45551 * Note: In ES6 will be unicode aware:
45552 * https://stackoverflow.com/questions/280712/javascript-unicode-regexes
45553 * https://mathiasbynens.be/notes/es6-unicode-regex
45554 *
45555 * @param {string} high
45556 * @param {string} low
45557 * @return {boolean}
45558 */
45559
45560
45561 parse.isValidMathSymbol = function isValidMathSymbol(high, low) {
45562 return /^[\uD835]$/.test(high) && /^[\uDC00-\uDFFF]$/.test(low) && /^[^\uDC55\uDC9D\uDCA0\uDCA1\uDCA3\uDCA4\uDCA7\uDCA8\uDCAD\uDCBA\uDCBC\uDCC4\uDD06\uDD0B\uDD0C\uDD15\uDD1D\uDD3A\uDD3F\uDD45\uDD47-\uDD49\uDD51\uDEA6\uDEA7\uDFCC\uDFCD]$/.test(low);
45563 };
45564 /**
45565 * Check whether given character c is a white space character: space, tab, or enter
45566 * @param {string} c
45567 * @param {number} nestingLevel
45568 * @return {boolean}
45569 */
45570
45571
45572 parse.isWhitespace = function isWhitespace(c, nestingLevel) {
45573 // TODO: also take '\r' carriage return as newline? Or does that give problems on mac?
45574 return c === ' ' || c === '\t' || c === '\n' && nestingLevel > 0;
45575 };
45576 /**
45577 * Test whether the character c is a decimal mark (dot).
45578 * This is the case when it's not the start of a delimiter '.*', './', or '.^'
45579 * @param {string} c
45580 * @param {string} cNext
45581 * @return {boolean}
45582 */
45583
45584
45585 parse.isDecimalMark = function isDecimalMark(c, cNext) {
45586 return c === '.' && cNext !== '/' && cNext !== '*' && cNext !== '^';
45587 };
45588 /**
45589 * checks if the given char c is a digit or dot
45590 * @param {string} c a string with one character
45591 * @return {boolean}
45592 */
45593
45594
45595 parse.isDigitDot = function isDigitDot(c) {
45596 return c >= '0' && c <= '9' || c === '.';
45597 };
45598 /**
45599 * checks if the given char c is a digit
45600 * @param {string} c a string with one character
45601 * @return {boolean}
45602 */
45603
45604
45605 parse.isDigit = function isDigit(c) {
45606 return c >= '0' && c <= '9';
45607 };
45608 /**
45609 * Start of the parse levels below, in order of precedence
45610 * @return {Node} node
45611 * @private
45612 */
45613
45614
45615 function parseStart(expression, extraNodes) {
45616 var state = initialState();
45617
45618 parse_extends(state, {
45619 expression: expression,
45620 extraNodes: extraNodes
45621 });
45622
45623 getToken(state);
45624 var node = parseBlock(state); // check for garbage at the end of the expression
45625 // an expression ends with a empty character '' and tokenType DELIMITER
45626
45627 if (state.token !== '') {
45628 if (state.tokenType === TOKENTYPE.DELIMITER) {
45629 // user entered a not existing operator like "//"
45630 // TODO: give hints for aliases, for example with "<>" give as hint " did you mean !== ?"
45631 throw createError(state, 'Unexpected operator ' + state.token);
45632 } else {
45633 throw createSyntaxError(state, 'Unexpected part "' + state.token + '"');
45634 }
45635 }
45636
45637 return node;
45638 }
45639 /**
45640 * Parse a block with expressions. Expressions can be separated by a newline
45641 * character '\n', or by a semicolon ';'. In case of a semicolon, no output
45642 * of the preceding line is returned.
45643 * @return {Node} node
45644 * @private
45645 */
45646
45647
45648 function parseBlock(state) {
45649 var node;
45650 var blocks = [];
45651 var visible;
45652
45653 if (state.token !== '' && state.token !== '\n' && state.token !== ';') {
45654 node = parseAssignment(state);
45655 node.comment = state.comment;
45656 } // TODO: simplify this loop
45657
45658
45659 while (state.token === '\n' || state.token === ';') {
45660 // eslint-disable-line no-unmodified-loop-condition
45661 if (blocks.length === 0 && node) {
45662 visible = state.token !== ';';
45663 blocks.push({
45664 node: node,
45665 visible: visible
45666 });
45667 }
45668
45669 getToken(state);
45670
45671 if (state.token !== '\n' && state.token !== ';' && state.token !== '') {
45672 node = parseAssignment(state);
45673 node.comment = state.comment;
45674 visible = state.token !== ';';
45675 blocks.push({
45676 node: node,
45677 visible: visible
45678 });
45679 }
45680 }
45681
45682 if (blocks.length > 0) {
45683 return new BlockNode(blocks);
45684 } else {
45685 if (!node) {
45686 node = new ConstantNode(undefined);
45687 node.comment = state.comment;
45688 }
45689
45690 return node;
45691 }
45692 }
45693 /**
45694 * Assignment of a function or variable,
45695 * - can be a variable like 'a=2.3'
45696 * - or a updating an existing variable like 'matrix(2,3:5)=[6,7,8]'
45697 * - defining a function like 'f(x) = x^2'
45698 * @return {Node} node
45699 * @private
45700 */
45701
45702
45703 function parseAssignment(state) {
45704 var name, args, value, valid;
45705 var node = parseConditional(state);
45706
45707 if (state.token === '=') {
45708 if (Object(is["J" /* isSymbolNode */])(node)) {
45709 // parse a variable assignment like 'a = 2/3'
45710 name = node.name;
45711 getTokenSkipNewline(state);
45712 value = parseAssignment(state);
45713 return new AssignmentNode(new SymbolNode(name), value);
45714 } else if (Object(is["a" /* isAccessorNode */])(node)) {
45715 // parse a matrix subset assignment like 'A[1,2] = 4'
45716 getTokenSkipNewline(state);
45717 value = parseAssignment(state);
45718 return new AssignmentNode(node.object, node.index, value);
45719 } else if (Object(is["r" /* isFunctionNode */])(node) && Object(is["J" /* isSymbolNode */])(node.fn)) {
45720 // parse function assignment like 'f(x) = x^2'
45721 valid = true;
45722 args = [];
45723 name = node.name;
45724 node.args.forEach(function (arg, index) {
45725 if (Object(is["J" /* isSymbolNode */])(arg)) {
45726 args[index] = arg.name;
45727 } else {
45728 valid = false;
45729 }
45730 });
45731
45732 if (valid) {
45733 getTokenSkipNewline(state);
45734 value = parseAssignment(state);
45735 return new FunctionAssignmentNode(name, args, value);
45736 }
45737 }
45738
45739 throw createSyntaxError(state, 'Invalid left hand side of assignment operator =');
45740 }
45741
45742 return node;
45743 }
45744 /**
45745 * conditional operation
45746 *
45747 * condition ? truePart : falsePart
45748 *
45749 * Note: conditional operator is right-associative
45750 *
45751 * @return {Node} node
45752 * @private
45753 */
45754
45755
45756 function parseConditional(state) {
45757 var node = parseLogicalOr(state);
45758
45759 while (state.token === '?') {
45760 // eslint-disable-line no-unmodified-loop-condition
45761 // set a conditional level, the range operator will be ignored as long
45762 // as conditionalLevel === state.nestingLevel.
45763 var prev = state.conditionalLevel;
45764 state.conditionalLevel = state.nestingLevel;
45765 getTokenSkipNewline(state);
45766 var condition = node;
45767 var trueExpr = parseAssignment(state);
45768 if (state.token !== ':') throw createSyntaxError(state, 'False part of conditional expression expected');
45769 state.conditionalLevel = null;
45770 getTokenSkipNewline(state);
45771 var falseExpr = parseAssignment(state); // Note: check for conditional operator again, right associativity
45772
45773 node = new ConditionalNode(condition, trueExpr, falseExpr); // restore the previous conditional level
45774
45775 state.conditionalLevel = prev;
45776 }
45777
45778 return node;
45779 }
45780 /**
45781 * logical or, 'x or y'
45782 * @return {Node} node
45783 * @private
45784 */
45785
45786
45787 function parseLogicalOr(state) {
45788 var node = parseLogicalXor(state);
45789
45790 while (state.token === 'or') {
45791 // eslint-disable-line no-unmodified-loop-condition
45792 getTokenSkipNewline(state);
45793 node = new OperatorNode('or', 'or', [node, parseLogicalXor(state)]);
45794 }
45795
45796 return node;
45797 }
45798 /**
45799 * logical exclusive or, 'x xor y'
45800 * @return {Node} node
45801 * @private
45802 */
45803
45804
45805 function parseLogicalXor(state) {
45806 var node = parseLogicalAnd(state);
45807
45808 while (state.token === 'xor') {
45809 // eslint-disable-line no-unmodified-loop-condition
45810 getTokenSkipNewline(state);
45811 node = new OperatorNode('xor', 'xor', [node, parseLogicalAnd(state)]);
45812 }
45813
45814 return node;
45815 }
45816 /**
45817 * logical and, 'x and y'
45818 * @return {Node} node
45819 * @private
45820 */
45821
45822
45823 function parseLogicalAnd(state) {
45824 var node = parseBitwiseOr(state);
45825
45826 while (state.token === 'and') {
45827 // eslint-disable-line no-unmodified-loop-condition
45828 getTokenSkipNewline(state);
45829 node = new OperatorNode('and', 'and', [node, parseBitwiseOr(state)]);
45830 }
45831
45832 return node;
45833 }
45834 /**
45835 * bitwise or, 'x | y'
45836 * @return {Node} node
45837 * @private
45838 */
45839
45840
45841 function parseBitwiseOr(state) {
45842 var node = parseBitwiseXor(state);
45843
45844 while (state.token === '|') {
45845 // eslint-disable-line no-unmodified-loop-condition
45846 getTokenSkipNewline(state);
45847 node = new OperatorNode('|', 'bitOr', [node, parseBitwiseXor(state)]);
45848 }
45849
45850 return node;
45851 }
45852 /**
45853 * bitwise exclusive or (xor), 'x ^| y'
45854 * @return {Node} node
45855 * @private
45856 */
45857
45858
45859 function parseBitwiseXor(state) {
45860 var node = parseBitwiseAnd(state);
45861
45862 while (state.token === '^|') {
45863 // eslint-disable-line no-unmodified-loop-condition
45864 getTokenSkipNewline(state);
45865 node = new OperatorNode('^|', 'bitXor', [node, parseBitwiseAnd(state)]);
45866 }
45867
45868 return node;
45869 }
45870 /**
45871 * bitwise and, 'x & y'
45872 * @return {Node} node
45873 * @private
45874 */
45875
45876
45877 function parseBitwiseAnd(state) {
45878 var node = parseRelational(state);
45879
45880 while (state.token === '&') {
45881 // eslint-disable-line no-unmodified-loop-condition
45882 getTokenSkipNewline(state);
45883 node = new OperatorNode('&', 'bitAnd', [node, parseRelational(state)]);
45884 }
45885
45886 return node;
45887 }
45888 /**
45889 * Parse a chained conditional, like 'a > b >= c'
45890 * @return {Node} node
45891 */
45892
45893
45894 function parseRelational(state) {
45895 var params = [parseShift(state)];
45896 var conditionals = [];
45897 var operators = {
45898 '==': 'equal',
45899 '!=': 'unequal',
45900 '<': 'smaller',
45901 '>': 'larger',
45902 '<=': 'smallerEq',
45903 '>=': 'largerEq'
45904 };
45905
45906 while (Object(utils_object["f" /* hasOwnProperty */])(operators, state.token)) {
45907 // eslint-disable-line no-unmodified-loop-condition
45908 var cond = {
45909 name: state.token,
45910 fn: operators[state.token]
45911 };
45912 conditionals.push(cond);
45913 getTokenSkipNewline(state);
45914 params.push(parseShift(state));
45915 }
45916
45917 if (params.length === 1) {
45918 return params[0];
45919 } else if (params.length === 2) {
45920 return new OperatorNode(conditionals[0].name, conditionals[0].fn, params);
45921 } else {
45922 return new RelationalNode(conditionals.map(function (c) {
45923 return c.fn;
45924 }), params);
45925 }
45926 }
45927 /**
45928 * Bitwise left shift, bitwise right arithmetic shift, bitwise right logical shift
45929 * @return {Node} node
45930 * @private
45931 */
45932
45933
45934 function parseShift(state) {
45935 var node, name, fn, params;
45936 node = parseConversion(state);
45937 var operators = {
45938 '<<': 'leftShift',
45939 '>>': 'rightArithShift',
45940 '>>>': 'rightLogShift'
45941 };
45942
45943 while (Object(utils_object["f" /* hasOwnProperty */])(operators, state.token)) {
45944 name = state.token;
45945 fn = operators[name];
45946 getTokenSkipNewline(state);
45947 params = [node, parseConversion(state)];
45948 node = new OperatorNode(name, fn, params);
45949 }
45950
45951 return node;
45952 }
45953 /**
45954 * conversion operators 'to' and 'in'
45955 * @return {Node} node
45956 * @private
45957 */
45958
45959
45960 function parseConversion(state) {
45961 var node, name, fn, params;
45962 node = parseRange(state);
45963 var operators = {
45964 to: 'to',
45965 "in": 'to' // alias of 'to'
45966
45967 };
45968
45969 while (Object(utils_object["f" /* hasOwnProperty */])(operators, state.token)) {
45970 name = state.token;
45971 fn = operators[name];
45972 getTokenSkipNewline(state);
45973
45974 if (name === 'in' && state.token === '') {
45975 // end of expression -> this is the unit 'in' ('inch')
45976 node = new OperatorNode('*', 'multiply', [node, new SymbolNode('in')], true);
45977 } else {
45978 // operator 'a to b' or 'a in b'
45979 params = [node, parseRange(state)];
45980 node = new OperatorNode(name, fn, params);
45981 }
45982 }
45983
45984 return node;
45985 }
45986 /**
45987 * parse range, "start:end", "start:step:end", ":", "start:", ":end", etc
45988 * @return {Node} node
45989 * @private
45990 */
45991
45992
45993 function parseRange(state) {
45994 var node;
45995 var params = [];
45996
45997 if (state.token === ':') {
45998 // implicit start=1 (one-based)
45999 node = new ConstantNode(1);
46000 } else {
46001 // explicit start
46002 node = parseAddSubtract(state);
46003 }
46004
46005 if (state.token === ':' && state.conditionalLevel !== state.nestingLevel) {
46006 // we ignore the range operator when a conditional operator is being processed on the same level
46007 params.push(node); // parse step and end
46008
46009 while (state.token === ':' && params.length < 3) {
46010 // eslint-disable-line no-unmodified-loop-condition
46011 getTokenSkipNewline(state);
46012
46013 if (state.token === ')' || state.token === ']' || state.token === ',' || state.token === '') {
46014 // implicit end
46015 params.push(new SymbolNode('end'));
46016 } else {
46017 // explicit end
46018 params.push(parseAddSubtract(state));
46019 }
46020 }
46021
46022 if (params.length === 3) {
46023 // params = [start, step, end]
46024 node = new RangeNode(params[0], params[2], params[1]); // start, end, step
46025 } else {
46026 // length === 2
46027 // params = [start, end]
46028 node = new RangeNode(params[0], params[1]); // start, end
46029 }
46030 }
46031
46032 return node;
46033 }
46034 /**
46035 * add or subtract
46036 * @return {Node} node
46037 * @private
46038 */
46039
46040
46041 function parseAddSubtract(state) {
46042 var node, name, fn, params;
46043 node = parseMultiplyDivide(state);
46044 var operators = {
46045 '+': 'add',
46046 '-': 'subtract'
46047 };
46048
46049 while (Object(utils_object["f" /* hasOwnProperty */])(operators, state.token)) {
46050 name = state.token;
46051 fn = operators[name];
46052 getTokenSkipNewline(state);
46053 params = [node, parseMultiplyDivide(state)];
46054 node = new OperatorNode(name, fn, params);
46055 }
46056
46057 return node;
46058 }
46059 /**
46060 * multiply, divide, modulus
46061 * @return {Node} node
46062 * @private
46063 */
46064
46065
46066 function parseMultiplyDivide(state) {
46067 var node, last, name, fn;
46068 node = parseImplicitMultiplication(state);
46069 last = node;
46070 var operators = {
46071 '*': 'multiply',
46072 '.*': 'dotMultiply',
46073 '/': 'divide',
46074 './': 'dotDivide',
46075 '%': 'mod',
46076 mod: 'mod'
46077 };
46078
46079 while (true) {
46080 if (Object(utils_object["f" /* hasOwnProperty */])(operators, state.token)) {
46081 // explicit operators
46082 name = state.token;
46083 fn = operators[name];
46084 getTokenSkipNewline(state);
46085 last = parseImplicitMultiplication(state);
46086 node = new OperatorNode(name, fn, [node, last]);
46087 } else {
46088 break;
46089 }
46090 }
46091
46092 return node;
46093 }
46094 /**
46095 * implicit multiplication
46096 * @return {Node} node
46097 * @private
46098 */
46099
46100
46101 function parseImplicitMultiplication(state) {
46102 var node, last;
46103 node = parseRule2(state);
46104 last = node;
46105
46106 while (true) {
46107 if (state.tokenType === TOKENTYPE.SYMBOL || state.token === 'in' && Object(is["l" /* isConstantNode */])(node) || state.tokenType === TOKENTYPE.NUMBER && !Object(is["l" /* isConstantNode */])(last) && (!Object(is["B" /* isOperatorNode */])(last) || last.op === '!') || state.token === '(') {
46108 // parse implicit multiplication
46109 //
46110 // symbol: implicit multiplication like '2a', '(2+3)a', 'a b'
46111 // number: implicit multiplication like '(2+3)2'
46112 // parenthesis: implicit multiplication like '2(3+4)', '(3+4)(1+2)'
46113 last = parseRule2(state);
46114 node = new OperatorNode('*', 'multiply', [node, last], true
46115 /* implicit */
46116 );
46117 } else {
46118 break;
46119 }
46120 }
46121
46122 return node;
46123 }
46124 /**
46125 * Infamous "rule 2" as described in https://github.com/josdejong/mathjs/issues/792#issuecomment-361065370
46126 * Explicit division gets higher precedence than implicit multiplication
46127 * when the division matches this pattern: [number] / [number] [symbol]
46128 * @return {Node} node
46129 * @private
46130 */
46131
46132
46133 function parseRule2(state) {
46134 var node = parseUnary(state);
46135 var last = node;
46136 var tokenStates = [];
46137
46138 while (true) {
46139 // Match the "number /" part of the pattern "number / number symbol"
46140 if (state.token === '/' && Object(is["l" /* isConstantNode */])(last)) {
46141 // Look ahead to see if the next token is a number
46142 tokenStates.push(parse_extends({}, state));
46143 getTokenSkipNewline(state); // Match the "number / number" part of the pattern
46144
46145 if (state.tokenType === TOKENTYPE.NUMBER) {
46146 // Look ahead again
46147 tokenStates.push(parse_extends({}, state));
46148 getTokenSkipNewline(state); // Match the "symbol" part of the pattern, or a left parenthesis
46149
46150 if (state.tokenType === TOKENTYPE.SYMBOL || state.token === '(') {
46151 // We've matched the pattern "number / number symbol".
46152 // Rewind once and build the "number / number" node; the symbol will be consumed later
46153 parse_extends(state, tokenStates.pop());
46154
46155 tokenStates.pop();
46156 last = parseUnary(state);
46157 node = new OperatorNode('/', 'divide', [node, last]);
46158 } else {
46159 // Not a match, so rewind
46160 tokenStates.pop();
46161
46162 parse_extends(state, tokenStates.pop());
46163
46164 break;
46165 }
46166 } else {
46167 // Not a match, so rewind
46168 parse_extends(state, tokenStates.pop());
46169
46170 break;
46171 }
46172 } else {
46173 break;
46174 }
46175 }
46176
46177 return node;
46178 }
46179 /**
46180 * Unary plus and minus, and logical and bitwise not
46181 * @return {Node} node
46182 * @private
46183 */
46184
46185
46186 function parseUnary(state) {
46187 var name, params, fn;
46188 var operators = {
46189 '-': 'unaryMinus',
46190 '+': 'unaryPlus',
46191 '~': 'bitNot',
46192 not: 'not'
46193 };
46194
46195 if (Object(utils_object["f" /* hasOwnProperty */])(operators, state.token)) {
46196 fn = operators[state.token];
46197 name = state.token;
46198 getTokenSkipNewline(state);
46199 params = [parseUnary(state)];
46200 return new OperatorNode(name, fn, params);
46201 }
46202
46203 return parsePow(state);
46204 }
46205 /**
46206 * power
46207 * Note: power operator is right associative
46208 * @return {Node} node
46209 * @private
46210 */
46211
46212
46213 function parsePow(state) {
46214 var node, name, fn, params;
46215 node = parseLeftHandOperators(state);
46216
46217 if (state.token === '^' || state.token === '.^') {
46218 name = state.token;
46219 fn = name === '^' ? 'pow' : 'dotPow';
46220 getTokenSkipNewline(state);
46221 params = [node, parseUnary(state)]; // Go back to unary, we can have '2^-3'
46222
46223 node = new OperatorNode(name, fn, params);
46224 }
46225
46226 return node;
46227 }
46228 /**
46229 * Left hand operators: factorial x!, ctranspose x'
46230 * @return {Node} node
46231 * @private
46232 */
46233
46234
46235 function parseLeftHandOperators(state) {
46236 var node, name, fn, params;
46237 node = parseCustomNodes(state);
46238 var operators = {
46239 '!': 'factorial',
46240 '\'': 'ctranspose'
46241 };
46242
46243 while (Object(utils_object["f" /* hasOwnProperty */])(operators, state.token)) {
46244 name = state.token;
46245 fn = operators[name];
46246 getToken(state);
46247 params = [node];
46248 node = new OperatorNode(name, fn, params);
46249 node = parseAccessors(state, node);
46250 }
46251
46252 return node;
46253 }
46254 /**
46255 * Parse a custom node handler. A node handler can be used to process
46256 * nodes in a custom way, for example for handling a plot.
46257 *
46258 * A handler must be passed as second argument of the parse function.
46259 * - must extend math.expression.node.Node
46260 * - must contain a function _compile(defs: Object) : string
46261 * - must contain a function find(filter: Object) : Node[]
46262 * - must contain a function toString() : string
46263 * - the constructor is called with a single argument containing all parameters
46264 *
46265 * For example:
46266 *
46267 * nodes = {
46268 * 'plot': PlotHandler
46269 * }
46270 *
46271 * The constructor of the handler is called as:
46272 *
46273 * node = new PlotHandler(params)
46274 *
46275 * The handler will be invoked when evaluating an expression like:
46276 *
46277 * node = math.parse('plot(sin(x), x)', nodes)
46278 *
46279 * @return {Node} node
46280 * @private
46281 */
46282
46283
46284 function parseCustomNodes(state) {
46285 var params = [];
46286
46287 if (state.tokenType === TOKENTYPE.SYMBOL && Object(utils_object["f" /* hasOwnProperty */])(state.extraNodes, state.token)) {
46288 var CustomNode = state.extraNodes[state.token];
46289 getToken(state); // parse parameters
46290
46291 if (state.token === '(') {
46292 params = [];
46293 openParams(state);
46294 getToken(state);
46295
46296 if (state.token !== ')') {
46297 params.push(parseAssignment(state)); // parse a list with parameters
46298
46299 while (state.token === ',') {
46300 // eslint-disable-line no-unmodified-loop-condition
46301 getToken(state);
46302 params.push(parseAssignment(state));
46303 }
46304 }
46305
46306 if (state.token !== ')') {
46307 throw createSyntaxError(state, 'Parenthesis ) expected');
46308 }
46309
46310 closeParams(state);
46311 getToken(state);
46312 } // create a new custom node
46313 // noinspection JSValidateTypes
46314
46315
46316 return new CustomNode(params);
46317 }
46318
46319 return parseSymbol(state);
46320 }
46321 /**
46322 * parse symbols: functions, variables, constants, units
46323 * @return {Node} node
46324 * @private
46325 */
46326
46327
46328 function parseSymbol(state) {
46329 var node, name;
46330
46331 if (state.tokenType === TOKENTYPE.SYMBOL || state.tokenType === TOKENTYPE.DELIMITER && state.token in NAMED_DELIMITERS) {
46332 name = state.token;
46333 getToken(state);
46334
46335 if (Object(utils_object["f" /* hasOwnProperty */])(CONSTANTS, name)) {
46336 // true, false, null, ...
46337 node = new ConstantNode(CONSTANTS[name]);
46338 } else if (NUMERIC_CONSTANTS.indexOf(name) !== -1) {
46339 // NaN, Infinity
46340 node = new ConstantNode(numeric(name, 'number'));
46341 } else {
46342 node = new SymbolNode(name);
46343 } // parse function parameters and matrix index
46344
46345
46346 node = parseAccessors(state, node);
46347 return node;
46348 }
46349
46350 return parseDoubleQuotesString(state);
46351 }
46352 /**
46353 * parse accessors:
46354 * - function invocation in round brackets (...), for example sqrt(2)
46355 * - index enclosed in square brackets [...], for example A[2,3]
46356 * - dot notation for properties, like foo.bar
46357 * @param {Object} state
46358 * @param {Node} node Node on which to apply the parameters. If there
46359 * are no parameters in the expression, the node
46360 * itself is returned
46361 * @param {string[]} [types] Filter the types of notations
46362 * can be ['(', '[', '.']
46363 * @return {Node} node
46364 * @private
46365 */
46366
46367
46368 function parseAccessors(state, node, types) {
46369 var params;
46370
46371 while ((state.token === '(' || state.token === '[' || state.token === '.') && (!types || types.indexOf(state.token) !== -1)) {
46372 // eslint-disable-line no-unmodified-loop-condition
46373 params = [];
46374
46375 if (state.token === '(') {
46376 if (Object(is["J" /* isSymbolNode */])(node) || Object(is["a" /* isAccessorNode */])(node)) {
46377 // function invocation like fn(2, 3) or obj.fn(2, 3)
46378 openParams(state);
46379 getToken(state);
46380
46381 if (state.token !== ')') {
46382 params.push(parseAssignment(state)); // parse a list with parameters
46383
46384 while (state.token === ',') {
46385 // eslint-disable-line no-unmodified-loop-condition
46386 getToken(state);
46387 params.push(parseAssignment(state));
46388 }
46389 }
46390
46391 if (state.token !== ')') {
46392 throw createSyntaxError(state, 'Parenthesis ) expected');
46393 }
46394
46395 closeParams(state);
46396 getToken(state);
46397 node = new FunctionNode(node, params);
46398 } else {
46399 // implicit multiplication like (2+3)(4+5) or sqrt(2)(1+2)
46400 // don't parse it here but let it be handled by parseImplicitMultiplication
46401 // with correct precedence
46402 return node;
46403 }
46404 } else if (state.token === '[') {
46405 // index notation like variable[2, 3]
46406 openParams(state);
46407 getToken(state);
46408
46409 if (state.token !== ']') {
46410 params.push(parseAssignment(state)); // parse a list with parameters
46411
46412 while (state.token === ',') {
46413 // eslint-disable-line no-unmodified-loop-condition
46414 getToken(state);
46415 params.push(parseAssignment(state));
46416 }
46417 }
46418
46419 if (state.token !== ']') {
46420 throw createSyntaxError(state, 'Parenthesis ] expected');
46421 }
46422
46423 closeParams(state);
46424 getToken(state);
46425 node = new AccessorNode(node, new IndexNode(params));
46426 } else {
46427 // dot notation like variable.prop
46428 getToken(state);
46429
46430 if (state.tokenType !== TOKENTYPE.SYMBOL) {
46431 throw createSyntaxError(state, 'Property name expected after dot');
46432 }
46433
46434 params.push(new ConstantNode(state.token));
46435 getToken(state);
46436 var dotNotation = true;
46437 node = new AccessorNode(node, new IndexNode(params, dotNotation));
46438 }
46439 }
46440
46441 return node;
46442 }
46443 /**
46444 * Parse a double quotes string.
46445 * @return {Node} node
46446 * @private
46447 */
46448
46449
46450 function parseDoubleQuotesString(state) {
46451 var node, str;
46452
46453 if (state.token === '"') {
46454 str = parseDoubleQuotesStringToken(state); // create constant
46455
46456 node = new ConstantNode(str); // parse index parameters
46457
46458 node = parseAccessors(state, node);
46459 return node;
46460 }
46461
46462 return parseSingleQuotesString(state);
46463 }
46464 /**
46465 * Parse a string surrounded by double quotes "..."
46466 * @return {string}
46467 */
46468
46469
46470 function parseDoubleQuotesStringToken(state) {
46471 var str = '';
46472
46473 while (currentCharacter(state) !== '' && currentCharacter(state) !== '"') {
46474 if (currentCharacter(state) === '\\') {
46475 // escape character, immediately process the next
46476 // character to prevent stopping at a next '\"'
46477 str += currentCharacter(state);
46478 next(state);
46479 }
46480
46481 str += currentCharacter(state);
46482 next(state);
46483 }
46484
46485 getToken(state);
46486
46487 if (state.token !== '"') {
46488 throw createSyntaxError(state, 'End of string " expected');
46489 }
46490
46491 getToken(state);
46492 return JSON.parse('"' + str + '"'); // unescape escaped characters
46493 }
46494 /**
46495 * Parse a single quotes string.
46496 * @return {Node} node
46497 * @private
46498 */
46499
46500
46501 function parseSingleQuotesString(state) {
46502 var node, str;
46503
46504 if (state.token === '\'') {
46505 str = parseSingleQuotesStringToken(state); // create constant
46506
46507 node = new ConstantNode(str); // parse index parameters
46508
46509 node = parseAccessors(state, node);
46510 return node;
46511 }
46512
46513 return parseMatrix(state);
46514 }
46515 /**
46516 * Parse a string surrounded by single quotes '...'
46517 * @return {string}
46518 */
46519
46520
46521 function parseSingleQuotesStringToken(state) {
46522 var str = '';
46523
46524 while (currentCharacter(state) !== '' && currentCharacter(state) !== '\'') {
46525 if (currentCharacter(state) === '\\') {
46526 // escape character, immediately process the next
46527 // character to prevent stopping at a next '\''
46528 str += currentCharacter(state);
46529 next(state);
46530 }
46531
46532 str += currentCharacter(state);
46533 next(state);
46534 }
46535
46536 getToken(state);
46537
46538 if (state.token !== '\'') {
46539 throw createSyntaxError(state, 'End of string \' expected');
46540 }
46541
46542 getToken(state);
46543 return JSON.parse('"' + str + '"'); // unescape escaped characters
46544 }
46545 /**
46546 * parse the matrix
46547 * @return {Node} node
46548 * @private
46549 */
46550
46551
46552 function parseMatrix(state) {
46553 var array, params, rows, cols;
46554
46555 if (state.token === '[') {
46556 // matrix [...]
46557 openParams(state);
46558 getToken(state);
46559
46560 if (state.token !== ']') {
46561 // this is a non-empty matrix
46562 var row = parseRow(state);
46563
46564 if (state.token === ';') {
46565 // 2 dimensional array
46566 rows = 1;
46567 params = [row]; // the rows of the matrix are separated by dot-comma's
46568
46569 while (state.token === ';') {
46570 // eslint-disable-line no-unmodified-loop-condition
46571 getToken(state);
46572 params[rows] = parseRow(state);
46573 rows++;
46574 }
46575
46576 if (state.token !== ']') {
46577 throw createSyntaxError(state, 'End of matrix ] expected');
46578 }
46579
46580 closeParams(state);
46581 getToken(state); // check if the number of columns matches in all rows
46582
46583 cols = params[0].items.length;
46584
46585 for (var r = 1; r < rows; r++) {
46586 if (params[r].items.length !== cols) {
46587 throw createError(state, 'Column dimensions mismatch ' + '(' + params[r].items.length + ' !== ' + cols + ')');
46588 }
46589 }
46590
46591 array = new ArrayNode(params);
46592 } else {
46593 // 1 dimensional vector
46594 if (state.token !== ']') {
46595 throw createSyntaxError(state, 'End of matrix ] expected');
46596 }
46597
46598 closeParams(state);
46599 getToken(state);
46600 array = row;
46601 }
46602 } else {
46603 // this is an empty matrix "[ ]"
46604 closeParams(state);
46605 getToken(state);
46606 array = new ArrayNode([]);
46607 }
46608
46609 return parseAccessors(state, array);
46610 }
46611
46612 return parseObject(state);
46613 }
46614 /**
46615 * Parse a single comma-separated row from a matrix, like 'a, b, c'
46616 * @return {ArrayNode} node
46617 */
46618
46619
46620 function parseRow(state) {
46621 var params = [parseAssignment(state)];
46622 var len = 1;
46623
46624 while (state.token === ',') {
46625 // eslint-disable-line no-unmodified-loop-condition
46626 getToken(state); // parse expression
46627
46628 params[len] = parseAssignment(state);
46629 len++;
46630 }
46631
46632 return new ArrayNode(params);
46633 }
46634 /**
46635 * parse an object, enclosed in angle brackets{...}, for example {value: 2}
46636 * @return {Node} node
46637 * @private
46638 */
46639
46640
46641 function parseObject(state) {
46642 if (state.token === '{') {
46643 openParams(state);
46644 var key;
46645 var properties = {};
46646
46647 do {
46648 getToken(state);
46649
46650 if (state.token !== '}') {
46651 // parse key
46652 if (state.token === '"') {
46653 key = parseDoubleQuotesStringToken(state);
46654 } else if (state.token === '\'') {
46655 key = parseSingleQuotesStringToken(state);
46656 } else if (state.tokenType === TOKENTYPE.SYMBOL) {
46657 key = state.token;
46658 getToken(state);
46659 } else {
46660 throw createSyntaxError(state, 'Symbol or string expected as object key');
46661 } // parse key/value separator
46662
46663
46664 if (state.token !== ':') {
46665 throw createSyntaxError(state, 'Colon : expected after object key');
46666 }
46667
46668 getToken(state); // parse key
46669
46670 properties[key] = parseAssignment(state);
46671 }
46672 } while (state.token === ','); // eslint-disable-line no-unmodified-loop-condition
46673
46674
46675 if (state.token !== '}') {
46676 throw createSyntaxError(state, 'Comma , or bracket } expected after object value');
46677 }
46678
46679 closeParams(state);
46680 getToken(state);
46681 var node = new ObjectNode(properties); // parse index parameters
46682
46683 node = parseAccessors(state, node);
46684 return node;
46685 }
46686
46687 return parseNumber(state);
46688 }
46689 /**
46690 * parse a number
46691 * @return {Node} node
46692 * @private
46693 */
46694
46695
46696 function parseNumber(state) {
46697 var numberStr;
46698
46699 if (state.tokenType === TOKENTYPE.NUMBER) {
46700 // this is a number
46701 numberStr = state.token;
46702 getToken(state);
46703 return new ConstantNode(numeric(numberStr, config.number));
46704 }
46705
46706 return parseParentheses(state);
46707 }
46708 /**
46709 * parentheses
46710 * @return {Node} node
46711 * @private
46712 */
46713
46714
46715 function parseParentheses(state) {
46716 var node; // check if it is a parenthesized expression
46717
46718 if (state.token === '(') {
46719 // parentheses (...)
46720 openParams(state);
46721 getToken(state);
46722 node = parseAssignment(state); // start again
46723
46724 if (state.token !== ')') {
46725 throw createSyntaxError(state, 'Parenthesis ) expected');
46726 }
46727
46728 closeParams(state);
46729 getToken(state);
46730 node = new ParenthesisNode(node);
46731 node = parseAccessors(state, node);
46732 return node;
46733 }
46734
46735 return parseEnd(state);
46736 }
46737 /**
46738 * Evaluated when the expression is not yet ended but expected to end
46739 * @return {Node} res
46740 * @private
46741 */
46742
46743
46744 function parseEnd(state) {
46745 if (state.token === '') {
46746 // syntax error or unexpected end of expression
46747 throw createSyntaxError(state, 'Unexpected end of expression');
46748 } else {
46749 throw createSyntaxError(state, 'Value expected');
46750 }
46751 }
46752 /**
46753 * Shortcut for getting the current row value (one based)
46754 * Returns the line of the currently handled expression
46755 * @private
46756 */
46757
46758 /* TODO: implement keeping track on the row number
46759 function row () {
46760 return null
46761 }
46762 */
46763
46764 /**
46765 * Shortcut for getting the current col value (one based)
46766 * Returns the column (position) where the last state.token starts
46767 * @private
46768 */
46769
46770
46771 function col(state) {
46772 return state.index - state.token.length + 1;
46773 }
46774 /**
46775 * Create an error
46776 * @param {Object} state
46777 * @param {string} message
46778 * @return {SyntaxError} instantiated error
46779 * @private
46780 */
46781
46782
46783 function createSyntaxError(state, message) {
46784 var c = col(state);
46785 var error = new SyntaxError(message + ' (char ' + c + ')');
46786 error["char"] = c;
46787 return error;
46788 }
46789 /**
46790 * Create an error
46791 * @param {Object} state
46792 * @param {string} message
46793 * @return {Error} instantiated error
46794 * @private
46795 */
46796
46797
46798 function createError(state, message) {
46799 var c = col(state);
46800 var error = new SyntaxError(message + ' (char ' + c + ')');
46801 error["char"] = c;
46802 return error;
46803 }
46804
46805 return parse;
46806});
46807// CONCATENATED MODULE: ./src/expression/function/compile.js
46808
46809
46810var compile_name = 'compile';
46811var compile_dependencies = ['typed', 'parse'];
46812var createCompile =
46813/* #__PURE__ */
46814Object(factory["a" /* factory */])(compile_name, compile_dependencies, function (_ref) {
46815 var typed = _ref.typed,
46816 parse = _ref.parse;
46817
46818 /**
46819 * Parse and compile an expression.
46820 * Returns a an object with a function `evaluate([scope])` to evaluate the
46821 * compiled expression.
46822 *
46823 * Syntax:
46824 *
46825 * math.compile(expr) // returns one node
46826 * math.compile([expr1, expr2, expr3, ...]) // returns an array with nodes
46827 *
46828 * Examples:
46829 *
46830 * const code1 = math.compile('sqrt(3^2 + 4^2)')
46831 * code1.evaluate() // 5
46832 *
46833 * let scope = {a: 3, b: 4}
46834 * const code2 = math.compile('a * b') // 12
46835 * code2.evaluate(scope) // 12
46836 * scope.a = 5
46837 * code2.evaluate(scope) // 20
46838 *
46839 * const nodes = math.compile(['a = 3', 'b = 4', 'a * b'])
46840 * nodes[2].evaluate() // 12
46841 *
46842 * See also:
46843 *
46844 * parse, evaluate
46845 *
46846 * @param {string | string[] | Array | Matrix} expr
46847 * The expression to be compiled
46848 * @return {{evaluate: Function} | Array.<{evaluate: Function}>} code
46849 * An object with the compiled expression
46850 * @throws {Error}
46851 */
46852 return typed(compile_name, {
46853 string: function string(expr) {
46854 return parse(expr).compile();
46855 },
46856 'Array | Matrix': function ArrayMatrix(expr) {
46857 return deepMap(expr, function (entry) {
46858 return parse(entry).compile();
46859 });
46860 }
46861 });
46862});
46863// CONCATENATED MODULE: ./src/expression/function/evaluate.js
46864
46865
46866var evaluate_name = 'evaluate';
46867var evaluate_dependencies = ['typed', 'parse'];
46868var createEvaluate =
46869/* #__PURE__ */
46870Object(factory["a" /* factory */])(evaluate_name, evaluate_dependencies, function (_ref) {
46871 var typed = _ref.typed,
46872 parse = _ref.parse;
46873
46874 /**
46875 * Evaluate an expression.
46876 *
46877 * Note the evaluating arbitrary expressions may involve security risks,
46878 * see [https://mathjs.org/docs/expressions/security.html](https://mathjs.org/docs/expressions/security.html) for more information.
46879 *
46880 * Syntax:
46881 *
46882 * math.evaluate(expr)
46883 * math.evaluate(expr, scope)
46884 * math.evaluate([expr1, expr2, expr3, ...])
46885 * math.evaluate([expr1, expr2, expr3, ...], scope)
46886 *
46887 * Example:
46888 *
46889 * math.evaluate('(2+3)/4') // 1.25
46890 * math.evaluate('sqrt(3^2 + 4^2)') // 5
46891 * math.evaluate('sqrt(-4)') // 2i
46892 * math.evaluate(['a=3', 'b=4', 'a*b']) // [3, 4, 12]
46893 *
46894 * let scope = {a:3, b:4}
46895 * math.evaluate('a * b', scope) // 12
46896 *
46897 * See also:
46898 *
46899 * parse, compile
46900 *
46901 * @param {string | string[] | Matrix} expr The expression to be evaluated
46902 * @param {Object} [scope] Scope to read/write variables
46903 * @return {*} The result of the expression
46904 * @throws {Error}
46905 */
46906 return typed(evaluate_name, {
46907 string: function string(expr) {
46908 var scope = {};
46909 return parse(expr).compile().evaluate(scope);
46910 },
46911 'string, Object': function stringObject(expr, scope) {
46912 return parse(expr).compile().evaluate(scope);
46913 },
46914 'Array | Matrix': function ArrayMatrix(expr) {
46915 var scope = {};
46916 return deepMap(expr, function (entry) {
46917 return parse(entry).compile().evaluate(scope);
46918 });
46919 },
46920 'Array | Matrix, Object': function ArrayMatrixObject(expr, scope) {
46921 return deepMap(expr, function (entry) {
46922 return parse(entry).compile().evaluate(scope);
46923 });
46924 }
46925 });
46926});
46927// CONCATENATED MODULE: ./src/expression/function/eval.js
46928// For backward compatibility, deprecated since version 6.0.0. Date: 2018-12-05
46929
46930
46931var createDeprecatedEval =
46932/* #__PURE__ */
46933Object(factory["a" /* factory */])('eval', ['evaluate'], function (_ref) {
46934 var evaluate = _ref.evaluate;
46935 return function () {
46936 Object(utils_log["a" /* warnOnce */])('Function "eval" has been renamed to "evaluate" in v6.0.0, please use the new function instead.');
46937
46938 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
46939 args[_key] = arguments[_key];
46940 }
46941
46942 return evaluate.apply(evaluate, args);
46943 };
46944});
46945// CONCATENATED MODULE: ./src/expression/Parser.js
46946
46947
46948
46949
46950var Parser_name = 'Parser';
46951var Parser_dependencies = ['parse'];
46952var createParserClass =
46953/* #__PURE__ */
46954Object(factory["a" /* factory */])(Parser_name, Parser_dependencies, function (_ref) {
46955 var parse = _ref.parse;
46956
46957 /**
46958 * @constructor Parser
46959 * Parser contains methods to evaluate or parse expressions, and has a number
46960 * of convenience methods to get, set, and remove variables from memory. Parser
46961 * keeps a scope containing variables in memory, which is used for all
46962 * evaluations.
46963 *
46964 * Methods:
46965 * const result = parser.evaluate(expr) // evaluate an expression
46966 * const value = parser.get(name) // retrieve a variable from the parser
46967 * const values = parser.getAll() // retrieve all defined variables
46968 * parser.set(name, value) // set a variable in the parser
46969 * parser.remove(name) // clear a variable from the
46970 * // parsers scope
46971 * parser.clear() // clear the parsers scope
46972 *
46973 * Example usage:
46974 * const parser = new Parser()
46975 * // Note: there is a convenience method which can be used instead:
46976 * // const parser = new math.parser()
46977 *
46978 * // evaluate expressions
46979 * parser.evaluate('sqrt(3^2 + 4^2)') // 5
46980 * parser.evaluate('sqrt(-4)') // 2i
46981 * parser.evaluate('2 inch in cm') // 5.08 cm
46982 * parser.evaluate('cos(45 deg)') // 0.7071067811865476
46983 *
46984 * // define variables and functions
46985 * parser.evaluate('x = 7 / 2') // 3.5
46986 * parser.evaluate('x + 3') // 6.5
46987 * parser.evaluate('function f(x, y) = x^y') // f(x, y)
46988 * parser.evaluate('f(2, 3)') // 8
46989 *
46990 * // get and set variables and functions
46991 * const x = parser.get('x') // 7
46992 * const f = parser.get('f') // function
46993 * const g = f(3, 2) // 9
46994 * parser.set('h', 500)
46995 * const i = parser.evaluate('h / 2') // 250
46996 * parser.set('hello', function (name) {
46997 * return 'hello, ' + name + '!'
46998 * })
46999 * parser.evaluate('hello("user")') // "hello, user!"
47000 *
47001 * // clear defined functions and variables
47002 * parser.clear()
47003 *
47004 */
47005 function Parser() {
47006 if (!(this instanceof Parser)) {
47007 throw new SyntaxError('Constructor must be called with the new operator');
47008 }
47009
47010 this.scope = {};
47011 }
47012 /**
47013 * Attach type information
47014 */
47015
47016
47017 Parser.prototype.type = 'Parser';
47018 Parser.prototype.isParser = true;
47019 /**
47020 * Parse an expression and return the parsed function node.
47021 * The node tree can be compiled via `code = node.compile(math)`,
47022 * and the compiled code can be executed as `code.evaluate([scope])`
47023 * @param {string} expr
47024 * @return {Node} node
47025 * @throws {Error}
47026 */
47027
47028 Parser.prototype.parse = function (expr) {
47029 throw new Error('Parser.parse is deprecated. Use math.parse instead.');
47030 };
47031 /**
47032 * Parse and compile an expression, return the compiled javascript code.
47033 * The node can be evaluated via code.evaluate([scope])
47034 * @param {string} expr
47035 * @return {{evaluate: function}} code
47036 * @throws {Error}
47037 */
47038
47039
47040 Parser.prototype.compile = function (expr) {
47041 throw new Error('Parser.compile is deprecated. Use math.compile instead.');
47042 };
47043 /**
47044 * Parse and evaluate the given expression
47045 * @param {string} expr A string containing an expression, for example "2+3"
47046 * @return {*} result The result, or undefined when the expression was empty
47047 * @throws {Error}
47048 */
47049
47050
47051 Parser.prototype.evaluate = function (expr) {
47052 // TODO: validate arguments
47053 return parse(expr).compile().evaluate(this.scope);
47054 };
47055 /**
47056 * Parse and evaluate the given expression
47057 * @param {string} expr A string containing an expression, for example "2+3"
47058 * @return {*} result The result, or undefined when the expression was empty
47059 * @throws {Error}
47060 */
47061 // TODO: Deprecated since v6.0.0. Clean up some day
47062
47063
47064 Parser.prototype.eval = function (expr) {
47065 Object(utils_log["a" /* warnOnce */])('Method Parser.eval is renamed to Parser.evaluate. Please use the new method name.');
47066 return this.evaluate(expr);
47067 };
47068 /**
47069 * Get a variable (a function or variable) by name from the parsers scope.
47070 * Returns undefined when not found
47071 * @param {string} name
47072 * @return {* | undefined} value
47073 */
47074
47075
47076 Parser.prototype.get = function (name) {
47077 // TODO: validate arguments
47078 return name in this.scope ? getSafeProperty(this.scope, name) : undefined;
47079 };
47080 /**
47081 * Get a map with all defined variables
47082 * @return {Object} values
47083 */
47084
47085
47086 Parser.prototype.getAll = function () {
47087 return Object(utils_object["e" /* extend */])({}, this.scope);
47088 };
47089 /**
47090 * Set a symbol (a function or variable) by name from the parsers scope.
47091 * @param {string} name
47092 * @param {* | undefined} value
47093 */
47094
47095
47096 Parser.prototype.set = function (name, value) {
47097 // TODO: validate arguments
47098 return setSafeProperty(this.scope, name, value);
47099 };
47100 /**
47101 * Remove a variable from the parsers scope
47102 * @param {string} name
47103 */
47104
47105
47106 Parser.prototype.remove = function (name) {
47107 // TODO: validate arguments
47108 delete this.scope[name];
47109 };
47110 /**
47111 * Clear the scope with variables and functions
47112 */
47113
47114
47115 Parser.prototype.clear = function () {
47116 for (var _name in this.scope) {
47117 if (Object(utils_object["f" /* hasOwnProperty */])(this.scope, _name)) {
47118 delete this.scope[_name];
47119 }
47120 }
47121 };
47122
47123 return Parser;
47124}, {
47125 isClass: true
47126});
47127// CONCATENATED MODULE: ./src/expression/function/parser.js
47128
47129var parser_name = 'parser';
47130var parser_dependencies = ['typed', 'Parser'];
47131var createParser =
47132/* #__PURE__ */
47133Object(factory["a" /* factory */])(parser_name, parser_dependencies, function (_ref) {
47134 var typed = _ref.typed,
47135 Parser = _ref.Parser;
47136
47137 /**
47138 * Create a parser. The function creates a new `math.Parser` object.
47139 *
47140 * Syntax:
47141 *
47142 * math.parser()
47143 *
47144 * Examples:
47145 *
47146 * const parser = new math.parser()
47147 *
47148 * // evaluate expressions
47149 * const a = parser.evaluate('sqrt(3^2 + 4^2)') // 5
47150 * const b = parser.evaluate('sqrt(-4)') // 2i
47151 * const c = parser.evaluate('2 inch in cm') // 5.08 cm
47152 * const d = parser.evaluate('cos(45 deg)') // 0.7071067811865476
47153 *
47154 * // define variables and functions
47155 * parser.evaluate('x = 7 / 2') // 3.5
47156 * parser.evaluate('x + 3') // 6.5
47157 * parser.evaluate('function f(x, y) = x^y') // f(x, y)
47158 * parser.evaluate('f(2, 3)') // 8
47159 *
47160 * // get and set variables and functions
47161 * const x = parser.get('x') // 7
47162 * const f = parser.get('f') // function
47163 * const g = f(3, 2) // 9
47164 * parser.set('h', 500)
47165 * const i = parser.evaluate('h / 2') // 250
47166 * parser.set('hello', function (name) {
47167 * return 'hello, ' + name + '!'
47168 * })
47169 * parser.evaluate('hello("user")') // "hello, user!"
47170 *
47171 * // clear defined functions and variables
47172 * parser.clear()
47173 *
47174 * See also:
47175 *
47176 * evaluate, compile, parse
47177 *
47178 * @return {Parser} Parser
47179 */
47180 return typed(parser_name, {
47181 '': function _() {
47182 return new Parser();
47183 }
47184 });
47185});
47186// CONCATENATED MODULE: ./src/function/algebra/decomposition/lup.js
47187
47188
47189var lup_name = 'lup';
47190var lup_dependencies = ['typed', 'matrix', 'abs', 'addScalar', 'divideScalar', 'multiplyScalar', 'subtract', 'larger', 'equalScalar', 'unaryMinus', 'DenseMatrix', 'SparseMatrix', 'Spa'];
47191var createLup =
47192/* #__PURE__ */
47193Object(factory["a" /* factory */])(lup_name, lup_dependencies, function (_ref) {
47194 var typed = _ref.typed,
47195 matrix = _ref.matrix,
47196 abs = _ref.abs,
47197 addScalar = _ref.addScalar,
47198 divideScalar = _ref.divideScalar,
47199 multiplyScalar = _ref.multiplyScalar,
47200 subtract = _ref.subtract,
47201 larger = _ref.larger,
47202 equalScalar = _ref.equalScalar,
47203 unaryMinus = _ref.unaryMinus,
47204 DenseMatrix = _ref.DenseMatrix,
47205 SparseMatrix = _ref.SparseMatrix,
47206 Spa = _ref.Spa;
47207
47208 /**
47209 * Calculate the Matrix LU decomposition with partial pivoting. Matrix `A` is decomposed in two matrices (`L`, `U`) and a
47210 * row permutation vector `p` where `A[p,:] = L * U`
47211 *
47212 * Syntax:
47213 *
47214 * math.lup(A)
47215 *
47216 * Example:
47217 *
47218 * const m = [[2, 1], [1, 4]]
47219 * const r = math.lup(m)
47220 * // r = {
47221 * // L: [[1, 0], [0.5, 1]],
47222 * // U: [[2, 1], [0, 3.5]],
47223 * // P: [0, 1]
47224 * // }
47225 *
47226 * See also:
47227 *
47228 * slu, lsolve, lusolve, usolve
47229 *
47230 * @param {Matrix | Array} A A two dimensional matrix or array for which to get the LUP decomposition.
47231 *
47232 * @return {{L: Array | Matrix, U: Array | Matrix, P: Array.<number>}} The lower triangular matrix, the upper triangular matrix and the permutation matrix.
47233 */
47234 return typed(lup_name, {
47235 DenseMatrix: function DenseMatrix(m) {
47236 return _denseLUP(m);
47237 },
47238 SparseMatrix: function SparseMatrix(m) {
47239 return _sparseLUP(m);
47240 },
47241 Array: function Array(a) {
47242 // create dense matrix from array
47243 var m = matrix(a); // lup, use matrix implementation
47244
47245 var r = _denseLUP(m); // result
47246
47247
47248 return {
47249 L: r.L.valueOf(),
47250 U: r.U.valueOf(),
47251 p: r.p
47252 };
47253 }
47254 });
47255
47256 function _denseLUP(m) {
47257 // rows & columns
47258 var rows = m._size[0];
47259 var columns = m._size[1]; // minimum rows and columns
47260
47261 var n = Math.min(rows, columns); // matrix array, clone original data
47262
47263 var data = Object(utils_object["a" /* clone */])(m._data); // l matrix arrays
47264
47265 var ldata = [];
47266 var lsize = [rows, n]; // u matrix arrays
47267
47268 var udata = [];
47269 var usize = [n, columns]; // vars
47270
47271 var i, j, k; // permutation vector
47272
47273 var p = [];
47274
47275 for (i = 0; i < rows; i++) {
47276 p[i] = i;
47277 } // loop columns
47278
47279
47280 for (j = 0; j < columns; j++) {
47281 // skip first column in upper triangular matrix
47282 if (j > 0) {
47283 // loop rows
47284 for (i = 0; i < rows; i++) {
47285 // min i,j
47286 var min = Math.min(i, j); // v[i, j]
47287
47288 var s = 0; // loop up to min
47289
47290 for (k = 0; k < min; k++) {
47291 // s = l[i, k] - data[k, j]
47292 s = addScalar(s, multiplyScalar(data[i][k], data[k][j]));
47293 }
47294
47295 data[i][j] = subtract(data[i][j], s);
47296 }
47297 } // row with larger value in cvector, row >= j
47298
47299
47300 var pi = j;
47301 var pabsv = 0;
47302 var vjj = 0; // loop rows
47303
47304 for (i = j; i < rows; i++) {
47305 // data @ i, j
47306 var v = data[i][j]; // absolute value
47307
47308 var absv = abs(v); // value is greater than pivote value
47309
47310 if (larger(absv, pabsv)) {
47311 // store row
47312 pi = i; // update max value
47313
47314 pabsv = absv; // value @ [j, j]
47315
47316 vjj = v;
47317 }
47318 } // swap rows (j <-> pi)
47319
47320
47321 if (j !== pi) {
47322 // swap values j <-> pi in p
47323 p[j] = [p[pi], p[pi] = p[j]][0]; // swap j <-> pi in data
47324
47325 DenseMatrix._swapRows(j, pi, data);
47326 } // check column is in lower triangular matrix
47327
47328
47329 if (j < rows) {
47330 // loop rows (lower triangular matrix)
47331 for (i = j + 1; i < rows; i++) {
47332 // value @ i, j
47333 var vij = data[i][j];
47334
47335 if (!equalScalar(vij, 0)) {
47336 // update data
47337 data[i][j] = divideScalar(data[i][j], vjj);
47338 }
47339 }
47340 }
47341 } // loop columns
47342
47343
47344 for (j = 0; j < columns; j++) {
47345 // loop rows
47346 for (i = 0; i < rows; i++) {
47347 // initialize row in arrays
47348 if (j === 0) {
47349 // check row exists in upper triangular matrix
47350 if (i < columns) {
47351 // U
47352 udata[i] = [];
47353 } // L
47354
47355
47356 ldata[i] = [];
47357 } // check we are in the upper triangular matrix
47358
47359
47360 if (i < j) {
47361 // check row exists in upper triangular matrix
47362 if (i < columns) {
47363 // U
47364 udata[i][j] = data[i][j];
47365 } // check column exists in lower triangular matrix
47366
47367
47368 if (j < rows) {
47369 // L
47370 ldata[i][j] = 0;
47371 }
47372
47373 continue;
47374 } // diagonal value
47375
47376
47377 if (i === j) {
47378 // check row exists in upper triangular matrix
47379 if (i < columns) {
47380 // U
47381 udata[i][j] = data[i][j];
47382 } // check column exists in lower triangular matrix
47383
47384
47385 if (j < rows) {
47386 // L
47387 ldata[i][j] = 1;
47388 }
47389
47390 continue;
47391 } // check row exists in upper triangular matrix
47392
47393
47394 if (i < columns) {
47395 // U
47396 udata[i][j] = 0;
47397 } // check column exists in lower triangular matrix
47398
47399
47400 if (j < rows) {
47401 // L
47402 ldata[i][j] = data[i][j];
47403 }
47404 }
47405 } // l matrix
47406
47407
47408 var l = new DenseMatrix({
47409 data: ldata,
47410 size: lsize
47411 }); // u matrix
47412
47413 var u = new DenseMatrix({
47414 data: udata,
47415 size: usize
47416 }); // p vector
47417
47418 var pv = [];
47419
47420 for (i = 0, n = p.length; i < n; i++) {
47421 pv[p[i]] = i;
47422 } // return matrices
47423
47424
47425 return {
47426 L: l,
47427 U: u,
47428 p: pv,
47429 toString: function toString() {
47430 return 'L: ' + this.L.toString() + '\nU: ' + this.U.toString() + '\nP: ' + this.p;
47431 }
47432 };
47433 }
47434
47435 function _sparseLUP(m) {
47436 // rows & columns
47437 var rows = m._size[0];
47438 var columns = m._size[1]; // minimum rows and columns
47439
47440 var n = Math.min(rows, columns); // matrix arrays (will not be modified, thanks to permutation vector)
47441
47442 var values = m._values;
47443 var index = m._index;
47444 var ptr = m._ptr; // l matrix arrays
47445
47446 var lvalues = [];
47447 var lindex = [];
47448 var lptr = [];
47449 var lsize = [rows, n]; // u matrix arrays
47450
47451 var uvalues = [];
47452 var uindex = [];
47453 var uptr = [];
47454 var usize = [n, columns]; // vars
47455
47456 var i, j, k; // permutation vectors, (current index -> original index) and (original index -> current index)
47457
47458 var pvCo = [];
47459 var pvOc = [];
47460
47461 for (i = 0; i < rows; i++) {
47462 pvCo[i] = i;
47463 pvOc[i] = i;
47464 } // swap indices in permutation vectors (condition x < y)!
47465
47466
47467 var swapIndeces = function swapIndeces(x, y) {
47468 // find pv indeces getting data from x and y
47469 var kx = pvOc[x];
47470 var ky = pvOc[y]; // update permutation vector current -> original
47471
47472 pvCo[kx] = y;
47473 pvCo[ky] = x; // update permutation vector original -> current
47474
47475 pvOc[x] = ky;
47476 pvOc[y] = kx;
47477 }; // loop columns
47478
47479
47480 var _loop = function _loop() {
47481 // sparse accumulator
47482 var spa = new Spa(); // check lower triangular matrix has a value @ column j
47483
47484 if (j < rows) {
47485 // update ptr
47486 lptr.push(lvalues.length); // first value in j column for lower triangular matrix
47487
47488 lvalues.push(1);
47489 lindex.push(j);
47490 } // update ptr
47491
47492
47493 uptr.push(uvalues.length); // k0 <= k < k1 where k0 = _ptr[j] && k1 = _ptr[j+1]
47494
47495 var k0 = ptr[j];
47496 var k1 = ptr[j + 1]; // copy column j into sparse accumulator
47497
47498 for (k = k0; k < k1; k++) {
47499 // row
47500 i = index[k]; // copy column values into sparse accumulator (use permutation vector)
47501
47502 spa.set(pvCo[i], values[k]);
47503 } // skip first column in upper triangular matrix
47504
47505
47506 if (j > 0) {
47507 // loop rows in column j (above diagonal)
47508 spa.forEach(0, j - 1, function (k, vkj) {
47509 // loop rows in column k (L)
47510 SparseMatrix._forEachRow(k, lvalues, lindex, lptr, function (i, vik) {
47511 // check row is below k
47512 if (i > k) {
47513 // update spa value
47514 spa.accumulate(i, unaryMinus(multiplyScalar(vik, vkj)));
47515 }
47516 });
47517 });
47518 } // row with larger value in spa, row >= j
47519
47520
47521 var pi = j;
47522 var vjj = spa.get(j);
47523 var pabsv = abs(vjj); // loop values in spa (order by row, below diagonal)
47524
47525 spa.forEach(j + 1, rows - 1, function (x, v) {
47526 // absolute value
47527 var absv = abs(v); // value is greater than pivote value
47528
47529 if (larger(absv, pabsv)) {
47530 // store row
47531 pi = x; // update max value
47532
47533 pabsv = absv; // value @ [j, j]
47534
47535 vjj = v;
47536 }
47537 }); // swap rows (j <-> pi)
47538
47539 if (j !== pi) {
47540 // swap values j <-> pi in L
47541 SparseMatrix._swapRows(j, pi, lsize[1], lvalues, lindex, lptr); // swap values j <-> pi in U
47542
47543
47544 SparseMatrix._swapRows(j, pi, usize[1], uvalues, uindex, uptr); // swap values in spa
47545
47546
47547 spa.swap(j, pi); // update permutation vector (swap values @ j, pi)
47548
47549 swapIndeces(j, pi);
47550 } // loop values in spa (order by row)
47551
47552
47553 spa.forEach(0, rows - 1, function (x, v) {
47554 // check we are above diagonal
47555 if (x <= j) {
47556 // update upper triangular matrix
47557 uvalues.push(v);
47558 uindex.push(x);
47559 } else {
47560 // update value
47561 v = divideScalar(v, vjj); // check value is non zero
47562
47563 if (!equalScalar(v, 0)) {
47564 // update lower triangular matrix
47565 lvalues.push(v);
47566 lindex.push(x);
47567 }
47568 }
47569 });
47570 };
47571
47572 for (j = 0; j < columns; j++) {
47573 _loop();
47574 } // update ptrs
47575
47576
47577 uptr.push(uvalues.length);
47578 lptr.push(lvalues.length); // return matrices
47579
47580 return {
47581 L: new SparseMatrix({
47582 values: lvalues,
47583 index: lindex,
47584 ptr: lptr,
47585 size: lsize
47586 }),
47587 U: new SparseMatrix({
47588 values: uvalues,
47589 index: uindex,
47590 ptr: uptr,
47591 size: usize
47592 }),
47593 p: pvCo,
47594 toString: function toString() {
47595 return 'L: ' + this.L.toString() + '\nU: ' + this.U.toString() + '\nP: ' + this.p;
47596 }
47597 };
47598 }
47599});
47600// CONCATENATED MODULE: ./src/function/algebra/decomposition/qr.js
47601
47602var qr_name = 'qr';
47603var qr_dependencies = ['typed', 'matrix', 'zeros', 'identity', 'isZero', 'unequal', 'sign', 'sqrt', 'conj', 'unaryMinus', 'addScalar', 'divideScalar', 'multiplyScalar', 'subtract'];
47604var createQr =
47605/* #__PURE__ */
47606Object(factory["a" /* factory */])(qr_name, qr_dependencies, function (_ref) {
47607 var typed = _ref.typed,
47608 matrix = _ref.matrix,
47609 zeros = _ref.zeros,
47610 identity = _ref.identity,
47611 isZero = _ref.isZero,
47612 unequal = _ref.unequal,
47613 sign = _ref.sign,
47614 sqrt = _ref.sqrt,
47615 conj = _ref.conj,
47616 unaryMinus = _ref.unaryMinus,
47617 addScalar = _ref.addScalar,
47618 divideScalar = _ref.divideScalar,
47619 multiplyScalar = _ref.multiplyScalar,
47620 subtract = _ref.subtract;
47621
47622 /**
47623 * Calculate the Matrix QR decomposition. Matrix `A` is decomposed in
47624 * two matrices (`Q`, `R`) where `Q` is an
47625 * orthogonal matrix and `R` is an upper triangular matrix.
47626 *
47627 * Syntax:
47628 *
47629 * math.qr(A)
47630 *
47631 * Example:
47632 *
47633 * const m = [
47634 * [1, -1, 4],
47635 * [1, 4, -2],
47636 * [1, 4, 2],
47637 * [1, -1, 0]
47638 * ]
47639 * const result = math.qr(m)
47640 * // r = {
47641 * // Q: [
47642 * // [0.5, -0.5, 0.5],
47643 * // [0.5, 0.5, -0.5],
47644 * // [0.5, 0.5, 0.5],
47645 * // [0.5, -0.5, -0.5],
47646 * // ],
47647 * // R: [
47648 * // [2, 3, 2],
47649 * // [0, 5, -2],
47650 * // [0, 0, 4],
47651 * // [0, 0, 0]
47652 * // ]
47653 * // }
47654 *
47655 * See also:
47656 *
47657 * lup, lusolve
47658 *
47659 * @param {Matrix | Array} A A two dimensional matrix or array
47660 * for which to get the QR decomposition.
47661 *
47662 * @return {{Q: Array | Matrix, R: Array | Matrix}} Q: the orthogonal
47663 * matrix and R: the upper triangular matrix
47664 */
47665 return typed(qr_name, {
47666 DenseMatrix: function DenseMatrix(m) {
47667 return _denseQR(m);
47668 },
47669 SparseMatrix: function SparseMatrix(m) {
47670 return _sparseQR(m);
47671 },
47672 Array: function Array(a) {
47673 // create dense matrix from array
47674 var m = matrix(a); // lup, use matrix implementation
47675
47676 var r = _denseQR(m); // result
47677
47678
47679 return {
47680 Q: r.Q.valueOf(),
47681 R: r.R.valueOf()
47682 };
47683 }
47684 });
47685
47686 function _denseQR(m) {
47687 // rows & columns (m x n)
47688 var rows = m._size[0]; // m
47689
47690 var cols = m._size[1]; // n
47691
47692 var Q = identity([rows], 'dense');
47693 var Qdata = Q._data;
47694 var R = m.clone();
47695 var Rdata = R._data; // vars
47696
47697 var i, j, k;
47698 var w = zeros([rows], '');
47699
47700 for (k = 0; k < Math.min(cols, rows); ++k) {
47701 /*
47702 * **k-th Household matrix**
47703 *
47704 * The matrix I - 2*v*transpose(v)
47705 * x = first column of A
47706 * x1 = first element of x
47707 * alpha = x1 / |x1| * |x|
47708 * e1 = tranpose([1, 0, 0, ...])
47709 * u = x - alpha * e1
47710 * v = u / |u|
47711 *
47712 * Household matrix = I - 2 * v * tranpose(v)
47713 *
47714 * * Initially Q = I and R = A.
47715 * * Household matrix is a reflection in a plane normal to v which
47716 * will zero out all but the top right element in R.
47717 * * Appplying reflection to both Q and R will not change product.
47718 * * Repeat this process on the (1,1) minor to get R as an upper
47719 * triangular matrix.
47720 * * Reflections leave the magnitude of the columns of Q unchanged
47721 * so Q remains othoganal.
47722 *
47723 */
47724 var pivot = Rdata[k][k];
47725 var sgn = unaryMinus(sign(pivot));
47726 var conjSgn = conj(sgn);
47727 var alphaSquared = 0;
47728
47729 for (i = k; i < rows; i++) {
47730 alphaSquared = addScalar(alphaSquared, multiplyScalar(Rdata[i][k], conj(Rdata[i][k])));
47731 }
47732
47733 var alpha = multiplyScalar(sgn, sqrt(alphaSquared));
47734
47735 if (!isZero(alpha)) {
47736 // first element in vector u
47737 var u1 = subtract(pivot, alpha); // w = v * u1 / |u| (only elements k to (rows-1) are used)
47738
47739 w[k] = 1;
47740
47741 for (i = k + 1; i < rows; i++) {
47742 w[i] = divideScalar(Rdata[i][k], u1);
47743 } // tau = - conj(u1 / alpha)
47744
47745
47746 var tau = unaryMinus(conj(divideScalar(u1, alpha)));
47747 var s = void 0;
47748 /*
47749 * tau and w have been choosen so that
47750 *
47751 * 2 * v * tranpose(v) = tau * w * tranpose(w)
47752 */
47753
47754 /*
47755 * -- calculate R = R - tau * w * tranpose(w) * R --
47756 * Only do calculation with rows k to (rows-1)
47757 * Additionally columns 0 to (k-1) will not be changed by this
47758 * multiplication so do not bother recalculating them
47759 */
47760
47761 for (j = k; j < cols; j++) {
47762 s = 0.0; // calculate jth element of [tranpose(w) * R]
47763
47764 for (i = k; i < rows; i++) {
47765 s = addScalar(s, multiplyScalar(conj(w[i]), Rdata[i][j]));
47766 } // calculate the jth element of [tau * transpose(w) * R]
47767
47768
47769 s = multiplyScalar(s, tau);
47770
47771 for (i = k; i < rows; i++) {
47772 Rdata[i][j] = multiplyScalar(subtract(Rdata[i][j], multiplyScalar(w[i], s)), conjSgn);
47773 }
47774 }
47775 /*
47776 * -- calculate Q = Q - tau * Q * w * transpose(w) --
47777 * Q is a square matrix (rows x rows)
47778 * Only do calculation with columns k to (rows-1)
47779 * Additionally rows 0 to (k-1) will not be changed by this
47780 * multiplication so do not bother recalculating them
47781 */
47782
47783
47784 for (i = 0; i < rows; i++) {
47785 s = 0.0; // calculate ith element of [Q * w]
47786
47787 for (j = k; j < rows; j++) {
47788 s = addScalar(s, multiplyScalar(Qdata[i][j], w[j]));
47789 } // calculate the ith element of [tau * Q * w]
47790
47791
47792 s = multiplyScalar(s, tau);
47793
47794 for (j = k; j < rows; ++j) {
47795 Qdata[i][j] = divideScalar(subtract(Qdata[i][j], multiplyScalar(s, conj(w[j]))), conjSgn);
47796 }
47797 }
47798 }
47799 } // coerse almost zero elements to zero
47800 // TODO I feel uneasy just zeroing these values
47801
47802
47803 for (i = 0; i < rows; ++i) {
47804 for (j = 0; j < i && j < cols; ++j) {
47805 if (unequal(0, divideScalar(Rdata[i][j], 1e5))) {
47806 throw new Error('math.qr(): unknown error - ' + 'R is not lower triangular (element (' + i + ', ' + j + ') = ' + Rdata[i][j] + ')');
47807 }
47808
47809 Rdata[i][j] = multiplyScalar(Rdata[i][j], 0);
47810 }
47811 } // return matrices
47812
47813
47814 return {
47815 Q: Q,
47816 R: R,
47817 toString: function toString() {
47818 return 'Q: ' + this.Q.toString() + '\nR: ' + this.R.toString();
47819 }
47820 };
47821 }
47822
47823 function _sparseQR(m) {
47824 throw new Error('qr not implemented for sparse matrices yet');
47825 }
47826});
47827// CONCATENATED MODULE: ./src/function/algebra/sparse/csPermute.js
47828/**
47829 * Permutes a sparse matrix C = P * A * Q
47830 *
47831 * @param {SparseMatrix} a The Matrix A
47832 * @param {Array} pinv The row permutation vector
47833 * @param {Array} q The column permutation vector
47834 * @param {boolean} values Create a pattern matrix (false), values and pattern otherwise
47835 *
47836 * @return {Matrix} C = P * A * Q, null on error
47837 *
47838 * Reference: http://faculty.cse.tamu.edu/davis/publications.html
47839 */
47840function csPermute(a, pinv, q, values) {
47841 // a arrays
47842 var avalues = a._values;
47843 var aindex = a._index;
47844 var aptr = a._ptr;
47845 var asize = a._size;
47846 var adt = a._datatype; // rows & columns
47847
47848 var m = asize[0];
47849 var n = asize[1]; // c arrays
47850
47851 var cvalues = values && a._values ? [] : null;
47852 var cindex = []; // (aptr[n])
47853
47854 var cptr = []; // (n + 1)
47855 // initialize vars
47856
47857 var nz = 0; // loop columns
47858
47859 for (var k = 0; k < n; k++) {
47860 // column k of C is column q[k] of A
47861 cptr[k] = nz; // apply column permutation
47862
47863 var j = q ? q[k] : k; // loop values in column j of A
47864
47865 for (var t0 = aptr[j], t1 = aptr[j + 1], t = t0; t < t1; t++) {
47866 // row i of A is row pinv[i] of C
47867 var r = pinv ? pinv[aindex[t]] : aindex[t]; // index
47868
47869 cindex[nz] = r; // check we need to populate values
47870
47871 if (cvalues) {
47872 cvalues[nz] = avalues[t];
47873 } // increment number of nonzero elements
47874
47875
47876 nz++;
47877 }
47878 } // finalize the last column of C
47879
47880
47881 cptr[n] = nz; // return C matrix
47882
47883 return a.createSparseMatrix({
47884 values: cvalues,
47885 index: cindex,
47886 ptr: cptr,
47887 size: [m, n],
47888 datatype: adt
47889 });
47890}
47891// CONCATENATED MODULE: ./src/function/algebra/sparse/csTdfs.js
47892/**
47893 * Depth-first search and postorder of a tree rooted at node j
47894 *
47895 * @param {Number} j The tree node
47896 * @param {Number} k
47897 * @param {Array} w The workspace array
47898 * @param {Number} head The index offset within the workspace for the head array
47899 * @param {Number} next The index offset within the workspace for the next array
47900 * @param {Array} post The post ordering array
47901 * @param {Number} stack The index offset within the workspace for the stack array
47902 *
47903 * Reference: http://faculty.cse.tamu.edu/davis/publications.html
47904 */
47905function csTdfs(j, k, w, head, next, post, stack) {
47906 // variables
47907 var top = 0; // place j on the stack
47908
47909 w[stack] = j; // while (stack is not empty)
47910
47911 while (top >= 0) {
47912 // p = top of stack
47913 var p = w[stack + top]; // i = youngest child of p
47914
47915 var i = w[head + p];
47916
47917 if (i === -1) {
47918 // p has no unordered children left
47919 top--; // node p is the kth postordered node
47920
47921 post[k++] = p;
47922 } else {
47923 // remove i from children of p
47924 w[head + p] = w[next + i]; // increment top
47925
47926 ++top; // start dfs on child node i
47927
47928 w[stack + top] = i;
47929 }
47930 }
47931
47932 return k;
47933}
47934// CONCATENATED MODULE: ./src/function/algebra/sparse/csPost.js
47935
47936/**
47937 * Post order a tree of forest
47938 *
47939 * @param {Array} parent The tree or forest
47940 * @param {Number} n Number of columns
47941 *
47942 * Reference: http://faculty.cse.tamu.edu/davis/publications.html
47943 */
47944
47945function csPost(parent, n) {
47946 // check inputs
47947 if (!parent) {
47948 return null;
47949 } // vars
47950
47951
47952 var k = 0;
47953 var j; // allocate result
47954
47955 var post = []; // (n)
47956 // workspace, head: first n entries, next: next n entries, stack: last n entries
47957
47958 var w = []; // (3 * n)
47959
47960 var head = 0;
47961 var next = n;
47962 var stack = 2 * n; // initialize workspace
47963
47964 for (j = 0; j < n; j++) {
47965 // empty linked lists
47966 w[head + j] = -1;
47967 } // traverse nodes in reverse order
47968
47969
47970 for (j = n - 1; j >= 0; j--) {
47971 // check j is a root
47972 if (parent[j] === -1) {
47973 continue;
47974 } // add j to list of its parent
47975
47976
47977 w[next + j] = w[head + parent[j]];
47978 w[head + parent[j]] = j;
47979 } // loop nodes
47980
47981
47982 for (j = 0; j < n; j++) {
47983 // skip j if it is not a root
47984 if (parent[j] !== -1) {
47985 continue;
47986 } // depth-first search
47987
47988
47989 k = csTdfs(j, k, w, head, next, post, stack);
47990 }
47991
47992 return post;
47993}
47994// CONCATENATED MODULE: ./src/function/algebra/sparse/csEtree.js
47995/**
47996 * Computes the elimination tree of Matrix A (using triu(A)) or the
47997 * elimination tree of A'A without forming A'A.
47998 *
47999 * @param {Matrix} a The A Matrix
48000 * @param {boolean} ata A value of true the function computes the etree of A'A
48001 *
48002 * Reference: http://faculty.cse.tamu.edu/davis/publications.html
48003 */
48004function csEtree(a, ata) {
48005 // check inputs
48006 if (!a) {
48007 return null;
48008 } // a arrays
48009
48010
48011 var aindex = a._index;
48012 var aptr = a._ptr;
48013 var asize = a._size; // rows & columns
48014
48015 var m = asize[0];
48016 var n = asize[1]; // allocate result
48017
48018 var parent = []; // (n)
48019 // allocate workspace
48020
48021 var w = []; // (n + (ata ? m : 0))
48022
48023 var ancestor = 0; // first n entries in w
48024
48025 var prev = n; // last m entries (ata = true)
48026
48027 var i, inext; // check we are calculating A'A
48028
48029 if (ata) {
48030 // initialize workspace
48031 for (i = 0; i < m; i++) {
48032 w[prev + i] = -1;
48033 }
48034 } // loop columns
48035
48036
48037 for (var k = 0; k < n; k++) {
48038 // node k has no parent yet
48039 parent[k] = -1; // nor does k have an ancestor
48040
48041 w[ancestor + k] = -1; // values in column k
48042
48043 for (var p0 = aptr[k], p1 = aptr[k + 1], p = p0; p < p1; p++) {
48044 // row
48045 var r = aindex[p]; // node
48046
48047 i = ata ? w[prev + r] : r; // traverse from i to k
48048
48049 for (; i !== -1 && i < k; i = inext) {
48050 // inext = ancestor of i
48051 inext = w[ancestor + i]; // path compression
48052
48053 w[ancestor + i] = k; // check no anc., parent is k
48054
48055 if (inext === -1) {
48056 parent[i] = k;
48057 }
48058 }
48059
48060 if (ata) {
48061 w[prev + r] = k;
48062 }
48063 }
48064 }
48065
48066 return parent;
48067}
48068// CONCATENATED MODULE: ./src/function/algebra/sparse/csFkeep.js
48069/**
48070 * Keeps entries in the matrix when the callback function returns true, removes the entry otherwise
48071 *
48072 * @param {Matrix} a The sparse matrix
48073 * @param {function} callback The callback function, function will be invoked with the following args:
48074 * - The entry row
48075 * - The entry column
48076 * - The entry value
48077 * - The state parameter
48078 * @param {any} other The state
48079 *
48080 * @return The number of nonzero elements in the matrix
48081 *
48082 * Reference: http://faculty.cse.tamu.edu/davis/publications.html
48083 */
48084function csFkeep(a, callback, other) {
48085 // a arrays
48086 var avalues = a._values;
48087 var aindex = a._index;
48088 var aptr = a._ptr;
48089 var asize = a._size; // columns
48090
48091 var n = asize[1]; // nonzero items
48092
48093 var nz = 0; // loop columns
48094
48095 for (var j = 0; j < n; j++) {
48096 // get current location of col j
48097 var p = aptr[j]; // record new location of col j
48098
48099 aptr[j] = nz;
48100
48101 for (; p < aptr[j + 1]; p++) {
48102 // check we need to keep this item
48103 if (callback(aindex[p], j, avalues ? avalues[p] : 1, other)) {
48104 // keep A(i,j)
48105 aindex[nz] = aindex[p]; // check we need to process values (pattern only)
48106
48107 if (avalues) {
48108 avalues[nz] = avalues[p];
48109 } // increment nonzero items
48110
48111
48112 nz++;
48113 }
48114 }
48115 } // finalize A
48116
48117
48118 aptr[n] = nz; // trim arrays
48119
48120 aindex.splice(nz, aindex.length - nz); // check we need to process values (pattern only)
48121
48122 if (avalues) {
48123 avalues.splice(nz, avalues.length - nz);
48124 } // return number of nonzero items
48125
48126
48127 return nz;
48128}
48129// CONCATENATED MODULE: ./src/function/algebra/sparse/csFlip.js
48130/**
48131 * This function "flips" its input about the integer -1.
48132 *
48133 * @param {Number} i The value to flip
48134 *
48135 * Reference: http://faculty.cse.tamu.edu/davis/publications.html
48136 */
48137function csFlip(i) {
48138 // flip the value
48139 return -i - 2;
48140}
48141// CONCATENATED MODULE: ./src/function/algebra/sparse/csAmd.js
48142
48143
48144
48145
48146var csAmd_name = 'csAmd';
48147var csAmd_dependencies = ['add', 'multiply', 'transpose'];
48148var createCsAmd =
48149/* #__PURE__ */
48150Object(factory["a" /* factory */])(csAmd_name, csAmd_dependencies, function (_ref) {
48151 var add = _ref.add,
48152 multiply = _ref.multiply,
48153 transpose = _ref.transpose;
48154
48155 /**
48156 * Approximate minimum degree ordering. The minimum degree algorithm is a widely used
48157 * heuristic for finding a permutation P so that P*A*P' has fewer nonzeros in its factorization
48158 * than A. It is a gready method that selects the sparsest pivot row and column during the course
48159 * of a right looking sparse Cholesky factorization.
48160 *
48161 * Reference: http://faculty.cse.tamu.edu/davis/publications.html
48162 *
48163 * @param {Number} order 0: Natural, 1: Cholesky, 2: LU, 3: QR
48164 * @param {Matrix} m Sparse Matrix
48165 */
48166 return function csAmd(order, a) {
48167 // check input parameters
48168 if (!a || order <= 0 || order > 3) {
48169 return null;
48170 } // a matrix arrays
48171
48172
48173 var asize = a._size; // rows and columns
48174
48175 var m = asize[0];
48176 var n = asize[1]; // initialize vars
48177
48178 var lemax = 0; // dense threshold
48179
48180 var dense = Math.max(16, 10 * Math.sqrt(n));
48181 dense = Math.min(n - 2, dense); // create target matrix C
48182
48183 var cm = _createTargetMatrix(order, a, m, n, dense); // drop diagonal entries
48184
48185
48186 csFkeep(cm, _diag, null); // C matrix arrays
48187
48188 var cindex = cm._index;
48189 var cptr = cm._ptr; // number of nonzero elements in C
48190
48191 var cnz = cptr[n]; // allocate result (n+1)
48192
48193 var P = []; // create workspace (8 * (n + 1))
48194
48195 var W = [];
48196 var len = 0; // first n + 1 entries
48197
48198 var nv = n + 1; // next n + 1 entries
48199
48200 var next = 2 * (n + 1); // next n + 1 entries
48201
48202 var head = 3 * (n + 1); // next n + 1 entries
48203
48204 var elen = 4 * (n + 1); // next n + 1 entries
48205
48206 var degree = 5 * (n + 1); // next n + 1 entries
48207
48208 var w = 6 * (n + 1); // next n + 1 entries
48209
48210 var hhead = 7 * (n + 1); // last n + 1 entries
48211 // use P as workspace for last
48212
48213 var last = P; // initialize quotient graph
48214
48215 var mark = _initializeQuotientGraph(n, cptr, W, len, head, last, next, hhead, nv, w, elen, degree); // initialize degree lists
48216
48217
48218 var nel = _initializeDegreeLists(n, cptr, W, degree, elen, w, dense, nv, head, last, next); // minimum degree node
48219
48220
48221 var mindeg = 0; // vars
48222
48223 var i, j, k, k1, k2, e, pj, ln, nvi, pk, eln, p1, p2, pn, h, d; // while (selecting pivots) do
48224
48225 while (nel < n) {
48226 // select node of minimum approximate degree. amd() is now ready to start eliminating the graph. It first
48227 // finds a node k of minimum degree and removes it from its degree list. The variable nel keeps track of thow
48228 // many nodes have been eliminated.
48229 for (k = -1; mindeg < n && (k = W[head + mindeg]) === -1; mindeg++) {
48230 ;
48231 }
48232
48233 if (W[next + k] !== -1) {
48234 last[W[next + k]] = -1;
48235 } // remove k from degree list
48236
48237
48238 W[head + mindeg] = W[next + k]; // elenk = |Ek|
48239
48240 var elenk = W[elen + k]; // # of nodes k represents
48241
48242 var nvk = W[nv + k]; // W[nv + k] nodes of A eliminated
48243
48244 nel += nvk; // Construct a new element. The new element Lk is constructed in place if |Ek| = 0. nv[i] is
48245 // negated for all nodes i in Lk to flag them as members of this set. Each node i is removed from the
48246 // degree lists. All elements e in Ek are absorved into element k.
48247
48248 var dk = 0; // flag k as in Lk
48249
48250 W[nv + k] = -nvk;
48251 var p = cptr[k]; // do in place if W[elen + k] === 0
48252
48253 var pk1 = elenk === 0 ? p : cnz;
48254 var pk2 = pk1;
48255
48256 for (k1 = 1; k1 <= elenk + 1; k1++) {
48257 if (k1 > elenk) {
48258 // search the nodes in k
48259 e = k; // list of nodes starts at cindex[pj]
48260
48261 pj = p; // length of list of nodes in k
48262
48263 ln = W[len + k] - elenk;
48264 } else {
48265 // search the nodes in e
48266 e = cindex[p++];
48267 pj = cptr[e]; // length of list of nodes in e
48268
48269 ln = W[len + e];
48270 }
48271
48272 for (k2 = 1; k2 <= ln; k2++) {
48273 i = cindex[pj++]; // check node i dead, or seen
48274
48275 if ((nvi = W[nv + i]) <= 0) {
48276 continue;
48277 } // W[degree + Lk] += size of node i
48278
48279
48280 dk += nvi; // negate W[nv + i] to denote i in Lk
48281
48282 W[nv + i] = -nvi; // place i in Lk
48283
48284 cindex[pk2++] = i;
48285
48286 if (W[next + i] !== -1) {
48287 last[W[next + i]] = last[i];
48288 } // check we need to remove i from degree list
48289
48290
48291 if (last[i] !== -1) {
48292 W[next + last[i]] = W[next + i];
48293 } else {
48294 W[head + W[degree + i]] = W[next + i];
48295 }
48296 }
48297
48298 if (e !== k) {
48299 // absorb e into k
48300 cptr[e] = csFlip(k); // e is now a dead element
48301
48302 W[w + e] = 0;
48303 }
48304 } // cindex[cnz...nzmax] is free
48305
48306
48307 if (elenk !== 0) {
48308 cnz = pk2;
48309 } // external degree of k - |Lk\i|
48310
48311
48312 W[degree + k] = dk; // element k is in cindex[pk1..pk2-1]
48313
48314 cptr[k] = pk1;
48315 W[len + k] = pk2 - pk1; // k is now an element
48316
48317 W[elen + k] = -2; // Find set differences. The scan1 function now computes the set differences |Le \ Lk| for all elements e. At the start of the
48318 // scan, no entry in the w array is greater than or equal to mark.
48319 // clear w if necessary
48320
48321 mark = _wclear(mark, lemax, W, w, n); // scan 1: find |Le\Lk|
48322
48323 for (pk = pk1; pk < pk2; pk++) {
48324 i = cindex[pk]; // check if W[elen + i] empty, skip it
48325
48326 if ((eln = W[elen + i]) <= 0) {
48327 continue;
48328 } // W[nv + i] was negated
48329
48330
48331 nvi = -W[nv + i];
48332 var wnvi = mark - nvi; // scan Ei
48333
48334 for (p = cptr[i], p1 = cptr[i] + eln - 1; p <= p1; p++) {
48335 e = cindex[p];
48336
48337 if (W[w + e] >= mark) {
48338 // decrement |Le\Lk|
48339 W[w + e] -= nvi;
48340 } else if (W[w + e] !== 0) {
48341 // ensure e is a live element, 1st time e seen in scan 1
48342 W[w + e] = W[degree + e] + wnvi;
48343 }
48344 }
48345 } // degree update
48346 // The second pass computes the approximate degree di, prunes the sets Ei and Ai, and computes a hash
48347 // function h(i) for all nodes in Lk.
48348 // scan2: degree update
48349
48350
48351 for (pk = pk1; pk < pk2; pk++) {
48352 // consider node i in Lk
48353 i = cindex[pk];
48354 p1 = cptr[i];
48355 p2 = p1 + W[elen + i] - 1;
48356 pn = p1; // scan Ei
48357
48358 for (h = 0, d = 0, p = p1; p <= p2; p++) {
48359 e = cindex[p]; // check e is an unabsorbed element
48360
48361 if (W[w + e] !== 0) {
48362 // dext = |Le\Lk|
48363 var dext = W[w + e] - mark;
48364
48365 if (dext > 0) {
48366 // sum up the set differences
48367 d += dext; // keep e in Ei
48368
48369 cindex[pn++] = e; // compute the hash of node i
48370
48371 h += e;
48372 } else {
48373 // aggressive absorb. e->k
48374 cptr[e] = csFlip(k); // e is a dead element
48375
48376 W[w + e] = 0;
48377 }
48378 }
48379 } // W[elen + i] = |Ei|
48380
48381
48382 W[elen + i] = pn - p1 + 1;
48383 var p3 = pn;
48384 var p4 = p1 + W[len + i]; // prune edges in Ai
48385
48386 for (p = p2 + 1; p < p4; p++) {
48387 j = cindex[p]; // check node j dead or in Lk
48388
48389 var nvj = W[nv + j];
48390
48391 if (nvj <= 0) {
48392 continue;
48393 } // degree(i) += |j|
48394
48395
48396 d += nvj; // place j in node list of i
48397
48398 cindex[pn++] = j; // compute hash for node i
48399
48400 h += j;
48401 } // check for mass elimination
48402
48403
48404 if (d === 0) {
48405 // absorb i into k
48406 cptr[i] = csFlip(k);
48407 nvi = -W[nv + i]; // |Lk| -= |i|
48408
48409 dk -= nvi; // |k| += W[nv + i]
48410
48411 nvk += nvi;
48412 nel += nvi;
48413 W[nv + i] = 0; // node i is dead
48414
48415 W[elen + i] = -1;
48416 } else {
48417 // update degree(i)
48418 W[degree + i] = Math.min(W[degree + i], d); // move first node to end
48419
48420 cindex[pn] = cindex[p3]; // move 1st el. to end of Ei
48421
48422 cindex[p3] = cindex[p1]; // add k as 1st element in of Ei
48423
48424 cindex[p1] = k; // new len of adj. list of node i
48425
48426 W[len + i] = pn - p1 + 1; // finalize hash of i
48427
48428 h = (h < 0 ? -h : h) % n; // place i in hash bucket
48429
48430 W[next + i] = W[hhead + h];
48431 W[hhead + h] = i; // save hash of i in last[i]
48432
48433 last[i] = h;
48434 }
48435 } // finalize |Lk|
48436
48437
48438 W[degree + k] = dk;
48439 lemax = Math.max(lemax, dk); // clear w
48440
48441 mark = _wclear(mark + lemax, lemax, W, w, n); // Supernode detection. Supernode detection relies on the hash function h(i) computed for each node i.
48442 // If two nodes have identical adjacency lists, their hash functions wil be identical.
48443
48444 for (pk = pk1; pk < pk2; pk++) {
48445 i = cindex[pk]; // check i is dead, skip it
48446
48447 if (W[nv + i] >= 0) {
48448 continue;
48449 } // scan hash bucket of node i
48450
48451
48452 h = last[i];
48453 i = W[hhead + h]; // hash bucket will be empty
48454
48455 W[hhead + h] = -1;
48456
48457 for (; i !== -1 && W[next + i] !== -1; i = W[next + i], mark++) {
48458 ln = W[len + i];
48459 eln = W[elen + i];
48460
48461 for (p = cptr[i] + 1; p <= cptr[i] + ln - 1; p++) {
48462 W[w + cindex[p]] = mark;
48463 }
48464
48465 var jlast = i; // compare i with all j
48466
48467 for (j = W[next + i]; j !== -1;) {
48468 var ok = W[len + j] === ln && W[elen + j] === eln;
48469
48470 for (p = cptr[j] + 1; ok && p <= cptr[j] + ln - 1; p++) {
48471 // compare i and j
48472 if (W[w + cindex[p]] !== mark) {
48473 ok = 0;
48474 }
48475 } // check i and j are identical
48476
48477
48478 if (ok) {
48479 // absorb j into i
48480 cptr[j] = csFlip(i);
48481 W[nv + i] += W[nv + j];
48482 W[nv + j] = 0; // node j is dead
48483
48484 W[elen + j] = -1; // delete j from hash bucket
48485
48486 j = W[next + j];
48487 W[next + jlast] = j;
48488 } else {
48489 // j and i are different
48490 jlast = j;
48491 j = W[next + j];
48492 }
48493 }
48494 }
48495 } // Finalize new element. The elimination of node k is nearly complete. All nodes i in Lk are scanned one last time.
48496 // Node i is removed from Lk if it is dead. The flagged status of nv[i] is cleared.
48497
48498
48499 for (p = pk1, pk = pk1; pk < pk2; pk++) {
48500 i = cindex[pk]; // check i is dead, skip it
48501
48502 if ((nvi = -W[nv + i]) <= 0) {
48503 continue;
48504 } // restore W[nv + i]
48505
48506
48507 W[nv + i] = nvi; // compute external degree(i)
48508
48509 d = W[degree + i] + dk - nvi;
48510 d = Math.min(d, n - nel - nvi);
48511
48512 if (W[head + d] !== -1) {
48513 last[W[head + d]] = i;
48514 } // put i back in degree list
48515
48516
48517 W[next + i] = W[head + d];
48518 last[i] = -1;
48519 W[head + d] = i; // find new minimum degree
48520
48521 mindeg = Math.min(mindeg, d);
48522 W[degree + i] = d; // place i in Lk
48523
48524 cindex[p++] = i;
48525 } // # nodes absorbed into k
48526
48527
48528 W[nv + k] = nvk; // length of adj list of element k
48529
48530 if ((W[len + k] = p - pk1) === 0) {
48531 // k is a root of the tree
48532 cptr[k] = -1; // k is now a dead element
48533
48534 W[w + k] = 0;
48535 }
48536
48537 if (elenk !== 0) {
48538 // free unused space in Lk
48539 cnz = p;
48540 }
48541 } // Postordering. The elimination is complete, but no permutation has been computed. All that is left
48542 // of the graph is the assembly tree (ptr) and a set of dead nodes and elements (i is a dead node if
48543 // nv[i] is zero and a dead element if nv[i] > 0). It is from this information only that the final permutation
48544 // is computed. The tree is restored by unflipping all of ptr.
48545 // fix assembly tree
48546
48547
48548 for (i = 0; i < n; i++) {
48549 cptr[i] = csFlip(cptr[i]);
48550 }
48551
48552 for (j = 0; j <= n; j++) {
48553 W[head + j] = -1;
48554 } // place unordered nodes in lists
48555
48556
48557 for (j = n; j >= 0; j--) {
48558 // skip if j is an element
48559 if (W[nv + j] > 0) {
48560 continue;
48561 } // place j in list of its parent
48562
48563
48564 W[next + j] = W[head + cptr[j]];
48565 W[head + cptr[j]] = j;
48566 } // place elements in lists
48567
48568
48569 for (e = n; e >= 0; e--) {
48570 // skip unless e is an element
48571 if (W[nv + e] <= 0) {
48572 continue;
48573 }
48574
48575 if (cptr[e] !== -1) {
48576 // place e in list of its parent
48577 W[next + e] = W[head + cptr[e]];
48578 W[head + cptr[e]] = e;
48579 }
48580 } // postorder the assembly tree
48581
48582
48583 for (k = 0, i = 0; i <= n; i++) {
48584 if (cptr[i] === -1) {
48585 k = csTdfs(i, k, W, head, next, P, w);
48586 }
48587 } // remove last item in array
48588
48589
48590 P.splice(P.length - 1, 1); // return P
48591
48592 return P;
48593 };
48594 /**
48595 * 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
48596 * vector P. The amd algorithm operates on a symmetrix matrix, so one of three symmetric matrices is formed.
48597 *
48598 * Order: 0
48599 * A natural ordering P=null matrix is returned.
48600 *
48601 * Order: 1
48602 * Matrix must be square. This is appropriate for a Cholesky or LU factorization.
48603 * P = M + M'
48604 *
48605 * Order: 2
48606 * Dense columns from M' are dropped, M recreated from M'. This is appropriatefor LU factorization of unsymmetric matrices.
48607 * P = M' * M
48608 *
48609 * Order: 3
48610 * This is best used for QR factorization or LU factorization is matrix M has no dense rows. A dense row is a row with more than 10*sqr(columns) entries.
48611 * P = M' * M
48612 */
48613
48614 function _createTargetMatrix(order, a, m, n, dense) {
48615 // compute A'
48616 var at = transpose(a); // check order = 1, matrix must be square
48617
48618 if (order === 1 && n === m) {
48619 // C = A + A'
48620 return add(a, at);
48621 } // check order = 2, drop dense columns from M'
48622
48623
48624 if (order === 2) {
48625 // transpose arrays
48626 var tindex = at._index;
48627 var tptr = at._ptr; // new column index
48628
48629 var p2 = 0; // loop A' columns (rows)
48630
48631 for (var j = 0; j < m; j++) {
48632 // column j of AT starts here
48633 var p = tptr[j]; // new column j starts here
48634
48635 tptr[j] = p2; // skip dense col j
48636
48637 if (tptr[j + 1] - p > dense) {
48638 continue;
48639 } // map rows in column j of A
48640
48641
48642 for (var p1 = tptr[j + 1]; p < p1; p++) {
48643 tindex[p2++] = tindex[p];
48644 }
48645 } // finalize AT
48646
48647
48648 tptr[m] = p2; // recreate A from new transpose matrix
48649
48650 a = transpose(at); // use A' * A
48651
48652 return multiply(at, a);
48653 } // use A' * A, square or rectangular matrix
48654
48655
48656 return multiply(at, a);
48657 }
48658 /**
48659 * Initialize quotient graph. There are four kind of nodes and elements that must be represented:
48660 *
48661 * - 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.
48662 * - A dead node i is one that has been removed from the graph, having been absorved into r = flip(ptr[i]).
48663 * - A live element e is one that is in the graph, having been formed when node e was selected as the pivot.
48664 * - A dead element e is one that has benn absorved into a subsequent element s = flip(ptr[e]).
48665 */
48666
48667
48668 function _initializeQuotientGraph(n, cptr, W, len, head, last, next, hhead, nv, w, elen, degree) {
48669 // Initialize quotient graph
48670 for (var k = 0; k < n; k++) {
48671 W[len + k] = cptr[k + 1] - cptr[k];
48672 }
48673
48674 W[len + n] = 0; // initialize workspace
48675
48676 for (var i = 0; i <= n; i++) {
48677 // degree list i is empty
48678 W[head + i] = -1;
48679 last[i] = -1;
48680 W[next + i] = -1; // hash list i is empty
48681
48682 W[hhead + i] = -1; // node i is just one node
48683
48684 W[nv + i] = 1; // node i is alive
48685
48686 W[w + i] = 1; // Ek of node i is empty
48687
48688 W[elen + i] = 0; // degree of node i
48689
48690 W[degree + i] = W[len + i];
48691 } // clear w
48692
48693
48694 var mark = _wclear(0, 0, W, w, n); // n is a dead element
48695
48696
48697 W[elen + n] = -2; // n is a root of assembly tree
48698
48699 cptr[n] = -1; // n is a dead element
48700
48701 W[w + n] = 0; // return mark
48702
48703 return mark;
48704 }
48705 /**
48706 * Initialize degree lists. Each node is placed in its degree lists. Nodes of zero degree are eliminated immediately. Nodes with
48707 * degree >= dense are alsol eliminated and merged into a placeholder node n, a dead element. Thes nodes will appera last in the
48708 * output permutation p.
48709 */
48710
48711
48712 function _initializeDegreeLists(n, cptr, W, degree, elen, w, dense, nv, head, last, next) {
48713 // result
48714 var nel = 0; // loop columns
48715
48716 for (var i = 0; i < n; i++) {
48717 // degree @ i
48718 var d = W[degree + i]; // check node i is empty
48719
48720 if (d === 0) {
48721 // element i is dead
48722 W[elen + i] = -2;
48723 nel++; // i is a root of assembly tree
48724
48725 cptr[i] = -1;
48726 W[w + i] = 0;
48727 } else if (d > dense) {
48728 // absorb i into element n
48729 W[nv + i] = 0; // node i is dead
48730
48731 W[elen + i] = -1;
48732 nel++;
48733 cptr[i] = csFlip(n);
48734 W[nv + n]++;
48735 } else {
48736 var h = W[head + d];
48737
48738 if (h !== -1) {
48739 last[h] = i;
48740 } // put node i in degree list d
48741
48742
48743 W[next + i] = W[head + d];
48744 W[head + d] = i;
48745 }
48746 }
48747
48748 return nel;
48749 }
48750
48751 function _wclear(mark, lemax, W, w, n) {
48752 if (mark < 2 || mark + lemax < 0) {
48753 for (var k = 0; k < n; k++) {
48754 if (W[w + k] !== 0) {
48755 W[w + k] = 1;
48756 }
48757 }
48758
48759 mark = 2;
48760 } // at this point, W [0..n-1] < mark holds
48761
48762
48763 return mark;
48764 }
48765
48766 function _diag(i, j) {
48767 return i !== j;
48768 }
48769});
48770// CONCATENATED MODULE: ./src/function/algebra/sparse/csLeaf.js
48771/**
48772 * This function determines if j is a leaf of the ith row subtree.
48773 * Consider A(i,j), node j in ith row subtree and return lca(jprev,j)
48774 *
48775 * @param {Number} i The ith row subtree
48776 * @param {Number} j The node to test
48777 * @param {Array} w The workspace array
48778 * @param {Number} first The index offset within the workspace for the first array
48779 * @param {Number} maxfirst The index offset within the workspace for the maxfirst array
48780 * @param {Number} prevleaf The index offset within the workspace for the prevleaf array
48781 * @param {Number} ancestor The index offset within the workspace for the ancestor array
48782 *
48783 * @return {Object}
48784 *
48785 * Reference: http://faculty.cse.tamu.edu/davis/publications.html
48786 */
48787function csLeaf(i, j, w, first, maxfirst, prevleaf, ancestor) {
48788 var s, sparent; // our result
48789
48790 var jleaf = 0;
48791 var q; // check j is a leaf
48792
48793 if (i <= j || w[first + j] <= w[maxfirst + i]) {
48794 return -1;
48795 } // update max first[j] seen so far
48796
48797
48798 w[maxfirst + i] = w[first + j]; // jprev = previous leaf of ith subtree
48799
48800 var jprev = w[prevleaf + i];
48801 w[prevleaf + i] = j; // check j is first or subsequent leaf
48802
48803 if (jprev === -1) {
48804 // 1st leaf, q = root of ith subtree
48805 jleaf = 1;
48806 q = i;
48807 } else {
48808 // update jleaf
48809 jleaf = 2; // q = least common ancester (jprev,j)
48810
48811 for (q = jprev; q !== w[ancestor + q]; q = w[ancestor + q]) {
48812 ;
48813 }
48814
48815 for (s = jprev; s !== q; s = sparent) {
48816 // path compression
48817 sparent = w[ancestor + s];
48818 w[ancestor + s] = q;
48819 }
48820 }
48821
48822 return {
48823 jleaf: jleaf,
48824 q: q
48825 };
48826}
48827// CONCATENATED MODULE: ./src/function/algebra/sparse/csCounts.js
48828
48829
48830var csCounts_name = 'csCounts';
48831var csCounts_dependencies = ['transpose'];
48832var createCsCounts =
48833/* #__PURE__ */
48834Object(factory["a" /* factory */])(csCounts_name, csCounts_dependencies, function (_ref) {
48835 var transpose = _ref.transpose;
48836
48837 /**
48838 * Computes the column counts using the upper triangular part of A.
48839 * It transposes A internally, none of the input parameters are modified.
48840 *
48841 * @param {Matrix} a The sparse matrix A
48842 *
48843 * @param {Matrix} ata Count the columns of A'A instead
48844 *
48845 * @return An array of size n of the column counts or null on error
48846 *
48847 * Reference: http://faculty.cse.tamu.edu/davis/publications.html
48848 */
48849 return function (a, parent, post, ata) {
48850 // check inputs
48851 if (!a || !parent || !post) {
48852 return null;
48853 } // a matrix arrays
48854
48855
48856 var asize = a._size; // rows and columns
48857
48858 var m = asize[0];
48859 var n = asize[1]; // variables
48860
48861 var i, j, k, J, p, p0, p1; // workspace size
48862
48863 var s = 4 * n + (ata ? n + m + 1 : 0); // allocate workspace
48864
48865 var w = []; // (s)
48866
48867 var ancestor = 0; // first n entries
48868
48869 var maxfirst = n; // next n entries
48870
48871 var prevleaf = 2 * n; // next n entries
48872
48873 var first = 3 * n; // next n entries
48874
48875 var head = 4 * n; // next n + 1 entries (used when ata is true)
48876
48877 var next = 5 * n + 1; // last entries in workspace
48878 // clear workspace w[0..s-1]
48879
48880 for (k = 0; k < s; k++) {
48881 w[k] = -1;
48882 } // allocate result
48883
48884
48885 var colcount = []; // (n)
48886 // AT = A'
48887
48888 var at = transpose(a); // at arrays
48889
48890 var tindex = at._index;
48891 var tptr = at._ptr; // find w[first + j]
48892
48893 for (k = 0; k < n; k++) {
48894 j = post[k]; // colcount[j]=1 if j is a leaf
48895
48896 colcount[j] = w[first + j] === -1 ? 1 : 0;
48897
48898 for (; j !== -1 && w[first + j] === -1; j = parent[j]) {
48899 w[first + j] = k;
48900 }
48901 } // initialize ata if needed
48902
48903
48904 if (ata) {
48905 // invert post
48906 for (k = 0; k < n; k++) {
48907 w[post[k]] = k;
48908 } // loop rows (columns in AT)
48909
48910
48911 for (i = 0; i < m; i++) {
48912 // values in column i of AT
48913 for (k = n, p0 = tptr[i], p1 = tptr[i + 1], p = p0; p < p1; p++) {
48914 k = Math.min(k, w[tindex[p]]);
48915 } // place row i in linked list k
48916
48917
48918 w[next + i] = w[head + k];
48919 w[head + k] = i;
48920 }
48921 } // each node in its own set
48922
48923
48924 for (i = 0; i < n; i++) {
48925 w[ancestor + i] = i;
48926 }
48927
48928 for (k = 0; k < n; k++) {
48929 // j is the kth node in postordered etree
48930 j = post[k]; // check j is not a root
48931
48932 if (parent[j] !== -1) {
48933 colcount[parent[j]]--;
48934 } // J=j for LL'=A case
48935
48936
48937 for (J = ata ? w[head + k] : j; J !== -1; J = ata ? w[next + J] : -1) {
48938 for (p = tptr[J]; p < tptr[J + 1]; p++) {
48939 i = tindex[p];
48940 var r = csLeaf(i, j, w, first, maxfirst, prevleaf, ancestor); // check A(i,j) is in skeleton
48941
48942 if (r.jleaf >= 1) {
48943 colcount[j]++;
48944 } // check account for overlap in q
48945
48946
48947 if (r.jleaf === 2) {
48948 colcount[r.q]--;
48949 }
48950 }
48951 }
48952
48953 if (parent[j] !== -1) {
48954 w[ancestor + j] = parent[j];
48955 }
48956 } // sum up colcount's of each child
48957
48958
48959 for (j = 0; j < n; j++) {
48960 if (parent[j] !== -1) {
48961 colcount[parent[j]] += colcount[j];
48962 }
48963 }
48964
48965 return colcount;
48966 };
48967});
48968// CONCATENATED MODULE: ./src/function/algebra/sparse/csSqr.js
48969
48970
48971
48972
48973
48974
48975var csSqr_name = 'csSqr';
48976var csSqr_dependencies = ['add', 'multiply', 'transpose'];
48977var createCsSqr =
48978/* #__PURE__ */
48979Object(factory["a" /* factory */])(csSqr_name, csSqr_dependencies, function (_ref) {
48980 var add = _ref.add,
48981 multiply = _ref.multiply,
48982 transpose = _ref.transpose;
48983 var csAmd = createCsAmd({
48984 add: add,
48985 multiply: multiply,
48986 transpose: transpose
48987 });
48988 var csCounts = createCsCounts({
48989 transpose: transpose
48990 });
48991 /**
48992 * Symbolic ordering and analysis for QR and LU decompositions.
48993 *
48994 * @param {Number} order The ordering strategy (see csAmd for more details)
48995 * @param {Matrix} a The A matrix
48996 * @param {boolean} qr Symbolic ordering and analysis for QR decomposition (true) or
48997 * symbolic ordering and analysis for LU decomposition (false)
48998 *
48999 * @return {Object} The Symbolic ordering and analysis for matrix A
49000 *
49001 * Reference: http://faculty.cse.tamu.edu/davis/publications.html
49002 */
49003
49004 return function csSqr(order, a, qr) {
49005 // a arrays
49006 var aptr = a._ptr;
49007 var asize = a._size; // columns
49008
49009 var n = asize[1]; // vars
49010
49011 var k; // symbolic analysis result
49012
49013 var s = {}; // fill-reducing ordering
49014
49015 s.q = csAmd(order, a); // validate results
49016
49017 if (order && !s.q) {
49018 return null;
49019 } // QR symbolic analysis
49020
49021
49022 if (qr) {
49023 // apply permutations if needed
49024 var c = order ? csPermute(a, null, s.q, 0) : a; // etree of C'*C, where C=A(:,q)
49025
49026 s.parent = csEtree(c, 1); // post order elimination tree
49027
49028 var post = csPost(s.parent, n); // col counts chol(C'*C)
49029
49030 s.cp = csCounts(c, s.parent, post, 1); // check we have everything needed to calculate number of nonzero elements
49031
49032 if (c && s.parent && s.cp && _vcount(c, s)) {
49033 // calculate number of nonzero elements
49034 for (s.unz = 0, k = 0; k < n; k++) {
49035 s.unz += s.cp[k];
49036 }
49037 }
49038 } else {
49039 // for LU factorization only, guess nnz(L) and nnz(U)
49040 s.unz = 4 * aptr[n] + n;
49041 s.lnz = s.unz;
49042 } // return result S
49043
49044
49045 return s;
49046 };
49047 /**
49048 * Compute nnz(V) = s.lnz, s.pinv, s.leftmost, s.m2 from A and s.parent
49049 */
49050
49051 function _vcount(a, s) {
49052 // a arrays
49053 var aptr = a._ptr;
49054 var aindex = a._index;
49055 var asize = a._size; // rows & columns
49056
49057 var m = asize[0];
49058 var n = asize[1]; // initialize s arrays
49059
49060 s.pinv = []; // (m + n)
49061
49062 s.leftmost = []; // (m)
49063 // vars
49064
49065 var parent = s.parent;
49066 var pinv = s.pinv;
49067 var leftmost = s.leftmost; // workspace, next: first m entries, head: next n entries, tail: next n entries, nque: next n entries
49068
49069 var w = []; // (m + 3 * n)
49070
49071 var next = 0;
49072 var head = m;
49073 var tail = m + n;
49074 var nque = m + 2 * n; // vars
49075
49076 var i, k, p, p0, p1; // initialize w
49077
49078 for (k = 0; k < n; k++) {
49079 // queue k is empty
49080 w[head + k] = -1;
49081 w[tail + k] = -1;
49082 w[nque + k] = 0;
49083 } // initialize row arrays
49084
49085
49086 for (i = 0; i < m; i++) {
49087 leftmost[i] = -1;
49088 } // loop columns backwards
49089
49090
49091 for (k = n - 1; k >= 0; k--) {
49092 // values & index for column k
49093 for (p0 = aptr[k], p1 = aptr[k + 1], p = p0; p < p1; p++) {
49094 // leftmost[i] = min(find(A(i,:)))
49095 leftmost[aindex[p]] = k;
49096 }
49097 } // scan rows in reverse order
49098
49099
49100 for (i = m - 1; i >= 0; i--) {
49101 // row i is not yet ordered
49102 pinv[i] = -1;
49103 k = leftmost[i]; // check row i is empty
49104
49105 if (k === -1) {
49106 continue;
49107 } // first row in queue k
49108
49109
49110 if (w[nque + k]++ === 0) {
49111 w[tail + k] = i;
49112 } // put i at head of queue k
49113
49114
49115 w[next + i] = w[head + k];
49116 w[head + k] = i;
49117 }
49118
49119 s.lnz = 0;
49120 s.m2 = m; // find row permutation and nnz(V)
49121
49122 for (k = 0; k < n; k++) {
49123 // remove row i from queue k
49124 i = w[head + k]; // count V(k,k) as nonzero
49125
49126 s.lnz++; // add a fictitious row
49127
49128 if (i < 0) {
49129 i = s.m2++;
49130 } // associate row i with V(:,k)
49131
49132
49133 pinv[i] = k; // skip if V(k+1:m,k) is empty
49134
49135 if (--nque[k] <= 0) {
49136 continue;
49137 } // nque[k] is nnz (V(k+1:m,k))
49138
49139
49140 s.lnz += w[nque + k]; // move all rows to parent of k
49141
49142 var pa = parent[k];
49143
49144 if (pa !== -1) {
49145 if (w[nque + pa] === 0) {
49146 w[tail + pa] = w[tail + k];
49147 }
49148
49149 w[next + w[tail + k]] = w[head + pa];
49150 w[head + pa] = w[next + i];
49151 w[nque + pa] += w[nque + k];
49152 }
49153 }
49154
49155 for (i = 0; i < m; i++) {
49156 if (pinv[i] < 0) {
49157 pinv[i] = k++;
49158 }
49159 }
49160
49161 return true;
49162 }
49163});
49164// CONCATENATED MODULE: ./src/function/algebra/sparse/csMarked.js
49165/**
49166 * Checks if the node at w[j] is marked
49167 *
49168 * @param {Array} w The array
49169 * @param {Number} j The array index
49170 *
49171 * Reference: http://faculty.cse.tamu.edu/davis/publications.html
49172 */
49173function csMarked(w, j) {
49174 // check node is marked
49175 return w[j] < 0;
49176}
49177// CONCATENATED MODULE: ./src/function/algebra/sparse/csMark.js
49178
49179/**
49180 * Marks the node at w[j]
49181 *
49182 * @param {Array} w The array
49183 * @param {Number} j The array index
49184 *
49185 * Reference: http://faculty.cse.tamu.edu/davis/publications.html
49186 */
49187
49188function csMark(w, j) {
49189 // mark w[j]
49190 w[j] = csFlip(w[j]);
49191}
49192// CONCATENATED MODULE: ./src/function/algebra/sparse/csUnflip.js
49193
49194/**
49195 * Flips the value if it is negative of returns the same value otherwise.
49196 *
49197 * @param {Number} i The value to flip
49198 *
49199 * Reference: http://faculty.cse.tamu.edu/davis/publications.html
49200 */
49201
49202function csUnflip(i) {
49203 // flip the value if it is negative
49204 return i < 0 ? csFlip(i) : i;
49205}
49206// CONCATENATED MODULE: ./src/function/algebra/sparse/csDfs.js
49207
49208
49209
49210/**
49211 * Depth-first search computes the nonzero pattern xi of the directed graph G (Matrix) starting
49212 * at nodes in B (see csReach()).
49213 *
49214 * @param {Number} j The starting node for the DFS algorithm
49215 * @param {Matrix} g The G matrix to search, ptr array modified, then restored
49216 * @param {Number} top Start index in stack xi[top..n-1]
49217 * @param {Number} k The kth column in B
49218 * @param {Array} xi The nonzero pattern xi[top] .. xi[n - 1], an array of size = 2 * n
49219 * The first n entries is the nonzero pattern, the last n entries is the stack
49220 * @param {Array} pinv The inverse row permutation vector, must be null for L * x = b
49221 *
49222 * @return {Number} New value of top
49223 *
49224 * Reference: http://faculty.cse.tamu.edu/davis/publications.html
49225 */
49226
49227function csDfs(j, g, top, xi, pinv) {
49228 // g arrays
49229 var index = g._index;
49230 var ptr = g._ptr;
49231 var size = g._size; // columns
49232
49233 var n = size[1]; // vars
49234
49235 var i, p, p2; // initialize head
49236
49237 var head = 0; // initialize the recursion stack
49238
49239 xi[0] = j; // loop
49240
49241 while (head >= 0) {
49242 // get j from the top of the recursion stack
49243 j = xi[head]; // apply permutation vector
49244
49245 var jnew = pinv ? pinv[j] : j; // check node j is marked
49246
49247 if (!csMarked(ptr, j)) {
49248 // mark node j as visited
49249 csMark(ptr, j); // update stack (last n entries in xi)
49250
49251 xi[n + head] = jnew < 0 ? 0 : csUnflip(ptr[jnew]);
49252 } // node j done if no unvisited neighbors
49253
49254
49255 var done = 1; // examine all neighbors of j, stack (last n entries in xi)
49256
49257 for (p = xi[n + head], p2 = jnew < 0 ? 0 : csUnflip(ptr[jnew + 1]); p < p2; p++) {
49258 // consider neighbor node i
49259 i = index[p]; // check we have visited node i, skip it
49260
49261 if (csMarked(ptr, i)) {
49262 continue;
49263 } // pause depth-first search of node j, update stack (last n entries in xi)
49264
49265
49266 xi[n + head] = p; // start dfs at node i
49267
49268 xi[++head] = i; // node j is not done
49269
49270 done = 0; // break, to start dfs(i)
49271
49272 break;
49273 } // check depth-first search at node j is done
49274
49275
49276 if (done) {
49277 // remove j from the recursion stack
49278 head--; // and place in the output stack
49279
49280 xi[--top] = j;
49281 }
49282 }
49283
49284 return top;
49285}
49286// CONCATENATED MODULE: ./src/function/algebra/sparse/csReach.js
49287
49288
49289
49290/**
49291 * The csReach function computes X = Reach(B), where B is the nonzero pattern of the n-by-1
49292 * sparse column of vector b. The function returns the set of nodes reachable from any node in B. The
49293 * nonzero pattern xi of the solution x to the sparse linear system Lx=b is given by X=Reach(B).
49294 *
49295 * @param {Matrix} g The G matrix
49296 * @param {Matrix} b The B matrix
49297 * @param {Number} k The kth column in B
49298 * @param {Array} xi The nonzero pattern xi[top] .. xi[n - 1], an array of size = 2 * n
49299 * The first n entries is the nonzero pattern, the last n entries is the stack
49300 * @param {Array} pinv The inverse row permutation vector
49301 *
49302 * @return {Number} The index for the nonzero pattern
49303 *
49304 * Reference: http://faculty.cse.tamu.edu/davis/publications.html
49305 */
49306
49307function csReach(g, b, k, xi, pinv) {
49308 // g arrays
49309 var gptr = g._ptr;
49310 var gsize = g._size; // b arrays
49311
49312 var bindex = b._index;
49313 var bptr = b._ptr; // columns
49314
49315 var n = gsize[1]; // vars
49316
49317 var p, p0, p1; // initialize top
49318
49319 var top = n; // loop column indeces in B
49320
49321 for (p0 = bptr[k], p1 = bptr[k + 1], p = p0; p < p1; p++) {
49322 // node i
49323 var i = bindex[p]; // check node i is marked
49324
49325 if (!csMarked(gptr, i)) {
49326 // start a dfs at unmarked node i
49327 top = csDfs(i, g, top, xi, pinv);
49328 }
49329 } // loop columns from top -> n - 1
49330
49331
49332 for (p = top; p < n; p++) {
49333 // restore G
49334 csMark(gptr, xi[p]);
49335 }
49336
49337 return top;
49338}
49339// CONCATENATED MODULE: ./src/function/algebra/sparse/csSpsolve.js
49340
49341
49342var csSpsolve_name = 'csSpsolve';
49343var csSpsolve_dependencies = ['divideScalar', 'multiply', 'subtract'];
49344var createCsSpsolve =
49345/* #__PURE__ */
49346Object(factory["a" /* factory */])(csSpsolve_name, csSpsolve_dependencies, function (_ref) {
49347 var divideScalar = _ref.divideScalar,
49348 multiply = _ref.multiply,
49349 subtract = _ref.subtract;
49350
49351 /**
49352 * The function csSpsolve() computes the solution to G * x = bk, where bk is the
49353 * kth column of B. When lo is true, the function assumes G = L is lower triangular with the
49354 * diagonal entry as the first entry in each column. When lo is true, the function assumes G = U
49355 * is upper triangular with the diagonal entry as the last entry in each column.
49356 *
49357 * @param {Matrix} g The G matrix
49358 * @param {Matrix} b The B matrix
49359 * @param {Number} k The kth column in B
49360 * @param {Array} xi The nonzero pattern xi[top] .. xi[n - 1], an array of size = 2 * n
49361 * The first n entries is the nonzero pattern, the last n entries is the stack
49362 * @param {Array} x The soluton to the linear system G * x = b
49363 * @param {Array} pinv The inverse row permutation vector, must be null for L * x = b
49364 * @param {boolean} lo The lower (true) upper triangular (false) flag
49365 *
49366 * @return {Number} The index for the nonzero pattern
49367 *
49368 * Reference: http://faculty.cse.tamu.edu/davis/publications.html
49369 */
49370 return function csSpsolve(g, b, k, xi, x, pinv, lo) {
49371 // g arrays
49372 var gvalues = g._values;
49373 var gindex = g._index;
49374 var gptr = g._ptr;
49375 var gsize = g._size; // columns
49376
49377 var n = gsize[1]; // b arrays
49378
49379 var bvalues = b._values;
49380 var bindex = b._index;
49381 var bptr = b._ptr; // vars
49382
49383 var p, p0, p1, q; // xi[top..n-1] = csReach(B(:,k))
49384
49385 var top = csReach(g, b, k, xi, pinv); // clear x
49386
49387 for (p = top; p < n; p++) {
49388 x[xi[p]] = 0;
49389 } // scatter b
49390
49391
49392 for (p0 = bptr[k], p1 = bptr[k + 1], p = p0; p < p1; p++) {
49393 x[bindex[p]] = bvalues[p];
49394 } // loop columns
49395
49396
49397 for (var px = top; px < n; px++) {
49398 // x array index for px
49399 var j = xi[px]; // apply permutation vector (U x = b), j maps to column J of G
49400
49401 var J = pinv ? pinv[j] : j; // check column J is empty
49402
49403 if (J < 0) {
49404 continue;
49405 } // column value indeces in G, p0 <= p < p1
49406
49407
49408 p0 = gptr[J];
49409 p1 = gptr[J + 1]; // x(j) /= G(j,j)
49410
49411 x[j] = divideScalar(x[j], gvalues[lo ? p0 : p1 - 1]); // first entry L(j,j)
49412
49413 p = lo ? p0 + 1 : p0;
49414 q = lo ? p1 : p1 - 1; // loop
49415
49416 for (; p < q; p++) {
49417 // row
49418 var i = gindex[p]; // x(i) -= G(i,j) * x(j)
49419
49420 x[i] = subtract(x[i], multiply(gvalues[p], x[j]));
49421 }
49422 } // return top of stack
49423
49424
49425 return top;
49426 };
49427});
49428// CONCATENATED MODULE: ./src/function/algebra/sparse/csLu.js
49429
49430
49431var csLu_name = 'csLu';
49432var csLu_dependencies = ['abs', 'divideScalar', 'multiply', 'subtract', 'larger', 'largerEq', 'SparseMatrix'];
49433var createCsLu =
49434/* #__PURE__ */
49435Object(factory["a" /* factory */])(csLu_name, csLu_dependencies, function (_ref) {
49436 var abs = _ref.abs,
49437 divideScalar = _ref.divideScalar,
49438 multiply = _ref.multiply,
49439 subtract = _ref.subtract,
49440 larger = _ref.larger,
49441 largerEq = _ref.largerEq,
49442 SparseMatrix = _ref.SparseMatrix;
49443 var csSpsolve = createCsSpsolve({
49444 divideScalar: divideScalar,
49445 multiply: multiply,
49446 subtract: subtract
49447 });
49448 /**
49449 * Computes the numeric LU factorization of the sparse matrix A. Implements a Left-looking LU factorization
49450 * algorithm that computes L and U one column at a tume. At the kth step, it access columns 1 to k-1 of L
49451 * and column k of A. Given the fill-reducing column ordering q (see parameter s) computes L, U and pinv so
49452 * L * U = A(p, q), where p is the inverse of pinv.
49453 *
49454 * @param {Matrix} m The A Matrix to factorize
49455 * @param {Object} s The symbolic analysis from csSqr(). Provides the fill-reducing
49456 * column ordering q
49457 * @param {Number} tol Partial pivoting threshold (1 for partial pivoting)
49458 *
49459 * @return {Number} The numeric LU factorization of A or null
49460 *
49461 * Reference: http://faculty.cse.tamu.edu/davis/publications.html
49462 */
49463
49464 return function csLu(m, s, tol) {
49465 // validate input
49466 if (!m) {
49467 return null;
49468 } // m arrays
49469
49470
49471 var size = m._size; // columns
49472
49473 var n = size[1]; // symbolic analysis result
49474
49475 var q;
49476 var lnz = 100;
49477 var unz = 100; // update symbolic analysis parameters
49478
49479 if (s) {
49480 q = s.q;
49481 lnz = s.lnz || lnz;
49482 unz = s.unz || unz;
49483 } // L arrays
49484
49485
49486 var lvalues = []; // (lnz)
49487
49488 var lindex = []; // (lnz)
49489
49490 var lptr = []; // (n + 1)
49491 // L
49492
49493 var L = new SparseMatrix({
49494 values: lvalues,
49495 index: lindex,
49496 ptr: lptr,
49497 size: [n, n]
49498 }); // U arrays
49499
49500 var uvalues = []; // (unz)
49501
49502 var uindex = []; // (unz)
49503
49504 var uptr = []; // (n + 1)
49505 // U
49506
49507 var U = new SparseMatrix({
49508 values: uvalues,
49509 index: uindex,
49510 ptr: uptr,
49511 size: [n, n]
49512 }); // inverse of permutation vector
49513
49514 var pinv = []; // (n)
49515 // vars
49516
49517 var i, p; // allocate arrays
49518
49519 var x = []; // (n)
49520
49521 var xi = []; // (2 * n)
49522 // initialize variables
49523
49524 for (i = 0; i < n; i++) {
49525 // clear workspace
49526 x[i] = 0; // no rows pivotal yet
49527
49528 pinv[i] = -1; // no cols of L yet
49529
49530 lptr[i + 1] = 0;
49531 } // reset number of nonzero elements in L and U
49532
49533
49534 lnz = 0;
49535 unz = 0; // compute L(:,k) and U(:,k)
49536
49537 for (var k = 0; k < n; k++) {
49538 // update ptr
49539 lptr[k] = lnz;
49540 uptr[k] = unz; // apply column permutations if needed
49541
49542 var col = q ? q[k] : k; // solve triangular system, x = L\A(:,col)
49543
49544 var top = csSpsolve(L, m, col, xi, x, pinv, 1); // find pivot
49545
49546 var ipiv = -1;
49547 var a = -1; // loop xi[] from top -> n
49548
49549 for (p = top; p < n; p++) {
49550 // x[i] is nonzero
49551 i = xi[p]; // check row i is not yet pivotal
49552
49553 if (pinv[i] < 0) {
49554 // absolute value of x[i]
49555 var xabs = abs(x[i]); // check absoulte value is greater than pivot value
49556
49557 if (larger(xabs, a)) {
49558 // largest pivot candidate so far
49559 a = xabs;
49560 ipiv = i;
49561 }
49562 } else {
49563 // x(i) is the entry U(pinv[i],k)
49564 uindex[unz] = pinv[i];
49565 uvalues[unz++] = x[i];
49566 }
49567 } // validate we found a valid pivot
49568
49569
49570 if (ipiv === -1 || a <= 0) {
49571 return null;
49572 } // update actual pivot column, give preference to diagonal value
49573
49574
49575 if (pinv[col] < 0 && largerEq(abs(x[col]), multiply(a, tol))) {
49576 ipiv = col;
49577 } // the chosen pivot
49578
49579
49580 var pivot = x[ipiv]; // last entry in U(:,k) is U(k,k)
49581
49582 uindex[unz] = k;
49583 uvalues[unz++] = pivot; // ipiv is the kth pivot row
49584
49585 pinv[ipiv] = k; // first entry in L(:,k) is L(k,k) = 1
49586
49587 lindex[lnz] = ipiv;
49588 lvalues[lnz++] = 1; // L(k+1:n,k) = x / pivot
49589
49590 for (p = top; p < n; p++) {
49591 // row
49592 i = xi[p]; // check x(i) is an entry in L(:,k)
49593
49594 if (pinv[i] < 0) {
49595 // save unpermuted row in L
49596 lindex[lnz] = i; // scale pivot column
49597
49598 lvalues[lnz++] = divideScalar(x[i], pivot);
49599 } // x[0..n-1] = 0 for next k
49600
49601
49602 x[i] = 0;
49603 }
49604 } // update ptr
49605
49606
49607 lptr[n] = lnz;
49608 uptr[n] = unz; // fix row indices of L for final pinv
49609
49610 for (p = 0; p < lnz; p++) {
49611 lindex[p] = pinv[lindex[p]];
49612 } // trim arrays
49613
49614
49615 lvalues.splice(lnz, lvalues.length - lnz);
49616 lindex.splice(lnz, lindex.length - lnz);
49617 uvalues.splice(unz, uvalues.length - unz);
49618 uindex.splice(unz, uindex.length - unz); // return LU factor
49619
49620 return {
49621 L: L,
49622 U: U,
49623 pinv: pinv
49624 };
49625 };
49626});
49627// CONCATENATED MODULE: ./src/function/algebra/decomposition/slu.js
49628
49629
49630
49631
49632var slu_name = 'slu';
49633var slu_dependencies = ['typed', 'abs', 'add', 'multiply', 'transpose', 'divideScalar', 'subtract', 'larger', 'largerEq', 'SparseMatrix'];
49634var createSlu =
49635/* #__PURE__ */
49636Object(factory["a" /* factory */])(slu_name, slu_dependencies, function (_ref) {
49637 var typed = _ref.typed,
49638 abs = _ref.abs,
49639 add = _ref.add,
49640 multiply = _ref.multiply,
49641 transpose = _ref.transpose,
49642 divideScalar = _ref.divideScalar,
49643 subtract = _ref.subtract,
49644 larger = _ref.larger,
49645 largerEq = _ref.largerEq,
49646 SparseMatrix = _ref.SparseMatrix;
49647 var csSqr = createCsSqr({
49648 add: add,
49649 multiply: multiply,
49650 transpose: transpose
49651 });
49652 var csLu = createCsLu({
49653 abs: abs,
49654 divideScalar: divideScalar,
49655 multiply: multiply,
49656 subtract: subtract,
49657 larger: larger,
49658 largerEq: largerEq,
49659 SparseMatrix: SparseMatrix
49660 });
49661 /**
49662 * Calculate the Sparse Matrix LU decomposition with full pivoting. Sparse Matrix `A` is decomposed in two matrices (`L`, `U`) and two permutation vectors (`pinv`, `q`) where
49663 *
49664 * `P * A * Q = L * U`
49665 *
49666 * Syntax:
49667 *
49668 * math.slu(A, order, threshold)
49669 *
49670 * Examples:
49671 *
49672 * const A = math.sparse([[4,3], [6, 3]])
49673 * math.slu(A, 1, 0.001)
49674 * // returns:
49675 * // {
49676 * // L: [[1, 0], [1.5, 1]]
49677 * // U: [[4, 3], [0, -1.5]]
49678 * // p: [0, 1]
49679 * // q: [0, 1]
49680 * // }
49681 *
49682 * See also:
49683 *
49684 * lup, lsolve, usolve, lusolve
49685 *
49686 * @param {SparseMatrix} A A two dimensional sparse matrix for which to get the LU decomposition.
49687 * @param {Number} order The Symbolic Ordering and Analysis order:
49688 * 0 - Natural ordering, no permutation vector q is returned
49689 * 1 - Matrix must be square, symbolic ordering and analisis is performed on M = A + A'
49690 * 2 - Symbolic ordering and analisis is performed on M = A' * A. Dense columns from A' are dropped, A recreated from A'.
49691 * This is appropriatefor LU factorization of unsymmetric matrices.
49692 * 3 - Symbolic ordering and analisis is performed on M = A' * A. This is best used for LU factorization is matrix M has no dense rows.
49693 * A dense row is a row with more than 10*sqr(columns) entries.
49694 * @param {Number} threshold Partial pivoting threshold (1 for partial pivoting)
49695 *
49696 * @return {Object} The lower triangular matrix, the upper triangular matrix and the permutation vectors.
49697 */
49698
49699 return typed(slu_name, {
49700 'SparseMatrix, number, number': function SparseMatrixNumberNumber(a, order, threshold) {
49701 // verify order
49702 if (!Object(utils_number["i" /* isInteger */])(order) || order < 0 || order > 3) {
49703 throw new Error('Symbolic Ordering and Analysis order must be an integer number in the interval [0, 3]');
49704 } // verify threshold
49705
49706
49707 if (threshold < 0 || threshold > 1) {
49708 throw new Error('Partial pivoting threshold must be a number from 0 to 1');
49709 } // perform symbolic ordering and analysis
49710
49711
49712 var s = csSqr(order, a, false); // perform lu decomposition
49713
49714 var f = csLu(a, s, threshold); // return decomposition
49715
49716 return {
49717 L: f.L,
49718 U: f.U,
49719 p: f.pinv,
49720 q: s.q,
49721 toString: function toString() {
49722 return 'L: ' + this.L.toString() + '\nU: ' + this.U.toString() + '\np: ' + this.p.toString() + (this.q ? '\nq: ' + this.q.toString() : '') + '\n';
49723 }
49724 };
49725 }
49726 });
49727});
49728// CONCATENATED MODULE: ./src/function/algebra/sparse/csIpvec.js
49729/**
49730 * Permutes a vector; x = P'b. In MATLAB notation, x(p)=b.
49731 *
49732 * @param {Array} p The permutation vector of length n. null value denotes identity
49733 * @param {Array} b The input vector
49734 *
49735 * @return {Array} The output vector x = P'b
49736 */
49737function csIpvec(p, b) {
49738 // vars
49739 var k;
49740 var n = b.length;
49741 var x = []; // check permutation vector was provided, p = null denotes identity
49742
49743 if (p) {
49744 // loop vector
49745 for (k = 0; k < n; k++) {
49746 // apply permutation
49747 x[p[k]] = b[k];
49748 }
49749 } else {
49750 // loop vector
49751 for (k = 0; k < n; k++) {
49752 // x[i] = b[i]
49753 x[k] = b[k];
49754 }
49755 }
49756
49757 return x;
49758}
49759// CONCATENATED MODULE: ./src/function/algebra/solver/lusolve.js
49760
49761
49762
49763
49764var lusolve_name = 'lusolve';
49765var lusolve_dependencies = ['typed', 'matrix', 'lup', 'slu', 'usolve', 'lsolve', 'DenseMatrix'];
49766var createLusolve =
49767/* #__PURE__ */
49768Object(factory["a" /* factory */])(lusolve_name, lusolve_dependencies, function (_ref) {
49769 var typed = _ref.typed,
49770 matrix = _ref.matrix,
49771 lup = _ref.lup,
49772 slu = _ref.slu,
49773 usolve = _ref.usolve,
49774 lsolve = _ref.lsolve,
49775 DenseMatrix = _ref.DenseMatrix;
49776 var solveValidation = createSolveValidation({
49777 DenseMatrix: DenseMatrix
49778 });
49779 /**
49780 * Solves the linear system `A * x = b` where `A` is an [n x n] matrix and `b` is a [n] column vector.
49781 *
49782 * Syntax:
49783 *
49784 * math.lusolve(A, b) // returns column vector with the solution to the linear system A * x = b
49785 * math.lusolve(lup, b) // returns column vector with the solution to the linear system A * x = b, lup = math.lup(A)
49786 *
49787 * Examples:
49788 *
49789 * const m = [[1, 0, 0, 0], [0, 2, 0, 0], [0, 0, 3, 0], [0, 0, 0, 4]]
49790 *
49791 * const x = math.lusolve(m, [-1, -1, -1, -1]) // x = [[-1], [-0.5], [-1/3], [-0.25]]
49792 *
49793 * const f = math.lup(m)
49794 * const x1 = math.lusolve(f, [-1, -1, -1, -1]) // x1 = [[-1], [-0.5], [-1/3], [-0.25]]
49795 * const x2 = math.lusolve(f, [1, 2, 1, -1]) // x2 = [[1], [1], [1/3], [-0.25]]
49796 *
49797 * const a = [[-2, 3], [2, 1]]
49798 * const b = [11, 9]
49799 * const x = math.lusolve(a, b) // [[2], [5]]
49800 *
49801 * See also:
49802 *
49803 * lup, slu, lsolve, usolve
49804 *
49805 * @param {Matrix | Array | Object} A Invertible Matrix or the Matrix LU decomposition
49806 * @param {Matrix | Array} b Column Vector
49807 * @param {number} [order] The Symbolic Ordering and Analysis order, see slu for details. Matrix must be a SparseMatrix
49808 * @param {Number} [threshold] Partial pivoting threshold (1 for partial pivoting), see slu for details. Matrix must be a SparseMatrix.
49809 *
49810 * @return {DenseMatrix | Array} Column vector with the solution to the linear system A * x = b
49811 */
49812
49813 return typed(lusolve_name, {
49814 'Array, Array | Matrix': function ArrayArrayMatrix(a, b) {
49815 // convert a to matrix
49816 a = matrix(a); // matrix lup decomposition
49817
49818 var d = lup(a); // solve
49819
49820 var x = _lusolve(d.L, d.U, d.p, null, b); // convert result to array
49821
49822
49823 return x.valueOf();
49824 },
49825 'DenseMatrix, Array | Matrix': function DenseMatrixArrayMatrix(a, b) {
49826 // matrix lup decomposition
49827 var d = lup(a); // solve
49828
49829 return _lusolve(d.L, d.U, d.p, null, b);
49830 },
49831 'SparseMatrix, Array | Matrix': function SparseMatrixArrayMatrix(a, b) {
49832 // matrix lup decomposition
49833 var d = lup(a); // solve
49834
49835 return _lusolve(d.L, d.U, d.p, null, b);
49836 },
49837 'SparseMatrix, Array | Matrix, number, number': function SparseMatrixArrayMatrixNumberNumber(a, b, order, threshold) {
49838 // matrix lu decomposition
49839 var d = slu(a, order, threshold); // solve
49840
49841 return _lusolve(d.L, d.U, d.p, d.q, b);
49842 },
49843 'Object, Array | Matrix': function ObjectArrayMatrix(d, b) {
49844 // solve
49845 return _lusolve(d.L, d.U, d.p, d.q, b);
49846 }
49847 });
49848
49849 function _toMatrix(a) {
49850 // check it is a matrix
49851 if (Object(is["v" /* isMatrix */])(a)) {
49852 return a;
49853 } // check array
49854
49855
49856 if (Object(is["b" /* isArray */])(a)) {
49857 return matrix(a);
49858 } // throw
49859
49860
49861 throw new TypeError('Invalid Matrix LU decomposition');
49862 }
49863
49864 function _lusolve(l, u, p, q, b) {
49865 // verify L, U, P
49866 l = _toMatrix(l);
49867 u = _toMatrix(u); // validate matrix and vector
49868
49869 b = solveValidation(l, b, false); // apply row permutations if needed (b is a DenseMatrix)
49870
49871 if (p) {
49872 b._data = csIpvec(p, b._data);
49873 } // use forward substitution to resolve L * y = b
49874
49875
49876 var y = lsolve(l, b); // use backward substitution to resolve U * x = y
49877
49878 var x = usolve(u, y); // apply column permutations if needed (x is a DenseMatrix)
49879
49880 if (q) {
49881 x._data = csIpvec(q, x._data);
49882 } // return solution
49883
49884
49885 return x;
49886 }
49887});
49888// CONCATENATED MODULE: ./src/expression/Help.js
49889
49890
49891
49892
49893var Help_name = 'Help';
49894var Help_dependencies = ['parse'];
49895var createHelpClass =
49896/* #__PURE__ */
49897Object(factory["a" /* factory */])(Help_name, Help_dependencies, function (_ref) {
49898 var parse = _ref.parse;
49899
49900 /**
49901 * Documentation object
49902 * @param {Object} doc Object containing properties:
49903 * {string} name
49904 * {string} category
49905 * {string} description
49906 * {string[]} syntax
49907 * {string[]} examples
49908 * {string[]} seealso
49909 * @constructor
49910 */
49911 function Help(doc) {
49912 if (!(this instanceof Help)) {
49913 throw new SyntaxError('Constructor must be called with the new operator');
49914 }
49915
49916 if (!doc) throw new Error('Argument "doc" missing');
49917 this.doc = doc;
49918 }
49919 /**
49920 * Attach type information
49921 */
49922
49923
49924 Help.prototype.type = 'Help';
49925 Help.prototype.isHelp = true;
49926 /**
49927 * Generate a string representation of the Help object
49928 * @return {string} Returns a string
49929 * @private
49930 */
49931
49932 Help.prototype.toString = function () {
49933 var doc = this.doc || {};
49934 var desc = '\n';
49935
49936 if (doc.name) {
49937 desc += 'Name: ' + doc.name + '\n\n';
49938 }
49939
49940 if (doc.category) {
49941 desc += 'Category: ' + doc.category + '\n\n';
49942 }
49943
49944 if (doc.description) {
49945 desc += 'Description:\n ' + doc.description + '\n\n';
49946 }
49947
49948 if (doc.syntax) {
49949 desc += 'Syntax:\n ' + doc.syntax.join('\n ') + '\n\n';
49950 }
49951
49952 if (doc.examples) {
49953 desc += 'Examples:\n';
49954 var scope = {};
49955
49956 for (var i = 0; i < doc.examples.length; i++) {
49957 var expr = doc.examples[i];
49958 desc += ' ' + expr + '\n';
49959 var res = void 0;
49960
49961 try {
49962 // note: res can be undefined when `expr` is an empty string
49963 res = parse(expr).compile().evaluate(scope);
49964 } catch (e) {
49965 res = e;
49966 }
49967
49968 if (res !== undefined && !Object(is["s" /* isHelp */])(res)) {
49969 desc += ' ' + Object(utils_string["d" /* format */])(res, {
49970 precision: 14
49971 }) + '\n';
49972 }
49973 }
49974
49975 desc += '\n';
49976 }
49977
49978 if (doc.seealso && doc.seealso.length) {
49979 desc += 'See also: ' + doc.seealso.join(', ') + '\n';
49980 }
49981
49982 return desc;
49983 };
49984 /**
49985 * Export the help object to JSON
49986 */
49987
49988
49989 Help.prototype.toJSON = function () {
49990 var obj = Object(utils_object["a" /* clone */])(this.doc);
49991 obj.mathjs = 'Help';
49992 return obj;
49993 };
49994 /**
49995 * Instantiate a Help object from a JSON object
49996 * @param {Object} json
49997 * @returns {Help} Returns a new Help object
49998 */
49999
50000
50001 Help.fromJSON = function (json) {
50002 var doc = {};
50003
50004 for (var prop in json) {
50005 if (prop !== 'mathjs') {
50006 // ignore mathjs field
50007 doc[prop] = json[prop];
50008 }
50009 }
50010
50011 return new Help(doc);
50012 };
50013 /**
50014 * Returns a string representation of the Help object
50015 */
50016
50017
50018 Help.prototype.valueOf = Help.prototype.toString;
50019 return Help;
50020}, {
50021 isClass: true
50022});
50023// CONCATENATED MODULE: ./src/type/chain/Chain.js
50024
50025
50026
50027
50028var Chain_name = 'Chain';
50029var Chain_dependencies = ['?on', 'math'];
50030var createChainClass =
50031/* #__PURE__ */
50032Object(factory["a" /* factory */])(Chain_name, Chain_dependencies, function (_ref) {
50033 var on = _ref.on,
50034 math = _ref.math;
50035
50036 /**
50037 * @constructor Chain
50038 * Wrap any value in a chain, allowing to perform chained operations on
50039 * the value.
50040 *
50041 * All methods available in the math.js library can be called upon the chain,
50042 * and then will be evaluated with the value itself as first argument.
50043 * The chain can be closed by executing chain.done(), which will return
50044 * the final value.
50045 *
50046 * The Chain has a number of special functions:
50047 * - done() Finalize the chained operation and return the
50048 * chain's value.
50049 * - valueOf() The same as done()
50050 * - toString() Returns a string representation of the chain's value.
50051 *
50052 * @param {*} [value]
50053 */
50054 function Chain(value) {
50055 if (!(this instanceof Chain)) {
50056 throw new SyntaxError('Constructor must be called with the new operator');
50057 }
50058
50059 if (Object(is["h" /* isChain */])(value)) {
50060 this.value = value.value;
50061 } else {
50062 this.value = value;
50063 }
50064 }
50065 /**
50066 * Attach type information
50067 */
50068
50069
50070 Chain.prototype.type = 'Chain';
50071 Chain.prototype.isChain = true;
50072 /**
50073 * Close the chain. Returns the final value.
50074 * Does the same as method valueOf()
50075 * @returns {*} value
50076 */
50077
50078 Chain.prototype.done = function () {
50079 return this.value;
50080 };
50081 /**
50082 * Close the chain. Returns the final value.
50083 * Does the same as method done()
50084 * @returns {*} value
50085 */
50086
50087
50088 Chain.prototype.valueOf = function () {
50089 return this.value;
50090 };
50091 /**
50092 * Get a string representation of the value in the chain
50093 * @returns {string}
50094 */
50095
50096
50097 Chain.prototype.toString = function () {
50098 return Object(utils_string["d" /* format */])(this.value);
50099 };
50100 /**
50101 * Get a JSON representation of the chain
50102 * @returns {Object}
50103 */
50104
50105
50106 Chain.prototype.toJSON = function () {
50107 return {
50108 mathjs: 'Chain',
50109 value: this.value
50110 };
50111 };
50112 /**
50113 * Instantiate a Chain from its JSON representation
50114 * @param {Object} json An object structured like
50115 * `{"mathjs": "Chain", value: ...}`,
50116 * where mathjs is optional
50117 * @returns {Chain}
50118 */
50119
50120
50121 Chain.fromJSON = function (json) {
50122 return new Chain(json.value);
50123 };
50124 /**
50125 * Create a proxy method for the chain
50126 * @param {string} name
50127 * @param {Function} fn The function to be proxied
50128 * If fn is no function, it is silently ignored.
50129 * @private
50130 */
50131
50132
50133 function createProxy(name, fn) {
50134 if (typeof fn === 'function') {
50135 Chain.prototype[name] = chainify(fn);
50136 }
50137 }
50138 /**
50139 * Create a proxy method for the chain
50140 * @param {string} name
50141 * @param {function} resolver The function resolving with the
50142 * function to be proxied
50143 * @private
50144 */
50145
50146
50147 function createLazyProxy(name, resolver) {
50148 Object(utils_object["h" /* lazy */])(Chain.prototype, name, function outerResolver() {
50149 var fn = resolver();
50150
50151 if (typeof fn === 'function') {
50152 return chainify(fn);
50153 }
50154
50155 return undefined; // if not a function, ignore
50156 });
50157 }
50158 /**
50159 * Make a function chainable
50160 * @param {function} fn
50161 * @return {Function} chain function
50162 * @private
50163 */
50164
50165
50166 function chainify(fn) {
50167 return function () {
50168 var args = [this.value]; // `this` will be the context of a Chain instance
50169
50170 for (var i = 0; i < arguments.length; i++) {
50171 args[i + 1] = arguments[i];
50172 }
50173
50174 return new Chain(fn.apply(fn, args));
50175 };
50176 }
50177 /**
50178 * Create a proxy for a single method, or an object with multiple methods.
50179 * Example usage:
50180 *
50181 * Chain.createProxy('add', function add (x, y) {...})
50182 * Chain.createProxy({
50183 * add: function add (x, y) {...},
50184 * subtract: function subtract (x, y) {...}
50185 * }
50186 *
50187 * @param {string | Object} arg0 A name (string), or an object with
50188 * functions
50189 * @param {*} [arg1] A function, when arg0 is a name
50190 */
50191
50192
50193 Chain.createProxy = function (arg0, arg1) {
50194 if (typeof arg0 === 'string') {
50195 // createProxy(name, value)
50196 createProxy(arg0, arg1);
50197 } else {
50198 var _loop = function _loop(_name) {
50199 if (Object(utils_object["f" /* hasOwnProperty */])(arg0, _name) && excludedNames[_name] === undefined) {
50200 createLazyProxy(_name, function () {
50201 return arg0[_name];
50202 });
50203 }
50204 };
50205
50206 // createProxy(values)
50207 for (var _name in arg0) {
50208 _loop(_name);
50209 }
50210 }
50211 };
50212
50213 var excludedNames = {
50214 expression: true,
50215 docs: true,
50216 type: true,
50217 classes: true,
50218 json: true,
50219 error: true,
50220 isChain: true // conflicts with the property isChain of a Chain instance
50221
50222 }; // create proxy for everything that is in math.js
50223
50224 Chain.createProxy(math); // register on the import event, automatically add a proxy for every imported function.
50225
50226 if (on) {
50227 on('import', function (name, resolver, path) {
50228 if (!path) {
50229 // an imported function (not a data type or something special)
50230 createLazyProxy(name, resolver);
50231 }
50232 });
50233 }
50234
50235 return Chain;
50236}, {
50237 isClass: true
50238});
50239// CONCATENATED MODULE: ./src/expression/embeddedDocs/construction/bignumber.js
50240var bignumberDocs = {
50241 name: 'bignumber',
50242 category: 'Construction',
50243 syntax: ['bignumber(x)'],
50244 description: 'Create a big number from a number or string.',
50245 examples: ['0.1 + 0.2', 'bignumber(0.1) + bignumber(0.2)', 'bignumber("7.2")', 'bignumber("7.2e500")', 'bignumber([0.1, 0.2, 0.3])'],
50246 seealso: ['boolean', 'complex', 'fraction', 'index', 'matrix', 'string', 'unit']
50247};
50248// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/utils/typeOf.js
50249var typeOfDocs = {
50250 name: 'typeOf',
50251 category: 'Utils',
50252 syntax: ['typeOf(x)'],
50253 description: 'Get the type of a variable.',
50254 examples: ['typeOf(3.5)', 'typeOf(2 - 4i)', 'typeOf(45 deg)', 'typeOf("hello world")'],
50255 seealso: ['getMatrixDataType']
50256};
50257// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/utils/isZero.js
50258var isZeroDocs = {
50259 name: 'isZero',
50260 category: 'Utils',
50261 syntax: ['isZero(x)'],
50262 description: 'Test whether a value is zero.',
50263 examples: ['isZero(2)', 'isZero(0)', 'isZero(-4)', 'isZero([3, 0, -2, 0])'],
50264 seealso: ['isInteger', 'isNumeric', 'isNegative', 'isPositive']
50265};
50266// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/utils/isPrime.js
50267var isPrimeDocs = {
50268 name: 'isPrime',
50269 category: 'Utils',
50270 syntax: ['isPrime(x)'],
50271 description: 'Test whether a value is prime: has no divisors other than itself and one.',
50272 examples: ['isPrime(3)', 'isPrime(-2)', 'isPrime([2, 17, 100])'],
50273 seealso: ['isInteger', 'isNumeric', 'isNegative', 'isZero']
50274};
50275// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/utils/isPositive.js
50276var isPositiveDocs = {
50277 name: 'isPositive',
50278 category: 'Utils',
50279 syntax: ['isPositive(x)'],
50280 description: 'Test whether a value is positive: larger than zero.',
50281 examples: ['isPositive(2)', 'isPositive(0)', 'isPositive(-4)', 'isPositive([3, 0.5, -2])'],
50282 seealso: ['isInteger', 'isNumeric', 'isNegative', 'isZero']
50283};
50284// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/utils/isNumeric.js
50285var isNumericDocs = {
50286 name: 'isNumeric',
50287 category: 'Utils',
50288 syntax: ['isNumeric(x)'],
50289 description: 'Test whether a value is a numeric value. ' + 'Returns true when the input is a number, BigNumber, Fraction, or boolean.',
50290 examples: ['isNumeric(2)', 'isNumeric("2")', 'hasNumericValue("2")', 'isNumeric(0)', 'isNumeric(bignumber(500))', 'isNumeric(fraction(0.125))', 'isNumeric(2 + 3i)', 'isNumeric([2.3, "foo", false])'],
50291 seealso: ['isInteger', 'isZero', 'isNegative', 'isPositive', 'isNaN', 'hasNumericValue']
50292};
50293// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/utils/hasNumericValue.js
50294var hasNumericValueDocs = {
50295 name: 'hasNumericValue',
50296 category: 'Utils',
50297 syntax: ['hasNumericValue(x)'],
50298 description: 'Test whether a value is an numeric value. ' + 'In case of a string, true is returned if the string contains a numeric value.',
50299 examples: ['hasNumericValue(2)', 'hasNumericValue("2")', 'isNumeric("2")', 'hasNumericValue(0)', 'hasNumericValue(bignumber(500))', 'hasNumericValue(fraction(0.125))', 'hasNumericValue(2 + 3i)', 'hasNumericValue([2.3, "foo", false])'],
50300 seealso: ['isInteger', 'isZero', 'isNegative', 'isPositive', 'isNaN', 'isNumeric']
50301};
50302// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/utils/isNegative.js
50303var isNegativeDocs = {
50304 name: 'isNegative',
50305 category: 'Utils',
50306 syntax: ['isNegative(x)'],
50307 description: 'Test whether a value is negative: smaller than zero.',
50308 examples: ['isNegative(2)', 'isNegative(0)', 'isNegative(-4)', 'isNegative([3, 0.5, -2])'],
50309 seealso: ['isInteger', 'isNumeric', 'isPositive', 'isZero']
50310};
50311// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/utils/isInteger.js
50312var isIntegerDocs = {
50313 name: 'isInteger',
50314 category: 'Utils',
50315 syntax: ['isInteger(x)'],
50316 description: 'Test whether a value is an integer number.',
50317 examples: ['isInteger(2)', 'isInteger(3.5)', 'isInteger([3, 0.5, -2])'],
50318 seealso: ['isNegative', 'isNumeric', 'isPositive', 'isZero']
50319};
50320// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/utils/isNaN.js
50321var isNaNDocs = {
50322 name: 'isNaN',
50323 category: 'Utils',
50324 syntax: ['isNaN(x)'],
50325 description: 'Test whether a value is NaN (not a number)',
50326 examples: ['isNaN(2)', 'isNaN(0 / 0)', 'isNaN(NaN)', 'isNaN(Infinity)'],
50327 seealso: ['isNegative', 'isNumeric', 'isPositive', 'isZero']
50328};
50329// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/utils/format.js
50330var formatDocs = {
50331 name: 'format',
50332 category: 'Utils',
50333 syntax: ['format(value)', 'format(value, precision)'],
50334 description: 'Format a value of any type as string.',
50335 examples: ['format(2.3)', 'format(3 - 4i)', 'format([])', 'format(pi, 3)'],
50336 seealso: ['print']
50337};
50338// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/utils/clone.js
50339var cloneDocs = {
50340 name: 'clone',
50341 category: 'Utils',
50342 syntax: ['clone(x)'],
50343 description: 'Clone a variable. Creates a copy of primitive variables,and a deep copy of matrices',
50344 examples: ['clone(3.5)', 'clone(2 - 4i)', 'clone(45 deg)', 'clone([1, 2; 3, 4])', 'clone("hello world")'],
50345 seealso: []
50346};
50347// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/units/to.js
50348var toDocs = {
50349 name: 'to',
50350 category: 'Units',
50351 syntax: ['x to unit', 'to(x, unit)'],
50352 description: 'Change the unit of a value.',
50353 examples: ['5 inch to cm', '3.2kg to g', '16 bytes in bits'],
50354 seealso: []
50355};
50356// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/trigonometry/tanh.js
50357var tanhDocs = {
50358 name: 'tanh',
50359 category: 'Trigonometry',
50360 syntax: ['tanh(x)'],
50361 description: 'Compute the hyperbolic tangent of x in radians.',
50362 examples: ['tanh(0.5)', 'sinh(0.5) / cosh(0.5)'],
50363 seealso: ['sinh', 'cosh']
50364};
50365// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/trigonometry/tan.js
50366var tanDocs = {
50367 name: 'tan',
50368 category: 'Trigonometry',
50369 syntax: ['tan(x)'],
50370 description: 'Compute the tangent of x in radians.',
50371 examples: ['tan(0.5)', 'sin(0.5) / cos(0.5)', 'tan(pi / 4)', 'tan(45 deg)'],
50372 seealso: ['atan', 'sin', 'cos']
50373};
50374// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/trigonometry/sinh.js
50375var sinhDocs = {
50376 name: 'sinh',
50377 category: 'Trigonometry',
50378 syntax: ['sinh(x)'],
50379 description: 'Compute the hyperbolic sine of x in radians.',
50380 examples: ['sinh(0.5)'],
50381 seealso: ['cosh', 'tanh']
50382};
50383// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/trigonometry/sech.js
50384var sechDocs = {
50385 name: 'sech',
50386 category: 'Trigonometry',
50387 syntax: ['sech(x)'],
50388 description: 'Compute the hyperbolic secant of x in radians. Defined as 1/cosh(x)',
50389 examples: ['sech(2)', '1 / cosh(2)'],
50390 seealso: ['coth', 'csch', 'cosh']
50391};
50392// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/trigonometry/sec.js
50393var secDocs = {
50394 name: 'sec',
50395 category: 'Trigonometry',
50396 syntax: ['sec(x)'],
50397 description: 'Compute the secant of x in radians. Defined as 1/cos(x)',
50398 examples: ['sec(2)', '1 / cos(2)'],
50399 seealso: ['cot', 'csc', 'cos']
50400};
50401// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/trigonometry/csch.js
50402var cschDocs = {
50403 name: 'csch',
50404 category: 'Trigonometry',
50405 syntax: ['csch(x)'],
50406 description: 'Compute the hyperbolic cosecant of x in radians. Defined as 1/sinh(x)',
50407 examples: ['csch(2)', '1 / sinh(2)'],
50408 seealso: ['sech', 'coth', 'sinh']
50409};
50410// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/trigonometry/csc.js
50411var cscDocs = {
50412 name: 'csc',
50413 category: 'Trigonometry',
50414 syntax: ['csc(x)'],
50415 description: 'Compute the cosecant of x in radians. Defined as 1/sin(x)',
50416 examples: ['csc(2)', '1 / sin(2)'],
50417 seealso: ['sec', 'cot', 'sin']
50418};
50419// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/trigonometry/coth.js
50420var cothDocs = {
50421 name: 'coth',
50422 category: 'Trigonometry',
50423 syntax: ['coth(x)'],
50424 description: 'Compute the hyperbolic cotangent of x in radians.',
50425 examples: ['coth(2)', '1 / tanh(2)'],
50426 seealso: ['sech', 'csch', 'tanh']
50427};
50428// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/trigonometry/cot.js
50429var cotDocs = {
50430 name: 'cot',
50431 category: 'Trigonometry',
50432 syntax: ['cot(x)'],
50433 description: 'Compute the cotangent of x in radians. Defined as 1/tan(x)',
50434 examples: ['cot(2)', '1 / tan(2)'],
50435 seealso: ['sec', 'csc', 'tan']
50436};
50437// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/trigonometry/cosh.js
50438var coshDocs = {
50439 name: 'cosh',
50440 category: 'Trigonometry',
50441 syntax: ['cosh(x)'],
50442 description: 'Compute the hyperbolic cosine of x in radians.',
50443 examples: ['cosh(0.5)'],
50444 seealso: ['sinh', 'tanh', 'coth']
50445};
50446// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/trigonometry/cos.js
50447var cosDocs = {
50448 name: 'cos',
50449 category: 'Trigonometry',
50450 syntax: ['cos(x)'],
50451 description: 'Compute the cosine of x in radians.',
50452 examples: ['cos(2)', 'cos(pi / 4) ^ 2', 'cos(180 deg)', 'cos(60 deg)', 'sin(0.2)^2 + cos(0.2)^2'],
50453 seealso: ['acos', 'sin', 'tan']
50454};
50455// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/trigonometry/atan2.js
50456var atan2Docs = {
50457 name: 'atan2',
50458 category: 'Trigonometry',
50459 syntax: ['atan2(y, x)'],
50460 description: 'Computes the principal value of the arc tangent of y/x in radians.',
50461 examples: ['atan2(2, 2) / pi', 'angle = 60 deg in rad', 'x = cos(angle)', 'y = sin(angle)', 'atan2(y, x)'],
50462 seealso: ['sin', 'cos', 'tan']
50463};
50464// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/trigonometry/atanh.js
50465var atanhDocs = {
50466 name: 'atanh',
50467 category: 'Trigonometry',
50468 syntax: ['atanh(x)'],
50469 description: 'Calculate the hyperbolic arctangent of a value, defined as `atanh(x) = ln((1 + x)/(1 - x)) / 2`.',
50470 examples: ['atanh(0.5)'],
50471 seealso: ['acosh', 'asinh']
50472};
50473// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/trigonometry/atan.js
50474var atanDocs = {
50475 name: 'atan',
50476 category: 'Trigonometry',
50477 syntax: ['atan(x)'],
50478 description: 'Compute the inverse tangent of a value in radians.',
50479 examples: ['atan(0.5)', 'atan(tan(0.5))'],
50480 seealso: ['tan', 'acos', 'asin']
50481};
50482// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/trigonometry/asinh.js
50483var asinhDocs = {
50484 name: 'asinh',
50485 category: 'Trigonometry',
50486 syntax: ['asinh(x)'],
50487 description: 'Calculate the hyperbolic arcsine of a value, defined as `asinh(x) = ln(x + sqrt(x^2 + 1))`.',
50488 examples: ['asinh(0.5)'],
50489 seealso: ['acosh', 'atanh']
50490};
50491// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/trigonometry/asin.js
50492var asinDocs = {
50493 name: 'asin',
50494 category: 'Trigonometry',
50495 syntax: ['asin(x)'],
50496 description: 'Compute the inverse sine of a value in radians.',
50497 examples: ['asin(0.5)', 'asin(sin(0.5))'],
50498 seealso: ['sin', 'acos', 'atan']
50499};
50500// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/trigonometry/asech.js
50501var asechDocs = {
50502 name: 'asech',
50503 category: 'Trigonometry',
50504 syntax: ['asech(x)'],
50505 description: 'Calculate the inverse secant of a value.',
50506 examples: ['asech(0.5)'],
50507 seealso: ['acsch', 'acoth']
50508};
50509// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/trigonometry/asec.js
50510var asecDocs = {
50511 name: 'asec',
50512 category: 'Trigonometry',
50513 syntax: ['asec(x)'],
50514 description: 'Calculate the inverse secant of a value.',
50515 examples: ['asec(0.5)', 'asec(sec(0.5))', 'asec(2)'],
50516 seealso: ['acos', 'acot', 'acsc']
50517};
50518// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/trigonometry/acsch.js
50519var acschDocs = {
50520 name: 'acsch',
50521 category: 'Trigonometry',
50522 syntax: ['acsch(x)'],
50523 description: 'Calculate the hyperbolic arccosecant of a value, defined as `acsch(x) = ln(1/x + sqrt(1/x^2 + 1))`.',
50524 examples: ['acsch(0.5)'],
50525 seealso: ['asech', 'acoth']
50526};
50527// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/trigonometry/acsc.js
50528var acscDocs = {
50529 name: 'acsc',
50530 category: 'Trigonometry',
50531 syntax: ['acsc(x)'],
50532 description: 'Calculate the inverse cotangent of a value.',
50533 examples: ['acsc(2)', 'acsc(csc(0.5))', 'acsc(0.5)'],
50534 seealso: ['csc', 'asin', 'asec']
50535};
50536// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/trigonometry/acoth.js
50537var acothDocs = {
50538 name: 'acoth',
50539 category: 'Trigonometry',
50540 syntax: ['acoth(x)'],
50541 description: 'Calculate the hyperbolic arccotangent of a value, defined as `acoth(x) = (ln((x+1)/x) + ln(x/(x-1))) / 2`.',
50542 examples: ['acoth(2)', 'acoth(0.5)'],
50543 seealso: ['acsch', 'asech']
50544};
50545// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/trigonometry/acot.js
50546var acotDocs = {
50547 name: 'acot',
50548 category: 'Trigonometry',
50549 syntax: ['acot(x)'],
50550 description: 'Calculate the inverse cotangent of a value.',
50551 examples: ['acot(0.5)', 'acot(cot(0.5))', 'acot(2)'],
50552 seealso: ['cot', 'atan']
50553};
50554// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/trigonometry/acosh.js
50555var acoshDocs = {
50556 name: 'acosh',
50557 category: 'Trigonometry',
50558 syntax: ['acosh(x)'],
50559 description: 'Calculate the hyperbolic arccos of a value, defined as `acosh(x) = ln(sqrt(x^2 - 1) + x)`.',
50560 examples: ['acosh(1.5)'],
50561 seealso: ['cosh', 'asinh', 'atanh']
50562};
50563// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/trigonometry/acos.js
50564var acosDocs = {
50565 name: 'acos',
50566 category: 'Trigonometry',
50567 syntax: ['acos(x)'],
50568 description: 'Compute the inverse cosine of a value in radians.',
50569 examples: ['acos(0.5)', 'acos(cos(2.3))'],
50570 seealso: ['cos', 'atan', 'asin']
50571};
50572// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/statistics/sum.js
50573var sumDocs = {
50574 name: 'sum',
50575 category: 'Statistics',
50576 syntax: ['sum(a, b, c, ...)', 'sum(A)'],
50577 description: 'Compute the sum of all values.',
50578 examples: ['sum(2, 3, 4, 1)', 'sum([2, 3, 4, 1])', 'sum([2, 5; 4, 3])'],
50579 seealso: ['max', 'mean', 'median', 'min', 'prod', 'std', 'sum', 'variance']
50580};
50581// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/statistics/std.js
50582var stdDocs = {
50583 name: 'std',
50584 category: 'Statistics',
50585 syntax: ['std(a, b, c, ...)', 'std(A)', 'std(A, normalization)'],
50586 description: 'Compute the standard deviation of all values, defined as std(A) = sqrt(variance(A)). Optional parameter normalization can be "unbiased" (default), "uncorrected", or "biased".',
50587 examples: ['std(2, 4, 6)', 'std([2, 4, 6, 8])', 'std([2, 4, 6, 8], "uncorrected")', 'std([2, 4, 6, 8], "biased")', 'std([1, 2, 3; 4, 5, 6])'],
50588 seealso: ['max', 'mean', 'min', 'median', 'prod', 'sum', 'variance']
50589};
50590// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/statistics/quantileSeq.js
50591var quantileSeqDocs = {
50592 name: 'quantileSeq',
50593 category: 'Statistics',
50594 syntax: ['quantileSeq(A, prob[, sorted])', 'quantileSeq(A, [prob1, prob2, ...][, sorted])', 'quantileSeq(A, N[, sorted])'],
50595 description: 'Compute the prob order quantile of a matrix or a list with values. The sequence is sorted and the middle value is returned. Supported types of sequence values are: Number, BigNumber, Unit Supported types of probablity are: Number, BigNumber. \n\nIn case of a (multi dimensional) array or matrix, the prob order quantile of all elements will be calculated.',
50596 examples: ['quantileSeq([3, -1, 5, 7], 0.5)', 'quantileSeq([3, -1, 5, 7], [1/3, 2/3])', 'quantileSeq([3, -1, 5, 7], 2)', 'quantileSeq([-1, 3, 5, 7], 0.5, true)'],
50597 seealso: ['mean', 'median', 'min', 'max', 'prod', 'std', 'sum', 'variance']
50598};
50599// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/statistics/prod.js
50600var prodDocs = {
50601 name: 'prod',
50602 category: 'Statistics',
50603 syntax: ['prod(a, b, c, ...)', 'prod(A)'],
50604 description: 'Compute the product of all values.',
50605 examples: ['prod(2, 3, 4)', 'prod([2, 3, 4])', 'prod([2, 5; 4, 3])'],
50606 seealso: ['max', 'mean', 'min', 'median', 'min', 'std', 'sum', 'variance']
50607};
50608// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/statistics/mode.js
50609var modeDocs = {
50610 name: 'mode',
50611 category: 'Statistics',
50612 syntax: ['mode(a, b, c, ...)', 'mode(A)', 'mode(A, a, b, B, c, ...)'],
50613 description: 'Computes the mode of all values as an array. In case mode being more than one, multiple values are returned in an array.',
50614 examples: ['mode(2, 1, 4, 3, 1)', 'mode([1, 2.7, 3.2, 4, 2.7])', 'mode(1, 4, 6, 1, 6)'],
50615 seealso: ['max', 'mean', 'min', 'median', 'prod', 'std', 'sum', 'variance']
50616};
50617// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/statistics/min.js
50618var minDocs = {
50619 name: 'min',
50620 category: 'Statistics',
50621 syntax: ['min(a, b, c, ...)', 'min(A)', 'min(A, dim)'],
50622 description: 'Compute the minimum value of a list of values.',
50623 examples: ['min(2, 3, 4, 1)', 'min([2, 3, 4, 1])', 'min([2, 5; 4, 3])', 'min([2, 5; 4, 3], 1)', 'min([2, 5; 4, 3], 2)', 'min(2.7, 7.1, -4.5, 2.0, 4.1)', 'max(2.7, 7.1, -4.5, 2.0, 4.1)'],
50624 seealso: ['max', 'mean', 'median', 'prod', 'std', 'sum', 'variance']
50625};
50626// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/statistics/median.js
50627var medianDocs = {
50628 name: 'median',
50629 category: 'Statistics',
50630 syntax: ['median(a, b, c, ...)', 'median(A)'],
50631 description: 'Compute the median of all values. The values are sorted and the middle value is returned. In case of an even number of values, the average of the two middle values is returned.',
50632 examples: ['median(5, 2, 7)', 'median([3, -1, 5, 7])'],
50633 seealso: ['max', 'mean', 'min', 'prod', 'std', 'sum', 'variance', 'quantileSeq']
50634};
50635// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/statistics/mean.js
50636var meanDocs = {
50637 name: 'mean',
50638 category: 'Statistics',
50639 syntax: ['mean(a, b, c, ...)', 'mean(A)', 'mean(A, dim)'],
50640 description: 'Compute the arithmetic mean of a list of values.',
50641 examples: ['mean(2, 3, 4, 1)', 'mean([2, 3, 4, 1])', 'mean([2, 5; 4, 3])', 'mean([2, 5; 4, 3], 1)', 'mean([2, 5; 4, 3], 2)', 'mean([1.0, 2.7, 3.2, 4.0])'],
50642 seealso: ['max', 'median', 'min', 'prod', 'std', 'sum', 'variance']
50643};
50644// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/statistics/max.js
50645var maxDocs = {
50646 name: 'max',
50647 category: 'Statistics',
50648 syntax: ['max(a, b, c, ...)', 'max(A)', 'max(A, dim)'],
50649 description: 'Compute the maximum value of a list of values.',
50650 examples: ['max(2, 3, 4, 1)', 'max([2, 3, 4, 1])', 'max([2, 5; 4, 3])', 'max([2, 5; 4, 3], 1)', 'max([2, 5; 4, 3], 2)', 'max(2.7, 7.1, -4.5, 2.0, 4.1)', 'min(2.7, 7.1, -4.5, 2.0, 4.1)'],
50651 seealso: ['mean', 'median', 'min', 'prod', 'std', 'sum', 'variance']
50652};
50653// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/statistics/mad.js
50654var madDocs = {
50655 name: 'mad',
50656 category: 'Statistics',
50657 syntax: ['mad(a, b, c, ...)', 'mad(A)'],
50658 description: 'Compute the median absolute deviation of a matrix or a list with values. The median absolute deviation is defined as the median of the absolute deviations from the median.',
50659 examples: ['mad(10, 20, 30)', 'mad([1, 2, 3])'],
50660 seealso: ['mean', 'median', 'std', 'abs']
50661};
50662// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/special/erf.js
50663var erfDocs = {
50664 name: 'erf',
50665 category: 'Special',
50666 syntax: ['erf(x)'],
50667 description: 'Compute the erf function of a value using a rational Chebyshev approximations for different intervals of x',
50668 examples: ['erf(0.2)', 'erf(-0.5)', 'erf(4)'],
50669 seealso: []
50670};
50671// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/set/setUnion.js
50672var setUnionDocs = {
50673 name: 'setUnion',
50674 category: 'Set',
50675 syntax: ['setUnion(set1, set2)'],
50676 description: 'Create the union of two (multi)sets. Multi-dimension arrays will be converted to single-dimension arrays before the operation.',
50677 examples: ['setUnion([1, 2, 3, 4], [3, 4, 5, 6])', 'setUnion([[1, 2], [3, 4]], [[3, 4], [5, 6]])'],
50678 seealso: ['setIntersect', 'setDifference']
50679};
50680// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/set/setSymDifference.js
50681var setSymDifferenceDocs = {
50682 name: 'setSymDifference',
50683 category: 'Set',
50684 syntax: ['setSymDifference(set1, set2)'],
50685 description: 'Create the symmetric difference of two (multi)sets. Multi-dimension arrays will be converted to single-dimension arrays before the operation.',
50686 examples: ['setSymDifference([1, 2, 3, 4], [3, 4, 5, 6])', 'setSymDifference([[1, 2], [3, 4]], [[3, 4], [5, 6]])'],
50687 seealso: ['setUnion', 'setIntersect', 'setDifference']
50688};
50689// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/set/setSize.js
50690var setSizeDocs = {
50691 name: 'setSize',
50692 category: 'Set',
50693 syntax: ['setSize(set)', 'setSize(set, unique)'],
50694 description: 'Count the number of elements of a (multi)set. When the second parameter "unique" is true, count only the unique values. A multi-dimension array will be converted to a single-dimension array before the operation.',
50695 examples: ['setSize([1, 2, 2, 4])', 'setSize([1, 2, 2, 4], true)'],
50696 seealso: ['setUnion', 'setIntersect', 'setDifference']
50697};
50698// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/set/setPowerset.js
50699var setPowersetDocs = {
50700 name: 'setPowerset',
50701 category: 'Set',
50702 syntax: ['setPowerset(set)'],
50703 description: 'Create the powerset of a (multi)set: the powerset contains very possible subsets of a (multi)set. A multi-dimension array will be converted to a single-dimension array before the operation.',
50704 examples: ['setPowerset([1, 2, 3])'],
50705 seealso: ['setCartesian']
50706};
50707// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/set/setMultiplicity.js
50708var setMultiplicityDocs = {
50709 name: 'setMultiplicity',
50710 category: 'Set',
50711 syntax: ['setMultiplicity(element, set)'],
50712 description: 'Count the multiplicity of an element in a multiset. A multi-dimension array will be converted to a single-dimension array before the operation.',
50713 examples: ['setMultiplicity(1, [1, 2, 2, 4])', 'setMultiplicity(2, [1, 2, 2, 4])'],
50714 seealso: ['setDistinct', 'setSize']
50715};
50716// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/set/setIsSubset.js
50717var setIsSubsetDocs = {
50718 name: 'setIsSubset',
50719 category: 'Set',
50720 syntax: ['setIsSubset(set1, set2)'],
50721 description: 'Check whether a (multi)set is a subset of another (multi)set: every element of set1 is the element of set2. Multi-dimension arrays will be converted to single-dimension arrays before the operation.',
50722 examples: ['setIsSubset([1, 2], [3, 4, 5, 6])', 'setIsSubset([3, 4], [3, 4, 5, 6])'],
50723 seealso: ['setUnion', 'setIntersect', 'setDifference']
50724};
50725// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/set/setIntersect.js
50726var setIntersectDocs = {
50727 name: 'setIntersect',
50728 category: 'Set',
50729 syntax: ['setIntersect(set1, set2)'],
50730 description: 'Create the intersection of two (multi)sets. Multi-dimension arrays will be converted to single-dimension arrays before the operation.',
50731 examples: ['setIntersect([1, 2, 3, 4], [3, 4, 5, 6])', 'setIntersect([[1, 2], [3, 4]], [[3, 4], [5, 6]])'],
50732 seealso: ['setUnion', 'setDifference']
50733};
50734// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/set/setDistinct.js
50735var setDistinctDocs = {
50736 name: 'setDistinct',
50737 category: 'Set',
50738 syntax: ['setDistinct(set)'],
50739 description: 'Collect the distinct elements of a multiset. A multi-dimension array will be converted to a single-dimension array before the operation.',
50740 examples: ['setDistinct([1, 1, 1, 2, 2, 3])'],
50741 seealso: ['setMultiplicity']
50742};
50743// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/set/setDifference.js
50744var setDifferenceDocs = {
50745 name: 'setDifference',
50746 category: 'Set',
50747 syntax: ['setDifference(set1, set2)'],
50748 description: 'Create the difference of two (multi)sets: every element of set1, that is not the element of set2. Multi-dimension arrays will be converted to single-dimension arrays before the operation.',
50749 examples: ['setDifference([1, 2, 3, 4], [3, 4, 5, 6])', 'setDifference([[1, 2], [3, 4]], [[3, 4], [5, 6]])'],
50750 seealso: ['setUnion', 'setIntersect', 'setSymDifference']
50751};
50752// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/set/setCartesian.js
50753var setCartesianDocs = {
50754 name: 'setCartesian',
50755 category: 'Set',
50756 syntax: ['setCartesian(set1, set2)'],
50757 description: 'Create the cartesian product of two (multi)sets. Multi-dimension arrays will be converted to single-dimension arrays before the operation.',
50758 examples: ['setCartesian([1, 2], [3, 4])'],
50759 seealso: ['setUnion', 'setIntersect', 'setDifference', 'setPowerset']
50760};
50761// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/relational/unequal.js
50762var unequalDocs = {
50763 name: 'unequal',
50764 category: 'Relational',
50765 syntax: ['x != y', 'unequal(x, y)'],
50766 description: 'Check unequality of two values. Returns true if the values are unequal, and false if they are equal.',
50767 examples: ['2+2 != 3', '2+2 != 4', 'a = 3.2', 'b = 6-2.8', 'a != b', '50cm != 0.5m', '5 cm != 2 inch'],
50768 seealso: ['equal', 'smaller', 'larger', 'smallerEq', 'largerEq', 'compare', 'deepEqual']
50769};
50770// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/relational/smallerEq.js
50771var smallerEqDocs = {
50772 name: 'smallerEq',
50773 category: 'Relational',
50774 syntax: ['x <= y', 'smallerEq(x, y)'],
50775 description: 'Check if value x is smaller or equal to value y. Returns true if x is smaller than y, and false if not.',
50776 examples: ['2 <= 1+1', '2 < 1+1', 'a = 3.2', 'b = 6-2.8', '(a <= b)'],
50777 seealso: ['equal', 'unequal', 'larger', 'smaller', 'largerEq', 'compare']
50778};
50779// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/relational/smaller.js
50780var smallerDocs = {
50781 name: 'smaller',
50782 category: 'Relational',
50783 syntax: ['x < y', 'smaller(x, y)'],
50784 description: 'Check if value x is smaller than value y. Returns true if x is smaller than y, and false if not.',
50785 examples: ['2 < 3', '5 < 2*2', 'a = 3.3', 'b = 6-2.8', '(a < b)', '5 cm < 2 inch'],
50786 seealso: ['equal', 'unequal', 'larger', 'smallerEq', 'largerEq', 'compare']
50787};
50788// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/relational/largerEq.js
50789var largerEqDocs = {
50790 name: 'largerEq',
50791 category: 'Relational',
50792 syntax: ['x >= y', 'largerEq(x, y)'],
50793 description: 'Check if value x is larger or equal to y. Returns true if x is larger or equal to y, and false if not.',
50794 examples: ['2 >= 1+1', '2 > 1+1', 'a = 3.2', 'b = 6-2.8', '(a >= b)'],
50795 seealso: ['equal', 'unequal', 'smallerEq', 'smaller', 'compare']
50796};
50797// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/relational/larger.js
50798var largerDocs = {
50799 name: 'larger',
50800 category: 'Relational',
50801 syntax: ['x > y', 'larger(x, y)'],
50802 description: 'Check if value x is larger than y. Returns true if x is larger than y, and false if not.',
50803 examples: ['2 > 3', '5 > 2*2', 'a = 3.3', 'b = 6-2.8', '(a > b)', '(b < a)', '5 cm > 2 inch'],
50804 seealso: ['equal', 'unequal', 'smaller', 'smallerEq', 'largerEq', 'compare']
50805};
50806// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/relational/equalText.js
50807var equalTextDocs = {
50808 name: 'equalText',
50809 category: 'Relational',
50810 syntax: ['equalText(x, y)'],
50811 description: 'Check equality of two strings. Comparison is case sensitive. Returns true if the values are equal, and false if not.',
50812 examples: ['equalText("Hello", "Hello")', 'equalText("a", "A")', 'equal("2e3", "2000")', 'equalText("2e3", "2000")', 'equalText("B", ["A", "B", "C"])'],
50813 seealso: ['compare', 'compareNatural', 'compareText', 'equal']
50814};
50815// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/relational/equal.js
50816var equalDocs = {
50817 name: 'equal',
50818 category: 'Relational',
50819 syntax: ['x == y', 'equal(x, y)'],
50820 description: 'Check equality of two values. Returns true if the values are equal, and false if not.',
50821 examples: ['2+2 == 3', '2+2 == 4', 'a = 3.2', 'b = 6-2.8', 'a == b', '50cm == 0.5m'],
50822 seealso: ['unequal', 'smaller', 'larger', 'smallerEq', 'largerEq', 'compare', 'deepEqual', 'equalText']
50823};
50824// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/relational/deepEqual.js
50825var deepEqualDocs = {
50826 name: 'deepEqual',
50827 category: 'Relational',
50828 syntax: ['deepEqual(x, y)'],
50829 description: 'Check equality of two matrices element wise. Returns true if the size of both matrices is equal and when and each of the elements are equal.',
50830 examples: ['deepEqual([1,3,4], [1,3,4])', 'deepEqual([1,3,4], [1,3])'],
50831 seealso: ['equal', 'unequal', 'smaller', 'larger', 'smallerEq', 'largerEq', 'compare']
50832};
50833// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/relational/compareText.js
50834var compareTextDocs = {
50835 name: 'compareText',
50836 category: 'Relational',
50837 syntax: ['compareText(x, y)'],
50838 description: 'Compare two strings lexically. Comparison is case sensitive. ' + 'Returns 1 when x > y, -1 when x < y, and 0 when x == y.',
50839 examples: ['compareText("B", "A")', 'compareText("A", "B")', 'compareText("A", "A")', 'compareText("2", "10")', 'compare("2", "10")', 'compare(2, 10)', 'compareNatural("2", "10")', 'compareText("B", ["A", "B", "C"])'],
50840 seealso: ['compare', 'compareNatural']
50841};
50842// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/relational/compareNatural.js
50843var compareNaturalDocs = {
50844 name: 'compareNatural',
50845 category: 'Relational',
50846 syntax: ['compareNatural(x, y)'],
50847 description: 'Compare two values of any type in a deterministic, natural way. ' + 'Returns 1 when x > y, -1 when x < y, and 0 when x == y.',
50848 examples: ['compareNatural(2, 3)', 'compareNatural(3, 2)', 'compareNatural(2, 2)', 'compareNatural(5cm, 40mm)', 'compareNatural("2", "10")', 'compareNatural(2 + 3i, 2 + 4i)', 'compareNatural([1, 2, 4], [1, 2, 3])', 'compareNatural([1, 5], [1, 2, 3])', 'compareNatural([1, 2], [1, 2])', 'compareNatural({a: 2}, {a: 4})'],
50849 seealso: ['equal', 'unequal', 'smaller', 'smallerEq', 'largerEq', 'compare', 'compareText']
50850};
50851// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/relational/compare.js
50852var compareDocs = {
50853 name: 'compare',
50854 category: 'Relational',
50855 syntax: ['compare(x, y)'],
50856 description: 'Compare two values. ' + 'Returns 1 when x > y, -1 when x < y, and 0 when x == y.',
50857 examples: ['compare(2, 3)', 'compare(3, 2)', 'compare(2, 2)', 'compare(5cm, 40mm)', 'compare(2, [1, 2, 3])'],
50858 seealso: ['equal', 'unequal', 'smaller', 'smallerEq', 'largerEq', 'compareNatural', 'compareText']
50859};
50860// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/probability/randomInt.js
50861var randomIntDocs = {
50862 name: 'randomInt',
50863 category: 'Probability',
50864 syntax: ['randomInt(max)', 'randomInt(min, max)', 'randomInt(size)', 'randomInt(size, max)', 'randomInt(size, min, max)'],
50865 description: 'Return a random integer number',
50866 examples: ['randomInt(10, 20)', 'randomInt([2, 3], 10)'],
50867 seealso: ['pickRandom', 'random']
50868};
50869// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/probability/random.js
50870var randomDocs = {
50871 name: 'random',
50872 category: 'Probability',
50873 syntax: ['random()', 'random(max)', 'random(min, max)', 'random(size)', 'random(size, max)', 'random(size, min, max)'],
50874 description: 'Return a random number.',
50875 examples: ['random()', 'random(10, 20)', 'random([2, 3])'],
50876 seealso: ['pickRandom', 'randomInt']
50877};
50878// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/probability/pickRandom.js
50879var pickRandomDocs = {
50880 name: 'pickRandom',
50881 category: 'Probability',
50882 syntax: ['pickRandom(array)', 'pickRandom(array, number)', 'pickRandom(array, weights)', 'pickRandom(array, number, weights)', 'pickRandom(array, weights, number)'],
50883 description: 'Pick a random entry from a given array.',
50884 examples: ['pickRandom(0:10)', 'pickRandom([1, 3, 1, 6])', 'pickRandom([1, 3, 1, 6], 2)', 'pickRandom([1, 3, 1, 6], [2, 3, 2, 1])', 'pickRandom([1, 3, 1, 6], 2, [2, 3, 2, 1])', 'pickRandom([1, 3, 1, 6], [2, 3, 2, 1], 2)'],
50885 seealso: ['random', 'randomInt']
50886};
50887// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/probability/permutations.js
50888var permutationsDocs = {
50889 name: 'permutations',
50890 category: 'Probability',
50891 syntax: ['permutations(n)', 'permutations(n, k)'],
50892 description: 'Compute the number of permutations of n items taken k at a time',
50893 examples: ['permutations(5)', 'permutations(5, 3)'],
50894 seealso: ['combinations', 'combinationsWithRep', 'factorial']
50895};
50896// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/probability/multinomial.js
50897var multinomialDocs = {
50898 name: 'multinomial',
50899 category: 'Probability',
50900 syntax: ['multinomial(A)'],
50901 description: 'Multinomial Coefficients compute the number of ways of picking a1, a2, ..., ai unordered outcomes from `n` possibilities. multinomial takes one array of integers as an argument. The following condition must be enforced: every ai > 0.',
50902 examples: ['multinomial([1, 2, 1])'],
50903 seealso: ['combinations', 'factorial']
50904};
50905// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/probability/kldivergence.js
50906var kldivergenceDocs = {
50907 name: 'kldivergence',
50908 category: 'Probability',
50909 syntax: ['kldivergence(x, y)'],
50910 description: 'Calculate the Kullback-Leibler (KL) divergence between two distributions.',
50911 examples: ['kldivergence([0.7,0.5,0.4], [0.2,0.9,0.5])'],
50912 seealso: []
50913};
50914// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/probability/gamma.js
50915var gammaDocs = {
50916 name: 'gamma',
50917 category: 'Probability',
50918 syntax: ['gamma(n)'],
50919 description: 'Compute the gamma function. For small values, the Lanczos approximation is used, and for large values the extended Stirling approximation.',
50920 examples: ['gamma(4)', '3!', 'gamma(1/2)', 'sqrt(pi)'],
50921 seealso: ['factorial']
50922};
50923// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/probability/factorial.js
50924var factorialDocs = {
50925 name: 'factorial',
50926 category: 'Probability',
50927 syntax: ['n!', 'factorial(n)'],
50928 description: 'Compute the factorial of a value',
50929 examples: ['5!', '5 * 4 * 3 * 2 * 1', '3!'],
50930 seealso: ['combinations', 'combinationsWithRep', 'permutations', 'gamma']
50931};
50932// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/probability/combinations.js
50933var combinationsDocs = {
50934 name: 'combinations',
50935 category: 'Probability',
50936 syntax: ['combinations(n, k)'],
50937 description: 'Compute the number of combinations of n items taken k at a time',
50938 examples: ['combinations(7, 5)'],
50939 seealso: ['combinationsWithRep', 'permutations', 'factorial']
50940};
50941// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/probability/combinationsWithRep.js
50942var combinationsWithRepDocs = {
50943 name: 'combinationsWithRep',
50944 category: 'Probability',
50945 syntax: ['combinationsWithRep(n, k)'],
50946 description: 'Compute the number of combinations of n items taken k at a time with replacements.',
50947 examples: ['combinationsWithRep(7, 5)'],
50948 seealso: ['combinations', 'permutations', 'factorial']
50949};
50950// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/matrix/zeros.js
50951var zerosDocs = {
50952 name: 'zeros',
50953 category: 'Matrix',
50954 syntax: ['zeros(m)', 'zeros(m, n)', 'zeros(m, n, p, ...)', 'zeros([m])', 'zeros([m, n])', 'zeros([m, n, p, ...])'],
50955 description: 'Create a matrix containing zeros.',
50956 examples: ['zeros(3)', 'zeros(3, 5)', 'a = [1, 2, 3; 4, 5, 6]', 'zeros(size(a))'],
50957 seealso: ['concat', 'det', 'diag', 'identity', 'inv', 'ones', 'range', 'size', 'squeeze', 'subset', 'trace', 'transpose']
50958};
50959// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/matrix/transpose.js
50960var transposeDocs = {
50961 name: 'transpose',
50962 category: 'Matrix',
50963 syntax: ['x\'', 'transpose(x)'],
50964 description: 'Transpose a matrix',
50965 examples: ['a = [1, 2, 3; 4, 5, 6]', 'a\'', 'transpose(a)'],
50966 seealso: ['concat', 'det', 'diag', 'identity', 'inv', 'ones', 'range', 'size', 'squeeze', 'subset', 'trace', 'zeros']
50967};
50968// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/matrix/trace.js
50969var traceDocs = {
50970 name: 'trace',
50971 category: 'Matrix',
50972 syntax: ['trace(A)'],
50973 description: 'Calculate the trace of a matrix: the sum of the elements on the main diagonal of a square matrix.',
50974 examples: ['A = [1, 2, 3; -1, 2, 3; 2, 0, 3]', 'trace(A)'],
50975 seealso: ['concat', 'det', 'diag', 'identity', 'inv', 'ones', 'range', 'size', 'squeeze', 'subset', 'transpose', 'zeros']
50976};
50977// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/matrix/subset.js
50978var subsetDocs = {
50979 name: 'subset',
50980 category: 'Matrix',
50981 syntax: ['value(index)', 'value(index) = replacement', 'subset(value, [index])', 'subset(value, [index], replacement)'],
50982 description: 'Get or set a subset of a matrix or string. ' + 'Indexes are one-based. ' + 'Both the ranges lower-bound and upper-bound are included.',
50983 examples: ['d = [1, 2; 3, 4]', 'e = []', 'e[1, 1:2] = [5, 6]', 'e[2, :] = [7, 8]', 'f = d * e', 'f[2, 1]', 'f[:, 1]'],
50984 seealso: ['concat', 'det', 'diag', 'identity', 'inv', 'ones', 'range', 'size', 'squeeze', 'trace', 'transpose', 'zeros']
50985};
50986// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/matrix/squeeze.js
50987var squeezeDocs = {
50988 name: 'squeeze',
50989 category: 'Matrix',
50990 syntax: ['squeeze(x)'],
50991 description: 'Remove inner and outer singleton dimensions from a matrix.',
50992 examples: ['a = zeros(3,2,1)', 'size(squeeze(a))', 'b = zeros(1,1,3)', 'size(squeeze(b))'],
50993 seealso: ['concat', 'det', 'diag', 'identity', 'inv', 'ones', 'range', 'size', 'subset', 'trace', 'transpose', 'zeros']
50994};
50995// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/matrix/sort.js
50996var sortDocs = {
50997 name: 'sort',
50998 category: 'Matrix',
50999 syntax: ['sort(x)', 'sort(x, compare)'],
51000 description: 'Sort the items in a matrix. Compare can be a string "asc", "desc", "natural", or a custom sort function.',
51001 examples: ['sort([5, 10, 1])', 'sort(["C", "B", "A", "D"])', 'sortByLength(a, b) = size(a)[1] - size(b)[1]', 'sort(["Langdon", "Tom", "Sara"], sortByLength)', 'sort(["10", "1", "2"], "natural")'],
51002 seealso: ['map', 'filter', 'forEach']
51003};
51004// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/matrix/size.js
51005var sizeDocs = {
51006 name: 'size',
51007 category: 'Matrix',
51008 syntax: ['size(x)'],
51009 description: 'Calculate the size of a matrix.',
51010 examples: ['size(2.3)', 'size("hello world")', 'a = [1, 2; 3, 4; 5, 6]', 'size(a)', 'size(1:6)'],
51011 seealso: ['concat', 'det', 'diag', 'identity', 'inv', 'ones', 'range', 'squeeze', 'subset', 'trace', 'transpose', 'zeros']
51012};
51013// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/matrix/reshape.js
51014var reshapeDocs = {
51015 name: 'reshape',
51016 category: 'Matrix',
51017 syntax: ['reshape(x, sizes)'],
51018 description: 'Reshape a multi dimensional array to fit the specified dimensions.',
51019 examples: ['reshape([1, 2, 3, 4, 5, 6], [2, 3])', 'reshape([[1, 2], [3, 4]], [1, 4])', 'reshape([[1, 2], [3, 4]], [4])'],
51020 seealso: ['size', 'squeeze', 'resize']
51021};
51022// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/matrix/resize.js
51023var resizeDocs = {
51024 name: 'resize',
51025 category: 'Matrix',
51026 syntax: ['resize(x, size)', 'resize(x, size, defaultValue)'],
51027 description: 'Resize a matrix.',
51028 examples: ['resize([1,2,3,4,5], [3])', 'resize([1,2,3], [5])', 'resize([1,2,3], [5], -1)', 'resize(2, [2, 3])', 'resize("hello", [8], "!")'],
51029 seealso: ['size', 'subset', 'squeeze', 'reshape']
51030};
51031// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/matrix/range.js
51032var rangeDocs = {
51033 name: 'range',
51034 category: 'Type',
51035 syntax: ['start:end', 'start:step:end', 'range(start, end)', 'range(start, end, step)', 'range(string)'],
51036 description: 'Create a range. Lower bound of the range is included, upper bound is excluded.',
51037 examples: ['1:5', '3:-1:-3', 'range(3, 7)', 'range(0, 12, 2)', 'range("4:10")', 'a = [1, 2, 3, 4; 5, 6, 7, 8]', 'a[1:2, 1:2]'],
51038 seealso: ['concat', 'det', 'diag', 'identity', 'inv', 'ones', 'size', 'squeeze', 'subset', 'trace', 'transpose', 'zeros']
51039};
51040// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/matrix/partitionSelect.js
51041var partitionSelectDocs = {
51042 name: 'partitionSelect',
51043 category: 'Matrix',
51044 syntax: ['partitionSelect(x, k)', 'partitionSelect(x, k, compare)'],
51045 description: 'Partition-based selection of an array or 1D matrix. Will find the kth smallest value, and mutates the input array. Uses Quickselect.',
51046 examples: ['partitionSelect([5, 10, 1], 2)', 'partitionSelect(["C", "B", "A", "D"], 1)'],
51047 seealso: ['sort']
51048};
51049// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/matrix/ones.js
51050var onesDocs = {
51051 name: 'ones',
51052 category: 'Matrix',
51053 syntax: ['ones(m)', 'ones(m, n)', 'ones(m, n, p, ...)', 'ones([m])', 'ones([m, n])', 'ones([m, n, p, ...])'],
51054 description: 'Create a matrix containing ones.',
51055 examples: ['ones(3)', 'ones(3, 5)', 'ones([2,3]) * 4.5', 'a = [1, 2, 3; 4, 5, 6]', 'ones(size(a))'],
51056 seealso: ['concat', 'det', 'diag', 'identity', 'inv', 'range', 'size', 'squeeze', 'subset', 'trace', 'transpose', 'zeros']
51057};
51058// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/matrix/map.js
51059var mapDocs = {
51060 name: 'map',
51061 category: 'Matrix',
51062 syntax: ['map(x, callback)'],
51063 description: 'Create a new matrix or array with the results of the callback function executed on each entry of the matrix/array.',
51064 examples: ['map([1, 2, 3], square)'],
51065 seealso: ['filter', 'forEach']
51066};
51067// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/matrix/kron.js
51068var kronDocs = {
51069 name: 'kron',
51070 category: 'Matrix',
51071 syntax: ['kron(x, y)'],
51072 description: 'Calculates the kronecker product of 2 matrices or vectors.',
51073 examples: ['kron([[1, 0], [0, 1]], [[1, 2], [3, 4]])', 'kron([1,1], [2,3,4])'],
51074 seealso: ['multiply', 'dot', 'cross']
51075};
51076// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/matrix/inv.js
51077var invDocs = {
51078 name: 'inv',
51079 category: 'Matrix',
51080 syntax: ['inv(x)'],
51081 description: 'Calculate the inverse of a matrix',
51082 examples: ['inv([1, 2; 3, 4])', 'inv(4)', '1 / 4'],
51083 seealso: ['concat', 'det', 'diag', 'identity', 'ones', 'range', 'size', 'squeeze', 'subset', 'trace', 'transpose', 'zeros']
51084};
51085// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/matrix/forEach.js
51086var forEachDocs = {
51087 name: 'forEach',
51088 category: 'Matrix',
51089 syntax: ['forEach(x, callback)'],
51090 description: 'Iterates over all elements of a matrix/array, and executes the given callback function.',
51091 examples: ['forEach([1, 2, 3], function(val) { console.log(val) })'],
51092 seealso: ['map', 'sort', 'filter']
51093};
51094// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/matrix/flatten.js
51095var flattenDocs = {
51096 name: 'flatten',
51097 category: 'Matrix',
51098 syntax: ['flatten(x)'],
51099 description: 'Flatten a multi dimensional matrix into a single dimensional matrix.',
51100 examples: ['a = [1, 2, 3; 4, 5, 6]', 'size(a)', 'b = flatten(a)', 'size(b)'],
51101 seealso: ['concat', 'resize', 'size', 'squeeze']
51102};
51103// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/matrix/filter.js
51104var filterDocs = {
51105 name: 'filter',
51106 category: 'Matrix',
51107 syntax: ['filter(x, test)'],
51108 description: 'Filter items in a matrix.',
51109 examples: ['isPositive(x) = x > 0', 'filter([6, -2, -1, 4, 3], isPositive)', 'filter([6, -2, 0, 1, 0], x != 0)'],
51110 seealso: ['sort', 'map', 'forEach']
51111};
51112// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/matrix/identity.js
51113var identityDocs = {
51114 name: 'identity',
51115 category: 'Matrix',
51116 syntax: ['identity(n)', 'identity(m, n)', 'identity([m, n])'],
51117 description: 'Returns the identity matrix with size m-by-n. The matrix has ones on the diagonal and zeros elsewhere.',
51118 examples: ['identity(3)', 'identity(3, 5)', 'a = [1, 2, 3; 4, 5, 6]', 'identity(size(a))'],
51119 seealso: ['concat', 'det', 'diag', 'inv', 'ones', 'range', 'size', 'squeeze', 'subset', 'trace', 'transpose', 'zeros']
51120};
51121// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/matrix/getMatrixDataType.js
51122var getMatrixDataTypeDocs = {
51123 name: 'getMatrixDataType',
51124 category: 'Matrix',
51125 syntax: ['getMatrixDataType(x)'],
51126 description: 'Find the data type of all elements in a matrix or array, ' + 'for example "number" if all items are a number ' + 'and "Complex" if all values are complex numbers. ' + 'If a matrix contains more than one data type, it will return "mixed".',
51127 examples: ['getMatrixDataType([1, 2, 3])', 'getMatrixDataType([[5 cm], [2 inch]])', 'getMatrixDataType([1, "text"])', 'getMatrixDataType([1, bignumber(4)])'],
51128 seealso: ['matrix', 'sparse', 'typeOf']
51129};
51130// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/matrix/dot.js
51131var dotDocs = {
51132 name: 'dot',
51133 category: 'Matrix',
51134 syntax: ['dot(A, B)', 'A * B'],
51135 description: 'Calculate the dot product of two vectors. ' + 'The dot product of A = [a1, a2, a3, ..., an] and B = [b1, b2, b3, ..., bn] ' + 'is defined as dot(A, B) = a1 * b1 + a2 * b2 + a3 * b3 + ... + an * bn',
51136 examples: ['dot([2, 4, 1], [2, 2, 3])', '[2, 4, 1] * [2, 2, 3]'],
51137 seealso: ['multiply', 'cross']
51138};
51139// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/matrix/diag.js
51140var diagDocs = {
51141 name: 'diag',
51142 category: 'Matrix',
51143 syntax: ['diag(x)', 'diag(x, k)'],
51144 description: 'Create a diagonal matrix or retrieve the diagonal of a matrix. When x is a vector, a matrix with the vector values on the diagonal will be returned. When x is a matrix, a vector with the diagonal values of the matrix is returned. When k is provided, the k-th diagonal will be filled in or retrieved, if k is positive, the values are placed on the super diagonal. When k is negative, the values are placed on the sub diagonal.',
51145 examples: ['diag(1:3)', 'diag(1:3, 1)', 'a = [1, 2, 3; 4, 5, 6; 7, 8, 9]', 'diag(a)'],
51146 seealso: ['concat', 'det', 'identity', 'inv', 'ones', 'range', 'size', 'squeeze', 'subset', 'trace', 'transpose', 'zeros']
51147};
51148// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/matrix/det.js
51149var detDocs = {
51150 name: 'det',
51151 category: 'Matrix',
51152 syntax: ['det(x)'],
51153 description: 'Calculate the determinant of a matrix',
51154 examples: ['det([1, 2; 3, 4])', 'det([-2, 2, 3; -1, 1, 3; 2, 0, -1])'],
51155 seealso: ['concat', 'diag', 'identity', 'inv', 'ones', 'range', 'size', 'squeeze', 'subset', 'trace', 'transpose', 'zeros']
51156};
51157// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/matrix/ctranspose.js
51158var ctransposeDocs = {
51159 name: 'ctranspose',
51160 category: 'Matrix',
51161 syntax: ['x\'', 'ctranspose(x)'],
51162 description: 'Complex Conjugate and Transpose a matrix',
51163 examples: ['a = [1, 2, 3; 4, 5, 6]', 'a\'', 'ctranspose(a)'],
51164 seealso: ['concat', 'det', 'diag', 'identity', 'inv', 'ones', 'range', 'size', 'squeeze', 'subset', 'trace', 'zeros']
51165};
51166// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/matrix/cross.js
51167var crossDocs = {
51168 name: 'cross',
51169 category: 'Matrix',
51170 syntax: ['cross(A, B)'],
51171 description: 'Calculate the cross product for two vectors in three dimensional space.',
51172 examples: ['cross([1, 1, 0], [0, 1, 1])', 'cross([3, -3, 1], [4, 9, 2])', 'cross([2, 3, 4], [5, 6, 7])'],
51173 seealso: ['multiply', 'dot']
51174};
51175// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/matrix/concat.js
51176var concatDocs = {
51177 name: 'concat',
51178 category: 'Matrix',
51179 syntax: ['concat(A, B, C, ...)', 'concat(A, B, C, ..., dim)'],
51180 description: 'Concatenate matrices. By default, the matrices are concatenated by the last dimension. The dimension on which to concatenate can be provided as last argument.',
51181 examples: ['A = [1, 2; 5, 6]', 'B = [3, 4; 7, 8]', 'concat(A, B)', 'concat(A, B, 1)', 'concat(A, B, 2)'],
51182 seealso: ['det', 'diag', 'identity', 'inv', 'ones', 'range', 'size', 'squeeze', 'subset', 'trace', 'transpose', 'zeros']
51183};
51184// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/logical/xor.js
51185var xorDocs = {
51186 name: 'xor',
51187 category: 'Logical',
51188 syntax: ['x xor y', 'xor(x, y)'],
51189 description: 'Logical exclusive or, xor. Test whether one and only one value is defined with a nonzero/nonempty value.',
51190 examples: ['true xor false', 'false xor false', 'true xor true', '0 xor 4'],
51191 seealso: ['not', 'and', 'or']
51192};
51193// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/logical/or.js
51194var orDocs = {
51195 name: 'or',
51196 category: 'Logical',
51197 syntax: ['x or y', 'or(x, y)'],
51198 description: 'Logical or. Test if at least one value is defined with a nonzero/nonempty value.',
51199 examples: ['true or false', 'false or false', '0 or 4'],
51200 seealso: ['not', 'and', 'xor']
51201};
51202// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/logical/not.js
51203var notDocs = {
51204 name: 'not',
51205 category: 'Logical',
51206 syntax: ['not x', 'not(x)'],
51207 description: 'Logical not. Flips the boolean value of given argument.',
51208 examples: ['not true', 'not false', 'not 2', 'not 0'],
51209 seealso: ['and', 'or', 'xor']
51210};
51211// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/logical/and.js
51212var andDocs = {
51213 name: 'and',
51214 category: 'Logical',
51215 syntax: ['x and y', 'and(x, y)'],
51216 description: 'Logical and. Test whether two values are both defined with a nonzero/nonempty value.',
51217 examples: ['true and false', 'true and true', '2 and 4'],
51218 seealso: ['not', 'or', 'xor']
51219};
51220// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/geometry/intersect.js
51221var intersectDocs = {
51222 name: 'intersect',
51223 category: 'Geometry',
51224 syntax: ['intersect(expr1, expr2, expr3, expr4)', 'intersect(expr1, expr2, expr3)'],
51225 description: 'Computes the intersection point of lines and/or planes.',
51226 examples: ['intersect([0, 0], [10, 10], [10, 0], [0, 10])', 'intersect([1, 0, 1], [4, -2, 2], [1, 1, 1, 6])'],
51227 seealso: []
51228};
51229// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/geometry/distance.js
51230var distanceDocs = {
51231 name: 'distance',
51232 category: 'Geometry',
51233 syntax: ['distance([x1, y1], [x2, y2])', 'distance([[x1, y1], [x2, y2])'],
51234 description: 'Calculates the Euclidean distance between two points.',
51235 examples: ['distance([0,0], [4,4])', 'distance([[0,0], [4,4]])'],
51236 seealso: []
51237};
51238// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/expression/help.js
51239var helpDocs = {
51240 name: 'help',
51241 category: 'Expression',
51242 syntax: ['help(object)', 'help(string)'],
51243 description: 'Display documentation on a function or data type.',
51244 examples: ['help(sqrt)', 'help("complex")'],
51245 seealso: []
51246};
51247// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/expression/evaluate.js
51248var evaluateDocs = {
51249 name: 'evaluate',
51250 category: 'Expression',
51251 syntax: ['evaluate(expression)', 'evaluate([expr1, expr2, expr3, ...])'],
51252 description: 'Evaluate an expression or an array with expressions.',
51253 examples: ['evaluate("2 + 3")', 'evaluate("sqrt(" + 4 + ")")'],
51254 seealso: []
51255};
51256// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/complex/im.js
51257var imDocs = {
51258 name: 'im',
51259 category: 'Complex',
51260 syntax: ['im(x)'],
51261 description: 'Get the imaginary part of a complex number.',
51262 examples: ['im(2 + 3i)', 're(2 + 3i)', 'im(-5.2i)', 'im(2.4)'],
51263 seealso: ['re', 'conj', 'abs', 'arg']
51264};
51265// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/complex/re.js
51266var reDocs = {
51267 name: 're',
51268 category: 'Complex',
51269 syntax: ['re(x)'],
51270 description: 'Get the real part of a complex number.',
51271 examples: ['re(2 + 3i)', 'im(2 + 3i)', 're(-5.2i)', 're(2.4)'],
51272 seealso: ['im', 'conj', 'abs', 'arg']
51273};
51274// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/complex/conj.js
51275var conjDocs = {
51276 name: 'conj',
51277 category: 'Complex',
51278 syntax: ['conj(x)'],
51279 description: 'Compute the complex conjugate of a complex value. If x = a+bi, the complex conjugate is a-bi.',
51280 examples: ['conj(2 + 3i)', 'conj(2 - 3i)', 'conj(-5.2i)'],
51281 seealso: ['re', 'im', 'abs', 'arg']
51282};
51283// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/complex/arg.js
51284var argDocs = {
51285 name: 'arg',
51286 category: 'Complex',
51287 syntax: ['arg(x)'],
51288 description: 'Compute the argument of a complex value. If x = a+bi, the argument is computed as atan2(b, a).',
51289 examples: ['arg(2 + 2i)', 'atan2(3, 2)', 'arg(2 + 3i)'],
51290 seealso: ['re', 'im', 'conj', 'abs']
51291};
51292// CONCATENATED MODULE: ./src/expression/embeddedDocs/core/typed.js
51293var typedDocs = {
51294 name: 'typed',
51295 category: 'Core',
51296 syntax: ['typed(signatures)', 'typed(name, signatures)'],
51297 description: 'Create a typed function.',
51298 examples: ['double = typed({ "number, number": f(x)=x+x })', 'double(2)', 'double("hello")'],
51299 seealso: []
51300};
51301// CONCATENATED MODULE: ./src/expression/embeddedDocs/core/import.js
51302var importDocs = {
51303 name: 'import',
51304 category: 'Core',
51305 syntax: ['import(functions)', 'import(functions, options)'],
51306 description: 'Import functions or constants from an object.',
51307 examples: ['import({myFn: f(x)=x^2, myConstant: 32 })', 'myFn(2)', 'myConstant'],
51308 seealso: []
51309};
51310// CONCATENATED MODULE: ./src/expression/embeddedDocs/core/config.js
51311var configDocs = {
51312 name: 'config',
51313 category: 'Core',
51314 syntax: ['config()', 'config(options)'],
51315 description: 'Get configuration or change configuration.',
51316 examples: ['config()', '1/3 + 1/4', 'config({number: "Fraction"})', '1/3 + 1/4'],
51317 seealso: []
51318};
51319// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/combinatorics/stirlingS2.js
51320var stirlingS2Docs = {
51321 name: 'stirlingS2',
51322 category: 'Combinatorics',
51323 syntax: ['stirlingS2(n, k)'],
51324 description: 'he Stirling numbers of the second kind, counts the number of ways to partition a set of n labelled objects into k nonempty unlabelled subsets. `stirlingS2` only takes integer arguments. The following condition must be enforced: k <= n. If n = k or k = 1, then s(n,k) = 1.',
51325 examples: ['stirlingS2(5, 3)'],
51326 seealso: ['bellNumbers']
51327};
51328// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/combinatorics/composition.js
51329var compositionDocs = {
51330 name: 'composition',
51331 category: 'Combinatorics',
51332 syntax: ['composition(n, k)'],
51333 description: 'The composition counts of n into k parts. composition only takes integer arguments. The following condition must be enforced: k <= n.',
51334 examples: ['composition(5, 3)'],
51335 seealso: ['combinations']
51336};
51337// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/combinatorics/catalan.js
51338var catalanDocs = {
51339 name: 'catalan',
51340 category: 'Combinatorics',
51341 syntax: ['catalan(n)'],
51342 description: 'The Catalan Numbers enumerate combinatorial structures of many different types. catalan only takes integer arguments. The following condition must be enforced: n >= 0.',
51343 examples: ['catalan(3)', 'catalan(8)'],
51344 seealso: ['bellNumbers']
51345};
51346// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/combinatorics/bellNumbers.js
51347var bellNumbersDocs = {
51348 name: 'bellNumbers',
51349 category: 'Combinatorics',
51350 syntax: ['bellNumbers(n)'],
51351 description: 'The Bell Numbers count the number of partitions of a set. A partition is a pairwise disjoint subset of S whose union is S. `bellNumbers` only takes integer arguments. The following condition must be enforced: n >= 0.',
51352 examples: ['bellNumbers(3)', 'bellNumbers(8)'],
51353 seealso: ['stirlingS2']
51354};
51355// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/bitwise/rightLogShift.js
51356var rightLogShiftDocs = {
51357 name: 'rightLogShift',
51358 category: 'Bitwise',
51359 syntax: ['x >>> y', 'rightLogShift(x, y)'],
51360 description: 'Bitwise right logical shift of a value x by y number of bits.',
51361 examples: ['8 >>> 1', '4 << 1', '-12 >>> 2'],
51362 seealso: ['bitAnd', 'bitNot', 'bitOr', 'bitXor', 'leftShift', 'rightArithShift']
51363};
51364// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/bitwise/rightArithShift.js
51365var rightArithShiftDocs = {
51366 name: 'rightArithShift',
51367 category: 'Bitwise',
51368 syntax: ['x >> y', 'rightArithShift(x, y)'],
51369 description: 'Bitwise right arithmetic shift of a value x by y number of bits.',
51370 examples: ['8 >> 1', '4 << 1', '-12 >> 2'],
51371 seealso: ['bitAnd', 'bitNot', 'bitOr', 'bitXor', 'leftShift', 'rightLogShift']
51372};
51373// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/bitwise/leftShift.js
51374var leftShiftDocs = {
51375 name: 'leftShift',
51376 category: 'Bitwise',
51377 syntax: ['x << y', 'leftShift(x, y)'],
51378 description: 'Bitwise left logical shift of a value x by y number of bits.',
51379 examples: ['4 << 1', '8 >> 1'],
51380 seealso: ['bitAnd', 'bitNot', 'bitOr', 'bitXor', 'rightArithShift', 'rightLogShift']
51381};
51382// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/bitwise/bitXor.js
51383var bitXorDocs = {
51384 name: 'bitXor',
51385 category: 'Bitwise',
51386 syntax: ['bitXor(x, y)'],
51387 description: 'Bitwise XOR operation, exclusive OR. Performs the logical exclusive OR operation on each pair of corresponding bits of the two given values. The result in each position is 1 if only the first bit is 1 or only the second bit is 1, but will be 0 if both are 0 or both are 1.',
51388 examples: ['bitOr(1, 2)', 'bitXor([2, 3, 4], 4)'],
51389 seealso: ['bitAnd', 'bitNot', 'bitOr', 'leftShift', 'rightArithShift', 'rightLogShift']
51390};
51391// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/bitwise/bitOr.js
51392var bitOrDocs = {
51393 name: 'bitOr',
51394 category: 'Bitwise',
51395 syntax: ['x | y', 'bitOr(x, y)'],
51396 description: 'Bitwise OR operation. Performs the logical inclusive OR operation on each pair of corresponding bits of the two given values. The result in each position is 1 if the first bit is 1 or the second bit is 1 or both bits are 1, otherwise, the result is 0.',
51397 examples: ['5 | 3', 'bitOr([1, 2, 3], 4)'],
51398 seealso: ['bitAnd', 'bitNot', 'bitXor', 'leftShift', 'rightArithShift', 'rightLogShift']
51399};
51400// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/bitwise/bitNot.js
51401var bitNotDocs = {
51402 name: 'bitNot',
51403 category: 'Bitwise',
51404 syntax: ['~x', 'bitNot(x)'],
51405 description: 'Bitwise NOT operation. Performs a logical negation on each bit of the given value. Bits that are 0 become 1, and those that are 1 become 0.',
51406 examples: ['~1', '~2', 'bitNot([2, -3, 4])'],
51407 seealso: ['bitAnd', 'bitOr', 'bitXor', 'leftShift', 'rightArithShift', 'rightLogShift']
51408};
51409// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/bitwise/bitAnd.js
51410var bitAndDocs = {
51411 name: 'bitAnd',
51412 category: 'Bitwise',
51413 syntax: ['x & y', 'bitAnd(x, y)'],
51414 description: 'Bitwise AND operation. Performs the logical AND operation on each pair of the corresponding bits of the two given values by multiplying them. If both bits in the compared position are 1, the bit in the resulting binary representation is 1, otherwise, the result is 0',
51415 examples: ['5 & 3', 'bitAnd(53, 131)', '[1, 12, 31] & 42'],
51416 seealso: ['bitNot', 'bitOr', 'bitXor', 'leftShift', 'rightArithShift', 'rightLogShift']
51417};
51418// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/arithmetic/xgcd.js
51419var xgcdDocs = {
51420 name: 'xgcd',
51421 category: 'Arithmetic',
51422 syntax: ['xgcd(a, b)'],
51423 description: 'Calculate the extended greatest common divisor for two values. The result is an array [d, x, y] with 3 entries, where d is the greatest common divisor, and d = x * a + y * b.',
51424 examples: ['xgcd(8, 12)', 'gcd(8, 12)', 'xgcd(36163, 21199)'],
51425 seealso: ['gcd', 'lcm']
51426};
51427// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/arithmetic/unaryPlus.js
51428var unaryPlusDocs = {
51429 name: 'unaryPlus',
51430 category: 'Operators',
51431 syntax: ['+x', 'unaryPlus(x)'],
51432 description: 'Converts booleans and strings to numbers.',
51433 examples: ['+true', '+"2"'],
51434 seealso: ['add', 'subtract', 'unaryMinus']
51435};
51436// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/arithmetic/unaryMinus.js
51437var unaryMinusDocs = {
51438 name: 'unaryMinus',
51439 category: 'Operators',
51440 syntax: ['-x', 'unaryMinus(x)'],
51441 description: 'Inverse the sign of a value. Converts booleans and strings to numbers.',
51442 examples: ['-4.5', '-(-5.6)', '-"22"'],
51443 seealso: ['add', 'subtract', 'unaryPlus']
51444};
51445// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/arithmetic/square.js
51446var squareDocs = {
51447 name: 'square',
51448 category: 'Arithmetic',
51449 syntax: ['square(x)'],
51450 description: 'Compute the square of a value. The square of x is x * x.',
51451 examples: ['square(3)', 'sqrt(9)', '3^2', '3 * 3'],
51452 seealso: ['multiply', 'pow', 'sqrt', 'cube']
51453};
51454// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/arithmetic/sqrtm.js
51455var sqrtmDocs = {
51456 name: 'sqrtm',
51457 category: 'Arithmetic',
51458 syntax: ['sqrtm(x)'],
51459 description: 'Calculate the principal square root of a square matrix. The principal square root matrix `X` of another matrix `A` is such that `X * X = A`.',
51460 examples: ['sqrtm([[1, 2], [3, 4]])'],
51461 seealso: ['sqrt', 'abs', 'square', 'multiply']
51462};
51463// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/arithmetic/sqrt.js
51464var sqrtDocs = {
51465 name: 'sqrt',
51466 category: 'Arithmetic',
51467 syntax: ['sqrt(x)'],
51468 description: 'Compute the square root value. If x = y * y, then y is the square root of x.',
51469 examples: ['sqrt(25)', '5 * 5', 'sqrt(-1)'],
51470 seealso: ['square', 'sqrtm', 'multiply', 'nthRoot', 'nthRoots', 'pow']
51471};
51472// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/arithmetic/sign.js
51473var signDocs = {
51474 name: 'sign',
51475 category: 'Arithmetic',
51476 syntax: ['sign(x)'],
51477 description: 'Compute the sign of a value. The sign of a value x is 1 when x>1, -1 when x<0, and 0 when x=0.',
51478 examples: ['sign(3.5)', 'sign(-4.2)', 'sign(0)'],
51479 seealso: ['abs']
51480};
51481// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/arithmetic/round.js
51482var roundDocs = {
51483 name: 'round',
51484 category: 'Arithmetic',
51485 syntax: ['round(x)', 'round(x, n)'],
51486 description: 'round a value towards the nearest integer.If x is complex, both real and imaginary part are rounded towards the nearest integer. When n is specified, the value is rounded to n decimals.',
51487 examples: ['round(3.2)', 'round(3.8)', 'round(-4.2)', 'round(-4.8)', 'round(pi, 3)', 'round(123.45678, 2)'],
51488 seealso: ['ceil', 'floor', 'fix']
51489};
51490// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/arithmetic/pow.js
51491var powDocs = {
51492 name: 'pow',
51493 category: 'Operators',
51494 syntax: ['x ^ y', 'pow(x, y)'],
51495 description: 'Calculates the power of x to y, x^y.',
51496 examples: ['2^3', '2*2*2', '1 + e ^ (pi * i)'],
51497 seealso: ['multiply', 'nthRoot', 'nthRoots', 'sqrt']
51498};
51499// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/arithmetic/nthRoots.js
51500var nthRootsDocs = {
51501 name: 'nthRoots',
51502 category: 'Arithmetic',
51503 syntax: ['nthRoots(A)', 'nthRoots(A, root)'],
51504 description: '' + 'Calculate the nth roots of a value. ' + 'An nth root of a positive real number A, ' + 'is a positive real solution of the equation "x^root = A". ' + 'This function returns an array of complex values.',
51505 examples: ['nthRoots(1)', 'nthRoots(1, 3)'],
51506 seealso: ['sqrt', 'pow', 'nthRoot']
51507};
51508// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/arithmetic/nthRoot.js
51509var nthRootDocs = {
51510 name: 'nthRoot',
51511 category: 'Arithmetic',
51512 syntax: ['nthRoot(a)', 'nthRoot(a, root)'],
51513 description: 'Calculate the nth root of a value. ' + 'The principal nth root of a positive real number A, ' + 'is the positive real solution of the equation "x^root = A".',
51514 examples: ['4 ^ 3', 'nthRoot(64, 3)', 'nthRoot(9, 2)', 'sqrt(9)'],
51515 seealso: ['nthRoots', 'pow', 'sqrt']
51516};
51517// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/arithmetic/norm.js
51518var normDocs = {
51519 name: 'norm',
51520 category: 'Arithmetic',
51521 syntax: ['norm(x)', 'norm(x, p)'],
51522 description: 'Calculate the norm of a number, vector or matrix.',
51523 examples: ['abs(-3.5)', 'norm(-3.5)', 'norm(3 - 4i)', 'norm([1, 2, -3], Infinity)', 'norm([1, 2, -3], -Infinity)', 'norm([3, 4], 2)', 'norm([[1, 2], [3, 4]], 1)', 'norm([[1, 2], [3, 4]], "inf")', 'norm([[1, 2], [3, 4]], "fro")']
51524};
51525// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/arithmetic/multiply.js
51526var multiplyDocs = {
51527 name: 'multiply',
51528 category: 'Operators',
51529 syntax: ['x * y', 'multiply(x, y)'],
51530 description: 'multiply two values.',
51531 examples: ['a = 2.1 * 3.4', 'a / 3.4', '2 * 3 + 4', '2 * (3 + 4)', '3 * 2.1 km'],
51532 seealso: ['divide']
51533};
51534// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/arithmetic/mod.js
51535var modDocs = {
51536 name: 'mod',
51537 category: 'Operators',
51538 syntax: ['x % y', 'x mod y', 'mod(x, y)'],
51539 description: 'Calculates the modulus, the remainder of an integer division.',
51540 examples: ['7 % 3', '11 % 2', '10 mod 4', 'isOdd(x) = x % 2', 'isOdd(2)', 'isOdd(3)'],
51541 seealso: ['divide']
51542};
51543// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/arithmetic/log10.js
51544var log10Docs = {
51545 name: 'log10',
51546 category: 'Arithmetic',
51547 syntax: ['log10(x)'],
51548 description: 'Compute the 10-base logarithm of a value.',
51549 examples: ['log10(0.00001)', 'log10(10000)', '10 ^ 4', 'log(10000) / log(10)', 'log(10000, 10)'],
51550 seealso: ['exp', 'log']
51551};
51552// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/arithmetic/log1p.js
51553var log1pDocs = {
51554 name: 'log1p',
51555 category: 'Arithmetic',
51556 syntax: ['log1p(x)', 'log1p(x, base)'],
51557 description: 'Calculate the logarithm of a `value+1`',
51558 examples: ['log1p(2.5)', 'exp(log1p(1.4))', 'pow(10, 4)', 'log1p(9999, 10)', 'log1p(9999) / log(10)'],
51559 seealso: ['exp', 'log', 'log2', 'log10']
51560};
51561// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/arithmetic/log2.js
51562var log2Docs = {
51563 name: 'log2',
51564 category: 'Arithmetic',
51565 syntax: ['log2(x)'],
51566 description: 'Calculate the 2-base of a value. This is the same as calculating `log(x, 2)`.',
51567 examples: ['log2(0.03125)', 'log2(16)', 'log2(16) / log2(2)', 'pow(2, 4)'],
51568 seealso: ['exp', 'log1p', 'log', 'log10']
51569};
51570// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/arithmetic/log.js
51571var logDocs = {
51572 name: 'log',
51573 category: 'Arithmetic',
51574 syntax: ['log(x)', 'log(x, base)'],
51575 description: 'Compute the logarithm of a value. If no base is provided, the natural logarithm of x is calculated. If base if provided, the logarithm is calculated for the specified base. log(x, base) is defined as log(x) / log(base).',
51576 examples: ['log(3.5)', 'a = log(2.4)', 'exp(a)', '10 ^ 4', 'log(10000, 10)', 'log(10000) / log(10)', 'b = log(1024, 2)', '2 ^ b'],
51577 seealso: ['exp', 'log1p', 'log2', 'log10']
51578};
51579// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/arithmetic/lcm.js
51580var lcmDocs = {
51581 name: 'lcm',
51582 category: 'Arithmetic',
51583 syntax: ['lcm(x, y)'],
51584 description: 'Compute the least common multiple.',
51585 examples: ['lcm(4, 6)', 'lcm(6, 21)', 'lcm(6, 21, 5)'],
51586 seealso: ['gcd']
51587};
51588// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/arithmetic/hypot.js
51589var hypotDocs = {
51590 name: 'hypot',
51591 category: 'Arithmetic',
51592 syntax: ['hypot(a, b, c, ...)', 'hypot([a, b, c, ...])'],
51593 description: 'Calculate the hypotenusa of a list with values. ',
51594 examples: ['hypot(3, 4)', 'sqrt(3^2 + 4^2)', 'hypot(-2)', 'hypot([3, 4, 5])'],
51595 seealso: ['abs', 'norm']
51596};
51597// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/arithmetic/gcd.js
51598var gcdDocs = {
51599 name: 'gcd',
51600 category: 'Arithmetic',
51601 syntax: ['gcd(a, b)', 'gcd(a, b, c, ...)'],
51602 description: 'Compute the greatest common divisor.',
51603 examples: ['gcd(8, 12)', 'gcd(-4, 6)', 'gcd(25, 15, -10)'],
51604 seealso: ['lcm', 'xgcd']
51605};
51606// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/arithmetic/floor.js
51607var floorDocs = {
51608 name: 'floor',
51609 category: 'Arithmetic',
51610 syntax: ['floor(x)'],
51611 description: 'Round a value towards minus infinity.If x is complex, both real and imaginary part are rounded towards minus infinity.',
51612 examples: ['floor(3.2)', 'floor(3.8)', 'floor(-4.2)'],
51613 seealso: ['ceil', 'fix', 'round']
51614};
51615// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/arithmetic/fix.js
51616var fixDocs = {
51617 name: 'fix',
51618 category: 'Arithmetic',
51619 syntax: ['fix(x)'],
51620 description: 'Round a value towards zero. If x is complex, both real and imaginary part are rounded towards zero.',
51621 examples: ['fix(3.2)', 'fix(3.8)', 'fix(-4.2)', 'fix(-4.8)'],
51622 seealso: ['ceil', 'floor', 'round']
51623};
51624// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/arithmetic/expm1.js
51625var expm1Docs = {
51626 name: 'expm1',
51627 category: 'Arithmetic',
51628 syntax: ['expm1(x)'],
51629 description: 'Calculate the value of subtracting 1 from the exponential value.',
51630 examples: ['expm1(2)', 'pow(e, 2) - 1', 'log(expm1(2) + 1)'],
51631 seealso: ['exp', 'pow', 'log']
51632};
51633// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/arithmetic/expm.js
51634var expmDocs = {
51635 name: 'expm',
51636 category: 'Arithmetic',
51637 syntax: ['exp(x)'],
51638 description: 'Compute the matrix exponential, expm(A) = e^A. ' + 'The matrix must be square. ' + 'Not to be confused with exp(a), which performs element-wise exponentiation.',
51639 examples: ['expm([[0,2],[0,0]])'],
51640 seealso: ['exp']
51641};
51642// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/arithmetic/exp.js
51643var expDocs = {
51644 name: 'exp',
51645 category: 'Arithmetic',
51646 syntax: ['exp(x)'],
51647 description: 'Calculate the exponent of a value.',
51648 examples: ['exp(1.3)', 'e ^ 1.3', 'log(exp(1.3))', 'x = 2.4', '(exp(i*x) == cos(x) + i*sin(x)) # Euler\'s formula'],
51649 seealso: ['expm', 'expm1', 'pow', 'log']
51650};
51651// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/arithmetic/dotMultiply.js
51652var dotMultiplyDocs = {
51653 name: 'dotMultiply',
51654 category: 'Operators',
51655 syntax: ['x .* y', 'dotMultiply(x, y)'],
51656 description: 'Multiply two values element wise.',
51657 examples: ['a = [1, 2, 3; 4, 5, 6]', 'b = [2, 1, 1; 3, 2, 5]', 'a .* b'],
51658 seealso: ['multiply', 'divide', 'dotDivide']
51659};
51660// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/arithmetic/dotDivide.js
51661var dotDivideDocs = {
51662 name: 'dotDivide',
51663 category: 'Operators',
51664 syntax: ['x ./ y', 'dotDivide(x, y)'],
51665 description: 'Divide two values element wise.',
51666 examples: ['a = [1, 2, 3; 4, 5, 6]', 'b = [2, 1, 1; 3, 2, 5]', 'a ./ b'],
51667 seealso: ['multiply', 'dotMultiply', 'divide']
51668};
51669// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/arithmetic/divide.js
51670var divideDocs = {
51671 name: 'divide',
51672 category: 'Operators',
51673 syntax: ['x / y', 'divide(x, y)'],
51674 description: 'Divide two values.',
51675 examples: ['a = 2 / 3', 'a * 3', '4.5 / 2', '3 + 4 / 2', '(3 + 4) / 2', '18 km / 4.5'],
51676 seealso: ['multiply']
51677};
51678// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/arithmetic/cube.js
51679var cubeDocs = {
51680 name: 'cube',
51681 category: 'Arithmetic',
51682 syntax: ['cube(x)'],
51683 description: 'Compute the cube of a value. The cube of x is x * x * x.',
51684 examples: ['cube(2)', '2^3', '2 * 2 * 2'],
51685 seealso: ['multiply', 'square', 'pow']
51686};
51687// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/arithmetic/ceil.js
51688var ceilDocs = {
51689 name: 'ceil',
51690 category: 'Arithmetic',
51691 syntax: ['ceil(x)'],
51692 description: 'Round a value towards plus infinity. If x is complex, both real and imaginary part are rounded towards plus infinity.',
51693 examples: ['ceil(3.2)', 'ceil(3.8)', 'ceil(-4.2)'],
51694 seealso: ['floor', 'fix', 'round']
51695};
51696// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/arithmetic/cbrt.js
51697var cbrtDocs = {
51698 name: 'cbrt',
51699 category: 'Arithmetic',
51700 syntax: ['cbrt(x)', 'cbrt(x, allRoots)'],
51701 description: 'Compute the cubic root value. If x = y * y * y, then y is the cubic root of x. When `x` is a number or complex number, an optional second argument `allRoots` can be provided to return all three cubic roots. If not provided, the principal root is returned',
51702 examples: ['cbrt(64)', 'cube(4)', 'cbrt(-8)', 'cbrt(2 + 3i)', 'cbrt(8i)', 'cbrt(8i, true)', 'cbrt(27 m^3)'],
51703 seealso: ['square', 'sqrt', 'cube', 'multiply']
51704};
51705// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/arithmetic/add.js
51706var addDocs = {
51707 name: 'add',
51708 category: 'Operators',
51709 syntax: ['x + y', 'add(x, y)'],
51710 description: 'Add two values.',
51711 examples: ['a = 2.1 + 3.6', 'a - 3.6', '3 + 2i', '3 cm + 2 inch', '"2.3" + "4"'],
51712 seealso: ['subtract']
51713};
51714// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/arithmetic/abs.js
51715var absDocs = {
51716 name: 'abs',
51717 category: 'Arithmetic',
51718 syntax: ['abs(x)'],
51719 description: 'Compute the absolute value.',
51720 examples: ['abs(3.5)', 'abs(-4.2)'],
51721 seealso: ['sign']
51722};
51723// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/algebra/qr.js
51724var qrDocs = {
51725 name: 'qr',
51726 category: 'Algebra',
51727 syntax: ['qr(A)'],
51728 description: 'Calculates 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.',
51729 examples: ['qr([[1, -1, 4], [1, 4, -2], [1, 4, 2], [1, -1, 0]])'],
51730 seealso: ['lup', 'slu', 'matrix']
51731};
51732// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/algebra/usolve.js
51733var usolveDocs = {
51734 name: 'usolve',
51735 category: 'Algebra',
51736 syntax: ['x=usolve(U, b)'],
51737 description: 'Solves the linear system U * x = b where U is an [n x n] upper triangular matrix and b is a [n] column vector.',
51738 examples: ['x=usolve(sparse([1, 1, 1, 1; 0, 1, 1, 1; 0, 0, 1, 1; 0, 0, 0, 1]), [1; 2; 3; 4])'],
51739 seealso: ['lup', 'lusolve', 'lsolve', 'matrix', 'sparse']
51740};
51741// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/algebra/slu.js
51742var sluDocs = {
51743 name: 'slu',
51744 category: 'Algebra',
51745 syntax: ['slu(A, order, threshold)'],
51746 description: 'Calculate the Matrix LU decomposition with full pivoting. Matrix A is decomposed in two matrices (L, U) and two permutation vectors (pinv, q) where P * A * Q = L * U',
51747 examples: ['slu(sparse([4.5, 0, 3.2, 0; 3.1, 2.9, 0, 0.9; 0, 1.7, 3, 0; 3.5, 0.4, 0, 1]), 1, 0.001)'],
51748 seealso: ['lusolve', 'lsolve', 'usolve', 'matrix', 'sparse', 'lup', 'qr']
51749};
51750// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/algebra/rationalize.js
51751var rationalizeDocs = {
51752 name: 'rationalize',
51753 category: 'Algebra',
51754 syntax: ['rationalize(expr)', 'rationalize(expr, scope)', 'rationalize(expr, scope, detailed)'],
51755 description: 'Transform a rationalizable expression in a rational fraction. If rational fraction is one variable polynomial then converts the numerator and denominator in canonical form, with decreasing exponents, returning the coefficients of numerator.',
51756 examples: ['rationalize("2x/y - y/(x+1)")', 'rationalize("2x/y - y/(x+1)", true)'],
51757 seealso: ['simplify']
51758};
51759// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/algebra/simplify.js
51760var simplifyDocs = {
51761 name: 'simplify',
51762 category: 'Algebra',
51763 syntax: ['simplify(expr)', 'simplify(expr, rules)'],
51764 description: 'Simplify an expression tree.',
51765 examples: ['simplify("3 + 2 / 4")', 'simplify("2x + x")', 'f = parse("x * (x + 2 + x)")', 'simplified = simplify(f)', 'simplified.evaluate({x: 2})'],
51766 seealso: ['derivative', 'parse', 'evaluate']
51767};
51768// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/algebra/lup.js
51769var lupDocs = {
51770 name: 'lup',
51771 category: 'Algebra',
51772 syntax: ['lup(m)'],
51773 description: 'Calculate the Matrix LU decomposition with partial pivoting. Matrix A is decomposed in three matrices (L, U, P) where P * A = L * U',
51774 examples: ['lup([[2, 1], [1, 4]])', 'lup(matrix([[2, 1], [1, 4]]))', 'lup(sparse([[2, 1], [1, 4]]))'],
51775 seealso: ['lusolve', 'lsolve', 'usolve', 'matrix', 'sparse', 'slu', 'qr']
51776};
51777// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/algebra/lsolve.js
51778var lsolveDocs = {
51779 name: 'lsolve',
51780 category: 'Algebra',
51781 syntax: ['x=lsolve(L, b)'],
51782 description: 'Solves the linear system L * x = b where L is an [n x n] lower triangular matrix and b is a [n] column vector.',
51783 examples: ['a = [-2, 3; 2, 1]', 'b = [11, 9]', 'x = lsolve(a, b)'],
51784 seealso: ['lup', 'lusolve', 'usolve', 'matrix', 'sparse']
51785};
51786// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/algebra/derivative.js
51787var derivativeDocs = {
51788 name: 'derivative',
51789 category: 'Algebra',
51790 syntax: ['derivative(expr, variable)', 'derivative(expr, variable, {simplify: boolean})'],
51791 description: 'Takes the derivative of an expression expressed in parser Nodes. The derivative will be taken over the supplied variable in the second parameter. If there are multiple variables in the expression, it will return a partial derivative.',
51792 examples: ['derivative("2x^3", "x")', 'derivative("2x^3", "x", {simplify: false})', 'derivative("2x^2 + 3x + 4", "x")', 'derivative("sin(2x)", "x")', 'f = parse("x^2 + x")', 'x = parse("x")', 'df = derivative(f, x)', 'df.evaluate({x: 3})'],
51793 seealso: ['simplify', 'parse', 'evaluate']
51794};
51795// CONCATENATED MODULE: ./src/expression/embeddedDocs/constants/version.js
51796var versionDocs = {
51797 name: 'version',
51798 category: 'Constants',
51799 syntax: ['version'],
51800 description: 'A string with the version number of math.js',
51801 examples: ['version'],
51802 seealso: []
51803};
51804// CONCATENATED MODULE: ./src/expression/embeddedDocs/constants/true.js
51805var trueDocs = {
51806 name: 'true',
51807 category: 'Constants',
51808 syntax: ['true'],
51809 description: 'Boolean value true',
51810 examples: ['true'],
51811 seealso: ['false']
51812};
51813// CONCATENATED MODULE: ./src/expression/embeddedDocs/constants/tau.js
51814var tauDocs = {
51815 name: 'tau',
51816 category: 'Constants',
51817 syntax: ['tau'],
51818 description: 'Tau is the ratio constant of a circle\'s circumference to radius, equal to 2 * pi, approximately 6.2832.',
51819 examples: ['tau', '2 * pi'],
51820 seealso: ['pi']
51821};
51822// CONCATENATED MODULE: ./src/expression/embeddedDocs/constants/SQRT2.js
51823var SQRT2Docs = {
51824 name: 'SQRT2',
51825 category: 'Constants',
51826 syntax: ['SQRT2'],
51827 description: 'Returns the square root of 2, approximately equal to 1.414',
51828 examples: ['SQRT2', 'sqrt(2)'],
51829 seealso: []
51830};
51831// CONCATENATED MODULE: ./src/expression/embeddedDocs/constants/SQRT1_2.js
51832var SQRT12Docs = {
51833 name: 'SQRT1_2',
51834 category: 'Constants',
51835 syntax: ['SQRT1_2'],
51836 description: 'Returns the square root of 1/2, approximately equal to 0.707',
51837 examples: ['SQRT1_2', 'sqrt(1/2)'],
51838 seealso: []
51839};
51840// CONCATENATED MODULE: ./src/expression/embeddedDocs/constants/phi.js
51841var phiDocs = {
51842 name: 'phi',
51843 category: 'Constants',
51844 syntax: ['phi'],
51845 description: 'Phi is the golden ratio. Two quantities are in the golden ratio if their ratio is the same as the ratio of their sum to the larger of the two quantities. Phi is defined as `(1 + sqrt(5)) / 2` and is approximately 1.618034...',
51846 examples: ['phi'],
51847 seealso: []
51848};
51849// CONCATENATED MODULE: ./src/expression/embeddedDocs/constants/pi.js
51850var piDocs = {
51851 name: 'pi',
51852 category: 'Constants',
51853 syntax: ['pi'],
51854 description: 'The number pi is a mathematical constant that is the ratio of a circle\'s circumference to its diameter, and is approximately equal to 3.14159',
51855 examples: ['pi', 'sin(pi/2)'],
51856 seealso: ['tau']
51857};
51858// CONCATENATED MODULE: ./src/expression/embeddedDocs/constants/null.js
51859var nullDocs = {
51860 name: 'null',
51861 category: 'Constants',
51862 syntax: ['null'],
51863 description: 'Value null',
51864 examples: ['null'],
51865 seealso: ['true', 'false']
51866};
51867// CONCATENATED MODULE: ./src/expression/embeddedDocs/constants/NaN.js
51868var NaNDocs = {
51869 name: 'NaN',
51870 category: 'Constants',
51871 syntax: ['NaN'],
51872 description: 'Not a number',
51873 examples: ['NaN', '0 / 0'],
51874 seealso: []
51875};
51876// CONCATENATED MODULE: ./src/expression/embeddedDocs/constants/LOG10E.js
51877var LOG10EDocs = {
51878 name: 'LOG10E',
51879 category: 'Constants',
51880 syntax: ['LOG10E'],
51881 description: 'Returns the base-10 logarithm of E, approximately equal to 0.434',
51882 examples: ['LOG10E', 'log(e, 10)'],
51883 seealso: []
51884};
51885// CONCATENATED MODULE: ./src/expression/embeddedDocs/constants/LOG2E.js
51886var LOG2EDocs = {
51887 name: 'LOG2E',
51888 category: 'Constants',
51889 syntax: ['LOG2E'],
51890 description: 'Returns the base-2 logarithm of E, approximately equal to 1.442',
51891 examples: ['LOG2E', 'log(e, 2)'],
51892 seealso: []
51893};
51894// CONCATENATED MODULE: ./src/expression/embeddedDocs/constants/LN10.js
51895var LN10Docs = {
51896 name: 'LN10',
51897 category: 'Constants',
51898 syntax: ['LN10'],
51899 description: 'Returns the natural logarithm of 10, approximately equal to 2.302',
51900 examples: ['LN10', 'log(10)'],
51901 seealso: []
51902};
51903// CONCATENATED MODULE: ./src/expression/embeddedDocs/constants/LN2.js
51904var LN2Docs = {
51905 name: 'LN2',
51906 category: 'Constants',
51907 syntax: ['LN2'],
51908 description: 'Returns the natural logarithm of 2, approximately equal to 0.693',
51909 examples: ['LN2', 'log(2)'],
51910 seealso: []
51911};
51912// CONCATENATED MODULE: ./src/expression/embeddedDocs/constants/Infinity.js
51913var InfinityDocs = {
51914 name: 'Infinity',
51915 category: 'Constants',
51916 syntax: ['Infinity'],
51917 description: 'Infinity, a number which is larger than the maximum number that can be handled by a floating point number.',
51918 examples: ['Infinity', '1 / 0'],
51919 seealso: []
51920};
51921// CONCATENATED MODULE: ./src/expression/embeddedDocs/constants/i.js
51922var iDocs = {
51923 name: 'i',
51924 category: 'Constants',
51925 syntax: ['i'],
51926 description: 'Imaginary unit, defined as i*i=-1. A complex number is described as a + b*i, where a is the real part, and b is the imaginary part.',
51927 examples: ['i', 'i * i', 'sqrt(-1)'],
51928 seealso: []
51929};
51930// CONCATENATED MODULE: ./src/expression/embeddedDocs/constants/false.js
51931var falseDocs = {
51932 name: 'false',
51933 category: 'Constants',
51934 syntax: ['false'],
51935 description: 'Boolean value false',
51936 examples: ['false'],
51937 seealso: ['true']
51938};
51939// CONCATENATED MODULE: ./src/expression/embeddedDocs/constants/e.js
51940var eDocs = {
51941 name: 'e',
51942 category: 'Constants',
51943 syntax: ['e'],
51944 description: 'Euler\'s number, the base of the natural logarithm. Approximately equal to 2.71828',
51945 examples: ['e', 'e ^ 2', 'exp(2)', 'log(e)'],
51946 seealso: ['exp']
51947};
51948// CONCATENATED MODULE: ./src/expression/embeddedDocs/construction/unit.js
51949var unitDocs = {
51950 name: 'unit',
51951 category: 'Construction',
51952 syntax: ['value unit', 'unit(value, unit)', 'unit(string)'],
51953 description: 'Create a unit.',
51954 examples: ['5.5 mm', '3 inch', 'unit(7.1, "kilogram")', 'unit("23 deg")'],
51955 seealso: ['bignumber', 'boolean', 'complex', 'index', 'matrix', 'number', 'string']
51956};
51957// CONCATENATED MODULE: ./src/expression/embeddedDocs/construction/string.js
51958var stringDocs = {
51959 name: 'string',
51960 category: 'Construction',
51961 syntax: ['"text"', 'string(x)'],
51962 description: 'Create a string or convert a value to a string',
51963 examples: ['"Hello World!"', 'string(4.2)', 'string(3 + 2i)'],
51964 seealso: ['bignumber', 'boolean', 'complex', 'index', 'matrix', 'number', 'unit']
51965};
51966// CONCATENATED MODULE: ./src/expression/embeddedDocs/construction/splitUnit.js
51967var splitUnitDocs = {
51968 name: 'splitUnit',
51969 category: 'Construction',
51970 syntax: ['splitUnit(unit: Unit, parts: Unit[])'],
51971 description: 'Split a unit in an array of units whose sum is equal to the original unit.',
51972 examples: ['splitUnit(1 m, ["feet", "inch"])'],
51973 seealso: ['unit', 'createUnit']
51974};
51975// CONCATENATED MODULE: ./src/expression/embeddedDocs/construction/sparse.js
51976var sparseDocs = {
51977 name: 'sparse',
51978 category: 'Construction',
51979 syntax: ['sparse()', 'sparse([a1, b1, ...; a1, b2, ...])', 'sparse([a1, b1, ...; a1, b2, ...], "number")'],
51980 description: 'Create a sparse matrix.',
51981 examples: ['sparse()', 'sparse([3, 4; 5, 6])', 'sparse([3, 0; 5, 0], "number")'],
51982 seealso: ['bignumber', 'boolean', 'complex', 'index', 'number', 'string', 'unit', 'matrix']
51983};
51984// CONCATENATED MODULE: ./src/expression/embeddedDocs/construction/number.js
51985var numberDocs = {
51986 name: 'number',
51987 category: 'Construction',
51988 syntax: ['x', 'number(x)', 'number(unit, valuelessUnit)'],
51989 description: 'Create a number or convert a string or boolean into a number.',
51990 examples: ['2', '2e3', '4.05', 'number(2)', 'number("7.2")', 'number(true)', 'number([true, false, true, true])', 'number(unit("52cm"), "m")'],
51991 seealso: ['bignumber', 'boolean', 'complex', 'fraction', 'index', 'matrix', 'string', 'unit']
51992};
51993// CONCATENATED MODULE: ./src/expression/embeddedDocs/construction/matrix.js
51994var matrixDocs = {
51995 name: 'matrix',
51996 category: 'Construction',
51997 syntax: ['[]', '[a1, b1, ...; a2, b2, ...]', 'matrix()', 'matrix("dense")', 'matrix([...])'],
51998 description: 'Create a matrix.',
51999 examples: ['[]', '[1, 2, 3]', '[1, 2, 3; 4, 5, 6]', 'matrix()', 'matrix([3, 4])', 'matrix([3, 4; 5, 6], "sparse")', 'matrix([3, 4; 5, 6], "sparse", "number")'],
52000 seealso: ['bignumber', 'boolean', 'complex', 'index', 'number', 'string', 'unit', 'sparse']
52001};
52002// CONCATENATED MODULE: ./src/expression/embeddedDocs/construction/index.js
52003var indexDocs = {
52004 name: 'index',
52005 category: 'Construction',
52006 syntax: ['[start]', '[start:end]', '[start:step:end]', '[start1, start 2, ...]', '[start1:end1, start2:end2, ...]', '[start1:step1:end1, start2:step2:end2, ...]'],
52007 description: 'Create an index to get or replace a subset of a matrix',
52008 examples: ['[]', '[1, 2, 3]', 'A = [1, 2, 3; 4, 5, 6]', 'A[1, :]', 'A[1, 2] = 50', 'A[0:2, 0:2] = ones(2, 2)'],
52009 seealso: ['bignumber', 'boolean', 'complex', 'matrix,', 'number', 'range', 'string', 'unit']
52010};
52011// CONCATENATED MODULE: ./src/expression/embeddedDocs/construction/fraction.js
52012var fractionDocs = {
52013 name: 'fraction',
52014 category: 'Construction',
52015 syntax: ['fraction(num)', 'fraction(num,den)'],
52016 description: 'Create a fraction from a number or from a numerator and denominator.',
52017 examples: ['fraction(0.125)', 'fraction(1, 3) + fraction(2, 5)'],
52018 seealso: ['bignumber', 'boolean', 'complex', 'index', 'matrix', 'string', 'unit']
52019};
52020// CONCATENATED MODULE: ./src/expression/embeddedDocs/construction/createUnit.js
52021var createUnitDocs = {
52022 name: 'createUnit',
52023 category: 'Construction',
52024 syntax: ['createUnit(definitions)', 'createUnit(name, definition)'],
52025 description: 'Create a user-defined unit and register it with the Unit type.',
52026 examples: ['createUnit("foo")', 'createUnit("knot", {definition: "0.514444444 m/s", aliases: ["knots", "kt", "kts"]})', 'createUnit("mph", "1 mile/hour")'],
52027 seealso: ['unit', 'splitUnit']
52028};
52029// CONCATENATED MODULE: ./src/expression/embeddedDocs/construction/complex.js
52030var complexDocs = {
52031 name: 'complex',
52032 category: 'Construction',
52033 syntax: ['complex()', 'complex(re, im)', 'complex(string)'],
52034 description: 'Create a complex number.',
52035 examples: ['complex()', 'complex(2, 3)', 'complex("7 - 2i")'],
52036 seealso: ['bignumber', 'boolean', 'index', 'matrix', 'number', 'string', 'unit']
52037};
52038// CONCATENATED MODULE: ./src/expression/embeddedDocs/construction/boolean.js
52039var booleanDocs = {
52040 name: 'boolean',
52041 category: 'Construction',
52042 syntax: ['x', 'boolean(x)'],
52043 description: 'Convert a string or number into a boolean.',
52044 examples: ['boolean(0)', 'boolean(1)', 'boolean(3)', 'boolean("true")', 'boolean("false")', 'boolean([1, 0, 1, 1])'],
52045 seealso: ['bignumber', 'complex', 'index', 'matrix', 'number', 'string', 'unit']
52046};
52047// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/arithmetic/dotPow.js
52048var dotPowDocs = {
52049 name: 'dotPow',
52050 category: 'Operators',
52051 syntax: ['x .^ y', 'dotPow(x, y)'],
52052 description: 'Calculates the power of x to y element wise.',
52053 examples: ['a = [1, 2, 3; 4, 5, 6]', 'a .^ 2'],
52054 seealso: ['pow']
52055};
52056// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/algebra/lusolve.js
52057var lusolveDocs = {
52058 name: 'lusolve',
52059 category: 'Algebra',
52060 syntax: ['x=lusolve(A, b)', 'x=lusolve(lu, b)'],
52061 description: 'Solves the linear system A * x = b where A is an [n x n] matrix and b is a [n] column vector.',
52062 examples: ['a = [-2, 3; 2, 1]', 'b = [11, 9]', 'x = lusolve(a, b)'],
52063 seealso: ['lup', 'slu', 'lsolve', 'usolve', 'matrix', 'sparse']
52064};
52065// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/arithmetic/subtract.js
52066var subtractDocs = {
52067 name: 'subtract',
52068 category: 'Operators',
52069 syntax: ['x - y', 'subtract(x, y)'],
52070 description: 'subtract two values.',
52071 examples: ['a = 5.3 - 2', 'a + 2', '2/3 - 1/6', '2 * 3 - 3', '2.1 km - 500m'],
52072 seealso: ['add']
52073};
52074// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/statistics/variance.js
52075var varianceDocs = {
52076 name: 'variance',
52077 category: 'Statistics',
52078 syntax: ['variance(a, b, c, ...)', 'variance(A)', 'variance(A, normalization)'],
52079 description: 'Compute the variance of all values. Optional parameter normalization can be "unbiased" (default), "uncorrected", or "biased".',
52080 examples: ['variance(2, 4, 6)', 'variance([2, 4, 6, 8])', 'variance([2, 4, 6, 8], "uncorrected")', 'variance([2, 4, 6, 8], "biased")', 'variance([1, 2, 3; 4, 5, 6])'],
52081 seealso: ['max', 'mean', 'min', 'median', 'min', 'prod', 'std', 'sum']
52082};
52083// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/trigonometry/sin.js
52084var sinDocs = {
52085 name: 'sin',
52086 category: 'Trigonometry',
52087 syntax: ['sin(x)'],
52088 description: 'Compute the sine of x in radians.',
52089 examples: ['sin(2)', 'sin(pi / 4) ^ 2', 'sin(90 deg)', 'sin(30 deg)', 'sin(0.2)^2 + cos(0.2)^2'],
52090 seealso: ['asin', 'cos', 'tan']
52091};
52092// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/utils/numeric.js
52093var numericDocs = {
52094 name: 'numeric',
52095 category: 'Utils',
52096 syntax: ['numeric(x)'],
52097 description: 'Convert a numeric input to a specific numeric type: number, BigNumber, or Fraction.',
52098 examples: ['numeric("4")', 'numeric("4", "number")', 'numeric("4", "BigNumber")', 'numeric("4", "Fraction)', 'numeric(4, "Fraction")', 'numeric(fraction(2, 5), "number)'],
52099 seealso: ['number', 'fraction', 'bignumber', 'string', 'format']
52100};
52101// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/matrix/column.js
52102var columnDocs = {
52103 name: 'column',
52104 category: 'Matrix',
52105 syntax: ['column(x, index)'],
52106 description: 'Return a column from a matrix or array.',
52107 examples: ['A = [[1, 2], [3, 4]]', 'column(A, 1)', 'column(A, 2)'],
52108 seealso: ['row']
52109};
52110// CONCATENATED MODULE: ./src/expression/embeddedDocs/function/matrix/row.js
52111var rowDocs = {
52112 name: 'row',
52113 category: 'Matrix',
52114 syntax: ['row(x, index)'],
52115 description: 'Return a row from a matrix or array.',
52116 examples: ['A = [[1, 2], [3, 4]]', 'row(A, 1)', 'row(A, 2)'],
52117 seealso: ['column']
52118};
52119// CONCATENATED MODULE: ./src/expression/embeddedDocs/embeddedDocs.js
52120
52121
52122
52123
52124
52125
52126
52127
52128
52129
52130
52131
52132
52133
52134
52135
52136
52137
52138
52139
52140
52141
52142
52143
52144
52145
52146
52147
52148
52149
52150
52151
52152
52153
52154
52155
52156
52157
52158
52159
52160
52161
52162
52163
52164
52165
52166
52167
52168
52169
52170
52171
52172
52173
52174
52175
52176
52177
52178
52179
52180
52181
52182
52183
52184
52185
52186
52187
52188
52189
52190
52191
52192
52193
52194
52195
52196
52197
52198
52199
52200
52201
52202
52203
52204
52205
52206
52207
52208
52209
52210
52211
52212
52213
52214
52215
52216
52217
52218
52219
52220
52221
52222
52223
52224
52225
52226
52227
52228
52229
52230
52231
52232
52233
52234
52235
52236
52237
52238
52239
52240
52241
52242
52243
52244
52245
52246
52247
52248
52249
52250
52251
52252
52253
52254
52255
52256
52257
52258
52259
52260
52261
52262
52263
52264
52265
52266
52267
52268
52269
52270
52271
52272
52273
52274
52275
52276
52277
52278
52279
52280
52281
52282
52283
52284
52285
52286
52287
52288
52289
52290
52291
52292
52293
52294
52295
52296
52297
52298
52299
52300
52301
52302
52303
52304
52305
52306
52307
52308
52309
52310
52311
52312
52313
52314
52315
52316
52317
52318
52319
52320
52321
52322
52323
52324
52325
52326
52327
52328
52329var embeddedDocs = {
52330 // construction functions
52331 bignumber: bignumberDocs,
52332 "boolean": booleanDocs,
52333 complex: complexDocs,
52334 createUnit: createUnitDocs,
52335 fraction: fractionDocs,
52336 index: indexDocs,
52337 matrix: matrixDocs,
52338 number: numberDocs,
52339 sparse: sparseDocs,
52340 splitUnit: splitUnitDocs,
52341 string: stringDocs,
52342 unit: unitDocs,
52343 // constants
52344 e: eDocs,
52345 E: eDocs,
52346 "false": falseDocs,
52347 i: iDocs,
52348 Infinity: InfinityDocs,
52349 LN2: LN2Docs,
52350 LN10: LN10Docs,
52351 LOG2E: LOG2EDocs,
52352 LOG10E: LOG10EDocs,
52353 NaN: NaNDocs,
52354 "null": nullDocs,
52355 pi: piDocs,
52356 PI: piDocs,
52357 phi: phiDocs,
52358 SQRT1_2: SQRT12Docs,
52359 SQRT2: SQRT2Docs,
52360 tau: tauDocs,
52361 "true": trueDocs,
52362 version: versionDocs,
52363 // physical constants
52364 // TODO: more detailed docs for physical constants
52365 speedOfLight: {
52366 description: 'Speed of light in vacuum',
52367 examples: ['speedOfLight']
52368 },
52369 gravitationConstant: {
52370 description: 'Newtonian constant of gravitation',
52371 examples: ['gravitationConstant']
52372 },
52373 planckConstant: {
52374 description: 'Planck constant',
52375 examples: ['planckConstant']
52376 },
52377 reducedPlanckConstant: {
52378 description: 'Reduced Planck constant',
52379 examples: ['reducedPlanckConstant']
52380 },
52381 magneticConstant: {
52382 description: 'Magnetic constant (vacuum permeability)',
52383 examples: ['magneticConstant']
52384 },
52385 electricConstant: {
52386 description: 'Electric constant (vacuum permeability)',
52387 examples: ['electricConstant']
52388 },
52389 vacuumImpedance: {
52390 description: 'Characteristic impedance of vacuum',
52391 examples: ['vacuumImpedance']
52392 },
52393 coulomb: {
52394 description: 'Coulomb\'s constant',
52395 examples: ['coulomb']
52396 },
52397 elementaryCharge: {
52398 description: 'Elementary charge',
52399 examples: ['elementaryCharge']
52400 },
52401 bohrMagneton: {
52402 description: 'Borh magneton',
52403 examples: ['bohrMagneton']
52404 },
52405 conductanceQuantum: {
52406 description: 'Conductance quantum',
52407 examples: ['conductanceQuantum']
52408 },
52409 inverseConductanceQuantum: {
52410 description: 'Inverse conductance quantum',
52411 examples: ['inverseConductanceQuantum']
52412 },
52413 // josephson: {description: 'Josephson constant', examples: ['josephson']},
52414 magneticFluxQuantum: {
52415 description: 'Magnetic flux quantum',
52416 examples: ['magneticFluxQuantum']
52417 },
52418 nuclearMagneton: {
52419 description: 'Nuclear magneton',
52420 examples: ['nuclearMagneton']
52421 },
52422 klitzing: {
52423 description: 'Von Klitzing constant',
52424 examples: ['klitzing']
52425 },
52426 bohrRadius: {
52427 description: 'Borh radius',
52428 examples: ['bohrRadius']
52429 },
52430 classicalElectronRadius: {
52431 description: 'Classical electron radius',
52432 examples: ['classicalElectronRadius']
52433 },
52434 electronMass: {
52435 description: 'Electron mass',
52436 examples: ['electronMass']
52437 },
52438 fermiCoupling: {
52439 description: 'Fermi coupling constant',
52440 examples: ['fermiCoupling']
52441 },
52442 fineStructure: {
52443 description: 'Fine-structure constant',
52444 examples: ['fineStructure']
52445 },
52446 hartreeEnergy: {
52447 description: 'Hartree energy',
52448 examples: ['hartreeEnergy']
52449 },
52450 protonMass: {
52451 description: 'Proton mass',
52452 examples: ['protonMass']
52453 },
52454 deuteronMass: {
52455 description: 'Deuteron Mass',
52456 examples: ['deuteronMass']
52457 },
52458 neutronMass: {
52459 description: 'Neutron mass',
52460 examples: ['neutronMass']
52461 },
52462 quantumOfCirculation: {
52463 description: 'Quantum of circulation',
52464 examples: ['quantumOfCirculation']
52465 },
52466 rydberg: {
52467 description: 'Rydberg constant',
52468 examples: ['rydberg']
52469 },
52470 thomsonCrossSection: {
52471 description: 'Thomson cross section',
52472 examples: ['thomsonCrossSection']
52473 },
52474 weakMixingAngle: {
52475 description: 'Weak mixing angle',
52476 examples: ['weakMixingAngle']
52477 },
52478 efimovFactor: {
52479 description: 'Efimov factor',
52480 examples: ['efimovFactor']
52481 },
52482 atomicMass: {
52483 description: 'Atomic mass constant',
52484 examples: ['atomicMass']
52485 },
52486 avogadro: {
52487 description: 'Avogadro\'s number',
52488 examples: ['avogadro']
52489 },
52490 boltzmann: {
52491 description: 'Boltzmann constant',
52492 examples: ['boltzmann']
52493 },
52494 faraday: {
52495 description: 'Faraday constant',
52496 examples: ['faraday']
52497 },
52498 firstRadiation: {
52499 description: 'First radiation constant',
52500 examples: ['firstRadiation']
52501 },
52502 loschmidt: {
52503 description: 'Loschmidt constant at T=273.15 K and p=101.325 kPa',
52504 examples: ['loschmidt']
52505 },
52506 gasConstant: {
52507 description: 'Gas constant',
52508 examples: ['gasConstant']
52509 },
52510 molarPlanckConstant: {
52511 description: 'Molar Planck constant',
52512 examples: ['molarPlanckConstant']
52513 },
52514 molarVolume: {
52515 description: 'Molar volume of an ideal gas at T=273.15 K and p=101.325 kPa',
52516 examples: ['molarVolume']
52517 },
52518 sackurTetrode: {
52519 description: 'Sackur-Tetrode constant at T=1 K and p=101.325 kPa',
52520 examples: ['sackurTetrode']
52521 },
52522 secondRadiation: {
52523 description: 'Second radiation constant',
52524 examples: ['secondRadiation']
52525 },
52526 stefanBoltzmann: {
52527 description: 'Stefan-Boltzmann constant',
52528 examples: ['stefanBoltzmann']
52529 },
52530 wienDisplacement: {
52531 description: 'Wien displacement law constant',
52532 examples: ['wienDisplacement']
52533 },
52534 // spectralRadiance: {description: 'First radiation constant for spectral radiance', examples: ['spectralRadiance']},
52535 molarMass: {
52536 description: 'Molar mass constant',
52537 examples: ['molarMass']
52538 },
52539 molarMassC12: {
52540 description: 'Molar mass constant of carbon-12',
52541 examples: ['molarMassC12']
52542 },
52543 gravity: {
52544 description: 'Standard acceleration of gravity (standard acceleration of free-fall on Earth)',
52545 examples: ['gravity']
52546 },
52547 planckLength: {
52548 description: 'Planck length',
52549 examples: ['planckLength']
52550 },
52551 planckMass: {
52552 description: 'Planck mass',
52553 examples: ['planckMass']
52554 },
52555 planckTime: {
52556 description: 'Planck time',
52557 examples: ['planckTime']
52558 },
52559 planckCharge: {
52560 description: 'Planck charge',
52561 examples: ['planckCharge']
52562 },
52563 planckTemperature: {
52564 description: 'Planck temperature',
52565 examples: ['planckTemperature']
52566 },
52567 // functions - algebra
52568 derivative: derivativeDocs,
52569 lsolve: lsolveDocs,
52570 lup: lupDocs,
52571 lusolve: lusolveDocs,
52572 simplify: simplifyDocs,
52573 rationalize: rationalizeDocs,
52574 slu: sluDocs,
52575 usolve: usolveDocs,
52576 qr: qrDocs,
52577 // functions - arithmetic
52578 abs: absDocs,
52579 add: addDocs,
52580 cbrt: cbrtDocs,
52581 ceil: ceilDocs,
52582 cube: cubeDocs,
52583 divide: divideDocs,
52584 dotDivide: dotDivideDocs,
52585 dotMultiply: dotMultiplyDocs,
52586 dotPow: dotPowDocs,
52587 exp: expDocs,
52588 expm: expmDocs,
52589 expm1: expm1Docs,
52590 fix: fixDocs,
52591 floor: floorDocs,
52592 gcd: gcdDocs,
52593 hypot: hypotDocs,
52594 lcm: lcmDocs,
52595 log: logDocs,
52596 log2: log2Docs,
52597 log1p: log1pDocs,
52598 log10: log10Docs,
52599 mod: modDocs,
52600 multiply: multiplyDocs,
52601 norm: normDocs,
52602 nthRoot: nthRootDocs,
52603 nthRoots: nthRootsDocs,
52604 pow: powDocs,
52605 round: roundDocs,
52606 sign: signDocs,
52607 sqrt: sqrtDocs,
52608 sqrtm: sqrtmDocs,
52609 square: squareDocs,
52610 subtract: subtractDocs,
52611 unaryMinus: unaryMinusDocs,
52612 unaryPlus: unaryPlusDocs,
52613 xgcd: xgcdDocs,
52614 // functions - bitwise
52615 bitAnd: bitAndDocs,
52616 bitNot: bitNotDocs,
52617 bitOr: bitOrDocs,
52618 bitXor: bitXorDocs,
52619 leftShift: leftShiftDocs,
52620 rightArithShift: rightArithShiftDocs,
52621 rightLogShift: rightLogShiftDocs,
52622 // functions - combinatorics
52623 bellNumbers: bellNumbersDocs,
52624 catalan: catalanDocs,
52625 composition: compositionDocs,
52626 stirlingS2: stirlingS2Docs,
52627 // functions - core
52628 config: configDocs,
52629 "import": importDocs,
52630 typed: typedDocs,
52631 // functions - complex
52632 arg: argDocs,
52633 conj: conjDocs,
52634 re: reDocs,
52635 im: imDocs,
52636 // functions - expression
52637 evaluate: evaluateDocs,
52638 eval: evaluateDocs,
52639 // TODO: deprecated, cleanup in v7
52640 help: helpDocs,
52641 // functions - geometry
52642 distance: distanceDocs,
52643 intersect: intersectDocs,
52644 // functions - logical
52645 and: andDocs,
52646 not: notDocs,
52647 or: orDocs,
52648 xor: xorDocs,
52649 // functions - matrix
52650 concat: concatDocs,
52651 cross: crossDocs,
52652 column: columnDocs,
52653 ctranspose: ctransposeDocs,
52654 det: detDocs,
52655 diag: diagDocs,
52656 dot: dotDocs,
52657 getMatrixDataType: getMatrixDataTypeDocs,
52658 identity: identityDocs,
52659 filter: filterDocs,
52660 flatten: flattenDocs,
52661 forEach: forEachDocs,
52662 inv: invDocs,
52663 kron: kronDocs,
52664 map: mapDocs,
52665 ones: onesDocs,
52666 partitionSelect: partitionSelectDocs,
52667 range: rangeDocs,
52668 resize: resizeDocs,
52669 reshape: reshapeDocs,
52670 row: rowDocs,
52671 size: sizeDocs,
52672 sort: sortDocs,
52673 squeeze: squeezeDocs,
52674 subset: subsetDocs,
52675 trace: traceDocs,
52676 transpose: transposeDocs,
52677 zeros: zerosDocs,
52678 // functions - probability
52679 combinations: combinationsDocs,
52680 combinationsWithRep: combinationsWithRepDocs,
52681 // distribution: distributionDocs,
52682 factorial: factorialDocs,
52683 gamma: gammaDocs,
52684 kldivergence: kldivergenceDocs,
52685 multinomial: multinomialDocs,
52686 permutations: permutationsDocs,
52687 pickRandom: pickRandomDocs,
52688 random: randomDocs,
52689 randomInt: randomIntDocs,
52690 // functions - relational
52691 compare: compareDocs,
52692 compareNatural: compareNaturalDocs,
52693 compareText: compareTextDocs,
52694 deepEqual: deepEqualDocs,
52695 equal: equalDocs,
52696 equalText: equalTextDocs,
52697 larger: largerDocs,
52698 largerEq: largerEqDocs,
52699 smaller: smallerDocs,
52700 smallerEq: smallerEqDocs,
52701 unequal: unequalDocs,
52702 // functions - set
52703 setCartesian: setCartesianDocs,
52704 setDifference: setDifferenceDocs,
52705 setDistinct: setDistinctDocs,
52706 setIntersect: setIntersectDocs,
52707 setIsSubset: setIsSubsetDocs,
52708 setMultiplicity: setMultiplicityDocs,
52709 setPowerset: setPowersetDocs,
52710 setSize: setSizeDocs,
52711 setSymDifference: setSymDifferenceDocs,
52712 setUnion: setUnionDocs,
52713 // functions - special
52714 erf: erfDocs,
52715 // functions - statistics
52716 mad: madDocs,
52717 max: maxDocs,
52718 mean: meanDocs,
52719 median: medianDocs,
52720 min: minDocs,
52721 mode: modeDocs,
52722 prod: prodDocs,
52723 quantileSeq: quantileSeqDocs,
52724 std: stdDocs,
52725 sum: sumDocs,
52726 variance: varianceDocs,
52727 "var": varianceDocs,
52728 // TODO: deprecated, cleanup in v7
52729 // functions - trigonometry
52730 acos: acosDocs,
52731 acosh: acoshDocs,
52732 acot: acotDocs,
52733 acoth: acothDocs,
52734 acsc: acscDocs,
52735 acsch: acschDocs,
52736 asec: asecDocs,
52737 asech: asechDocs,
52738 asin: asinDocs,
52739 asinh: asinhDocs,
52740 atan: atanDocs,
52741 atanh: atanhDocs,
52742 atan2: atan2Docs,
52743 cos: cosDocs,
52744 cosh: coshDocs,
52745 cot: cotDocs,
52746 coth: cothDocs,
52747 csc: cscDocs,
52748 csch: cschDocs,
52749 sec: secDocs,
52750 sech: sechDocs,
52751 sin: sinDocs,
52752 sinh: sinhDocs,
52753 tan: tanDocs,
52754 tanh: tanhDocs,
52755 // functions - units
52756 to: toDocs,
52757 // functions - utils
52758 clone: cloneDocs,
52759 format: formatDocs,
52760 isNaN: isNaNDocs,
52761 isInteger: isIntegerDocs,
52762 isNegative: isNegativeDocs,
52763 isNumeric: isNumericDocs,
52764 hasNumericValue: hasNumericValueDocs,
52765 isPositive: isPositiveDocs,
52766 isPrime: isPrimeDocs,
52767 isZero: isZeroDocs,
52768 // print: printDocs // TODO: add documentation for print as soon as the parser supports objects.
52769 typeOf: typeOfDocs,
52770 "typeof": typeOfDocs,
52771 // TODO: deprecated, cleanup in v7
52772 numeric: numericDocs
52773};
52774// CONCATENATED MODULE: ./src/expression/function/help.js
52775
52776
52777
52778
52779var help_name = 'help';
52780var help_dependencies = ['typed', 'mathWithTransform', 'Help'];
52781var createHelp =
52782/* #__PURE__ */
52783Object(factory["a" /* factory */])(help_name, help_dependencies, function (_ref) {
52784 var typed = _ref.typed,
52785 mathWithTransform = _ref.mathWithTransform,
52786 Help = _ref.Help;
52787
52788 /**
52789 * Retrieve help on a function or data type.
52790 * Help files are retrieved from the embedded documentation in math.docs.
52791 *
52792 * Syntax:
52793 *
52794 * math.help(search)
52795 *
52796 * Examples:
52797 *
52798 * console.log(math.help('sin').toString())
52799 * console.log(math.help(math.add).toString())
52800 * console.log(math.help(math.add).toJSON())
52801 *
52802 * @param {Function | string | Object} search A function or function name
52803 * for which to get help
52804 * @return {Help} A help object
52805 */
52806 return typed(help_name, {
52807 any: function any(search) {
52808 var prop;
52809 var searchName = search;
52810
52811 if (typeof search !== 'string') {
52812 for (prop in mathWithTransform) {
52813 // search in functions and constants
52814 if (Object(utils_object["f" /* hasOwnProperty */])(mathWithTransform, prop) && search === mathWithTransform[prop]) {
52815 searchName = prop;
52816 break;
52817 }
52818 }
52819 /* TODO: implement help for data types
52820 if (!text) {
52821 // search data type
52822 for (prop in math.type) {
52823 if (hasOwnProperty(math, prop)) {
52824 if (search === math.type[prop]) {
52825 text = prop
52826 break
52827 }
52828 }
52829 }
52830 }
52831 */
52832
52833 }
52834
52835 var doc = getSafeProperty(embeddedDocs, searchName);
52836
52837 if (!doc) {
52838 var searchText = typeof searchName === 'function' ? searchName.name : searchName;
52839 throw new Error('No documentation found on "' + searchText + '"');
52840 }
52841
52842 return new Help(doc);
52843 }
52844 });
52845});
52846// CONCATENATED MODULE: ./src/type/chain/function/chain.js
52847
52848var chain_name = 'chain';
52849var chain_dependencies = ['typed', 'Chain'];
52850var createChain =
52851/* #__PURE__ */
52852Object(factory["a" /* factory */])(chain_name, chain_dependencies, function (_ref) {
52853 var typed = _ref.typed,
52854 Chain = _ref.Chain;
52855
52856 /**
52857 * Wrap any value in a chain, allowing to perform chained operations on
52858 * the value.
52859 *
52860 * All methods available in the math.js library can be called upon the chain,
52861 * and then will be evaluated with the value itself as first argument.
52862 * The chain can be closed by executing `chain.done()`, which returns
52863 * the final value.
52864 *
52865 * The chain has a number of special functions:
52866 *
52867 * - `done()` Finalize the chain and return the chain's value.
52868 * - `valueOf()` The same as `done()`
52869 * - `toString()` Executes `math.format()` onto the chain's value, returning
52870 * a string representation of the value.
52871 *
52872 * Syntax:
52873 *
52874 * math.chain(value)
52875 *
52876 * Examples:
52877 *
52878 * math.chain(3)
52879 * .add(4)
52880 * .subtract(2)
52881 * .done() // 5
52882 *
52883 * math.chain( [[1, 2], [3, 4]] )
52884 * .subset(math.index(0, 0), 8)
52885 * .multiply(3)
52886 * .done() // [[24, 6], [9, 12]]
52887 *
52888 * @param {*} [value] A value of any type on which to start a chained operation.
52889 * @return {math.Chain} The created chain
52890 */
52891 return typed(chain_name, {
52892 '': function _() {
52893 return new Chain();
52894 },
52895 any: function any(value) {
52896 return new Chain(value);
52897 }
52898 });
52899});
52900// CONCATENATED MODULE: ./src/function/matrix/det.js
52901
52902
52903
52904
52905var det_name = 'det';
52906var det_dependencies = ['typed', 'matrix', 'subtract', 'multiply', 'unaryMinus', 'lup'];
52907var createDet =
52908/* #__PURE__ */
52909Object(factory["a" /* factory */])(det_name, det_dependencies, function (_ref) {
52910 var typed = _ref.typed,
52911 matrix = _ref.matrix,
52912 subtract = _ref.subtract,
52913 multiply = _ref.multiply,
52914 unaryMinus = _ref.unaryMinus,
52915 lup = _ref.lup;
52916
52917 /**
52918 * Calculate the determinant of a matrix.
52919 *
52920 * Syntax:
52921 *
52922 * math.det(x)
52923 *
52924 * Examples:
52925 *
52926 * math.det([[1, 2], [3, 4]]) // returns -2
52927 *
52928 * const A = [
52929 * [-2, 2, 3],
52930 * [-1, 1, 3],
52931 * [2, 0, -1]
52932 * ]
52933 * math.det(A) // returns 6
52934 *
52935 * See also:
52936 *
52937 * inv
52938 *
52939 * @param {Array | Matrix} x A matrix
52940 * @return {number} The determinant of `x`
52941 */
52942 return typed(det_name, {
52943 any: function any(x) {
52944 return Object(utils_object["a" /* clone */])(x);
52945 },
52946 'Array | Matrix': function det(x) {
52947 var size;
52948
52949 if (Object(is["v" /* isMatrix */])(x)) {
52950 size = x.size();
52951 } else if (Array.isArray(x)) {
52952 x = matrix(x);
52953 size = x.size();
52954 } else {
52955 // a scalar
52956 size = [];
52957 }
52958
52959 switch (size.length) {
52960 case 0:
52961 // scalar
52962 return Object(utils_object["a" /* clone */])(x);
52963
52964 case 1:
52965 // vector
52966 if (size[0] === 1) {
52967 return Object(utils_object["a" /* clone */])(x.valueOf()[0]);
52968 } else {
52969 throw new RangeError('Matrix must be square ' + '(size: ' + Object(utils_string["d" /* format */])(size) + ')');
52970 }
52971
52972 case 2:
52973 {
52974 // two dimensional array
52975 var rows = size[0];
52976 var cols = size[1];
52977
52978 if (rows === cols) {
52979 return _det(x.clone().valueOf(), rows, cols);
52980 } else {
52981 throw new RangeError('Matrix must be square ' + '(size: ' + Object(utils_string["d" /* format */])(size) + ')');
52982 }
52983 }
52984
52985 default:
52986 // multi dimensional array
52987 throw new RangeError('Matrix must be two dimensional ' + '(size: ' + Object(utils_string["d" /* format */])(size) + ')');
52988 }
52989 }
52990 });
52991 /**
52992 * Calculate the determinant of a matrix
52993 * @param {Array[]} matrix A square, two dimensional matrix
52994 * @param {number} rows Number of rows of the matrix (zero-based)
52995 * @param {number} cols Number of columns of the matrix (zero-based)
52996 * @returns {number} det
52997 * @private
52998 */
52999
53000 function _det(matrix, rows, cols) {
53001 if (rows === 1) {
53002 // this is a 1 x 1 matrix
53003 return Object(utils_object["a" /* clone */])(matrix[0][0]);
53004 } else if (rows === 2) {
53005 // this is a 2 x 2 matrix
53006 // the determinant of [a11,a12;a21,a22] is det = a11*a22-a21*a12
53007 return subtract(multiply(matrix[0][0], matrix[1][1]), multiply(matrix[1][0], matrix[0][1]));
53008 } else {
53009 // Compute the LU decomposition
53010 var decomp = lup(matrix); // The determinant is the product of the diagonal entries of U (and those of L, but they are all 1)
53011
53012 var det = decomp.U[0][0];
53013
53014 for (var _i = 1; _i < rows; _i++) {
53015 det = multiply(det, decomp.U[_i][_i]);
53016 } // The determinant will be multiplied by 1 or -1 depending on the parity of the permutation matrix.
53017 // This can be determined by counting the cycles. This is roughly a linear time algorithm.
53018
53019
53020 var evenCycles = 0;
53021 var i = 0;
53022 var visited = [];
53023
53024 while (true) {
53025 while (visited[i]) {
53026 i++;
53027 }
53028
53029 if (i >= rows) break;
53030 var j = i;
53031 var cycleLen = 0;
53032
53033 while (!visited[decomp.p[j]]) {
53034 visited[decomp.p[j]] = true;
53035 j = decomp.p[j];
53036 cycleLen++;
53037 }
53038
53039 if (cycleLen % 2 === 0) {
53040 evenCycles++;
53041 }
53042 }
53043
53044 return evenCycles % 2 === 0 ? det : unaryMinus(det);
53045 }
53046 }
53047});
53048// CONCATENATED MODULE: ./src/function/matrix/inv.js
53049
53050
53051
53052
53053var inv_name = 'inv';
53054var inv_dependencies = ['typed', 'matrix', 'divideScalar', 'addScalar', 'multiply', 'unaryMinus', 'det', 'identity', 'abs'];
53055var createInv =
53056/* #__PURE__ */
53057Object(factory["a" /* factory */])(inv_name, inv_dependencies, function (_ref) {
53058 var typed = _ref.typed,
53059 matrix = _ref.matrix,
53060 divideScalar = _ref.divideScalar,
53061 addScalar = _ref.addScalar,
53062 multiply = _ref.multiply,
53063 unaryMinus = _ref.unaryMinus,
53064 det = _ref.det,
53065 identity = _ref.identity,
53066 abs = _ref.abs;
53067
53068 /**
53069 * Calculate the inverse of a square matrix.
53070 *
53071 * Syntax:
53072 *
53073 * math.inv(x)
53074 *
53075 * Examples:
53076 *
53077 * math.inv([[1, 2], [3, 4]]) // returns [[-2, 1], [1.5, -0.5]]
53078 * math.inv(4) // returns 0.25
53079 * 1 / 4 // returns 0.25
53080 *
53081 * See also:
53082 *
53083 * det, transpose
53084 *
53085 * @param {number | Complex | Array | Matrix} x Matrix to be inversed
53086 * @return {number | Complex | Array | Matrix} The inverse of `x`.
53087 */
53088 return typed(inv_name, {
53089 'Array | Matrix': function ArrayMatrix(x) {
53090 var size = Object(is["v" /* isMatrix */])(x) ? x.size() : Object(utils_array["a" /* arraySize */])(x);
53091
53092 switch (size.length) {
53093 case 1:
53094 // vector
53095 if (size[0] === 1) {
53096 if (Object(is["v" /* isMatrix */])(x)) {
53097 return matrix([divideScalar(1, x.valueOf()[0])]);
53098 } else {
53099 return [divideScalar(1, x[0])];
53100 }
53101 } else {
53102 throw new RangeError('Matrix must be square ' + '(size: ' + Object(utils_string["d" /* format */])(size) + ')');
53103 }
53104
53105 case 2:
53106 // two dimensional array
53107 {
53108 var rows = size[0];
53109 var cols = size[1];
53110
53111 if (rows === cols) {
53112 if (Object(is["v" /* isMatrix */])(x)) {
53113 return matrix(_inv(x.valueOf(), rows, cols), x.storage());
53114 } else {
53115 // return an Array
53116 return _inv(x, rows, cols);
53117 }
53118 } else {
53119 throw new RangeError('Matrix must be square ' + '(size: ' + Object(utils_string["d" /* format */])(size) + ')');
53120 }
53121 }
53122
53123 default:
53124 // multi dimensional array
53125 throw new RangeError('Matrix must be two dimensional ' + '(size: ' + Object(utils_string["d" /* format */])(size) + ')');
53126 }
53127 },
53128 any: function any(x) {
53129 // scalar
53130 return divideScalar(1, x); // FIXME: create a BigNumber one when configured for bignumbers
53131 }
53132 });
53133 /**
53134 * Calculate the inverse of a square matrix
53135 * @param {Array[]} mat A square matrix
53136 * @param {number} rows Number of rows
53137 * @param {number} cols Number of columns, must equal rows
53138 * @return {Array[]} inv Inverse matrix
53139 * @private
53140 */
53141
53142 function _inv(mat, rows, cols) {
53143 var r, s, f, value, temp;
53144
53145 if (rows === 1) {
53146 // this is a 1 x 1 matrix
53147 value = mat[0][0];
53148
53149 if (value === 0) {
53150 throw Error('Cannot calculate inverse, determinant is zero');
53151 }
53152
53153 return [[divideScalar(1, value)]];
53154 } else if (rows === 2) {
53155 // this is a 2 x 2 matrix
53156 var d = det(mat);
53157
53158 if (d === 0) {
53159 throw Error('Cannot calculate inverse, determinant is zero');
53160 }
53161
53162 return [[divideScalar(mat[1][1], d), divideScalar(unaryMinus(mat[0][1]), d)], [divideScalar(unaryMinus(mat[1][0]), d), divideScalar(mat[0][0], d)]];
53163 } else {
53164 // this is a matrix of 3 x 3 or larger
53165 // calculate inverse using gauss-jordan elimination
53166 // https://en.wikipedia.org/wiki/Gaussian_elimination
53167 // http://mathworld.wolfram.com/MatrixInverse.html
53168 // http://math.uww.edu/~mcfarlat/inverse.htm
53169 // make a copy of the matrix (only the arrays, not of the elements)
53170 var A = mat.concat();
53171
53172 for (r = 0; r < rows; r++) {
53173 A[r] = A[r].concat();
53174 } // create an identity matrix which in the end will contain the
53175 // matrix inverse
53176
53177
53178 var B = identity(rows).valueOf(); // loop over all columns, and perform row reductions
53179
53180 for (var c = 0; c < cols; c++) {
53181 // Pivoting: Swap row c with row r, where row r contains the largest element A[r][c]
53182 var ABig = abs(A[c][c]);
53183 var rBig = c;
53184 r = c + 1;
53185
53186 while (r < rows) {
53187 if (abs(A[r][c]) > ABig) {
53188 ABig = abs(A[r][c]);
53189 rBig = r;
53190 }
53191
53192 r++;
53193 }
53194
53195 if (ABig === 0) {
53196 throw Error('Cannot calculate inverse, determinant is zero');
53197 }
53198
53199 r = rBig;
53200
53201 if (r !== c) {
53202 temp = A[c];
53203 A[c] = A[r];
53204 A[r] = temp;
53205 temp = B[c];
53206 B[c] = B[r];
53207 B[r] = temp;
53208 } // eliminate non-zero values on the other rows at column c
53209
53210
53211 var Ac = A[c];
53212 var Bc = B[c];
53213
53214 for (r = 0; r < rows; r++) {
53215 var Ar = A[r];
53216 var Br = B[r];
53217
53218 if (r !== c) {
53219 // eliminate value at column c and row r
53220 if (Ar[c] !== 0) {
53221 f = divideScalar(unaryMinus(Ar[c]), Ac[c]); // add (f * row c) to row r to eliminate the value
53222 // at column c
53223
53224 for (s = c; s < cols; s++) {
53225 Ar[s] = addScalar(Ar[s], multiply(f, Ac[s]));
53226 }
53227
53228 for (s = 0; s < cols; s++) {
53229 Br[s] = addScalar(Br[s], multiply(f, Bc[s]));
53230 }
53231 }
53232 } else {
53233 // normalize value at Acc to 1,
53234 // divide each value on row r with the value at Acc
53235 f = Ac[c];
53236
53237 for (s = c; s < cols; s++) {
53238 Ar[s] = divideScalar(Ar[s], f);
53239 }
53240
53241 for (s = 0; s < cols; s++) {
53242 Br[s] = divideScalar(Br[s], f);
53243 }
53244 }
53245 }
53246 }
53247
53248 return B;
53249 }
53250 }
53251});
53252// CONCATENATED MODULE: ./src/function/matrix/expm.js
53253
53254
53255
53256var expm_name = 'expm';
53257var expm_dependencies = ['typed', 'abs', 'add', 'identity', 'inv', 'multiply'];
53258var createExpm =
53259/* #__PURE__ */
53260Object(factory["a" /* factory */])(expm_name, expm_dependencies, function (_ref) {
53261 var typed = _ref.typed,
53262 abs = _ref.abs,
53263 add = _ref.add,
53264 identity = _ref.identity,
53265 inv = _ref.inv,
53266 multiply = _ref.multiply;
53267
53268 /**
53269 * Compute the matrix exponential, expm(A) = e^A. The matrix must be square.
53270 * Not to be confused with exp(a), which performs element-wise
53271 * exponentiation.
53272 *
53273 * The exponential is calculated using the Padé approximant with scaling and
53274 * squaring; see "Nineteen Dubious Ways to Compute the Exponential of a
53275 * Matrix," by Moler and Van Loan.
53276 *
53277 * Syntax:
53278 *
53279 * math.expm(x)
53280 *
53281 * Examples:
53282 *
53283 * const A = [[0,2],[0,0]]
53284 * math.expm(A) // returns [[1,2],[0,1]]
53285 *
53286 * See also:
53287 *
53288 * exp
53289 *
53290 * @param {Matrix} x A square Matrix
53291 * @return {Matrix} The exponential of x
53292 */
53293 return typed(expm_name, {
53294 Matrix: function Matrix(A) {
53295 // Check matrix size
53296 var size = A.size();
53297
53298 if (size.length !== 2 || size[0] !== size[1]) {
53299 throw new RangeError('Matrix must be square ' + '(size: ' + Object(utils_string["d" /* format */])(size) + ')');
53300 }
53301
53302 var n = size[0]; // Desired accuracy of the approximant (The actual accuracy
53303 // will be affected by round-off error)
53304
53305 var eps = 1e-15; // The Padé approximant is not so accurate when the values of A
53306 // are "large", so scale A by powers of two. Then compute the
53307 // exponential, and square the result repeatedly according to
53308 // the identity e^A = (e^(A/m))^m
53309 // Compute infinity-norm of A, ||A||, to see how "big" it is
53310
53311 var infNorm = infinityNorm(A); // Find the optimal scaling factor and number of terms in the
53312 // Padé approximant to reach the desired accuracy
53313
53314 var params = findParams(infNorm, eps);
53315 var q = params.q;
53316 var j = params.j; // The Pade approximation to e^A is:
53317 // Rqq(A) = Dqq(A) ^ -1 * Nqq(A)
53318 // where
53319 // Nqq(A) = sum(i=0, q, (2q-i)!p! / [ (2q)!i!(q-i)! ] A^i
53320 // Dqq(A) = sum(i=0, q, (2q-i)!q! / [ (2q)!i!(q-i)! ] (-A)^i
53321 // Scale A by 1 / 2^j
53322
53323 var Apos = multiply(A, Math.pow(2, -j)); // The i=0 term is just the identity matrix
53324
53325 var N = identity(n);
53326 var D = identity(n); // Initialization (i=0)
53327
53328 var factor = 1; // Initialization (i=1)
53329
53330 var AposToI = Apos; // Cloning not necessary
53331
53332 var alternate = -1;
53333
53334 for (var i = 1; i <= q; i++) {
53335 if (i > 1) {
53336 AposToI = multiply(AposToI, Apos);
53337 alternate = -alternate;
53338 }
53339
53340 factor = factor * (q - i + 1) / ((2 * q - i + 1) * i);
53341 N = add(N, multiply(factor, AposToI));
53342 D = add(D, multiply(factor * alternate, AposToI));
53343 }
53344
53345 var R = multiply(inv(D), N); // Square j times
53346
53347 for (var _i = 0; _i < j; _i++) {
53348 R = multiply(R, R);
53349 }
53350
53351 return Object(is["H" /* isSparseMatrix */])(A) ? A.createSparseMatrix(R) : R;
53352 }
53353 });
53354
53355 function infinityNorm(A) {
53356 var n = A.size()[0];
53357 var infNorm = 0;
53358
53359 for (var i = 0; i < n; i++) {
53360 var rowSum = 0;
53361
53362 for (var j = 0; j < n; j++) {
53363 rowSum += abs(A.get([i, j]));
53364 }
53365
53366 infNorm = Math.max(rowSum, infNorm);
53367 }
53368
53369 return infNorm;
53370 }
53371 /**
53372 * Find the best parameters for the Pade approximant given
53373 * the matrix norm and desired accuracy. Returns the first acceptable
53374 * combination in order of increasing computational load.
53375 */
53376
53377
53378 function findParams(infNorm, eps) {
53379 var maxSearchSize = 30;
53380
53381 for (var k = 0; k < maxSearchSize; k++) {
53382 for (var q = 0; q <= k; q++) {
53383 var j = k - q;
53384
53385 if (errorEstimate(infNorm, q, j) < eps) {
53386 return {
53387 q: q,
53388 j: j
53389 };
53390 }
53391 }
53392 }
53393
53394 throw new Error('Could not find acceptable parameters to compute the matrix exponential (try increasing maxSearchSize in expm.js)');
53395 }
53396 /**
53397 * Returns the estimated error of the Pade approximant for the given
53398 * parameters.
53399 */
53400
53401
53402 function errorEstimate(infNorm, q, j) {
53403 var qfac = 1;
53404
53405 for (var i = 2; i <= q; i++) {
53406 qfac *= i;
53407 }
53408
53409 var twoqfac = qfac;
53410
53411 for (var _i2 = q + 1; _i2 <= 2 * q; _i2++) {
53412 twoqfac *= _i2;
53413 }
53414
53415 var twoqp1fac = twoqfac * (2 * q + 1);
53416 return 8.0 * Math.pow(infNorm / Math.pow(2, j), 2 * q) * qfac * qfac / (twoqfac * twoqp1fac);
53417 }
53418});
53419// CONCATENATED MODULE: ./src/function/matrix/sqrtm.js
53420
53421
53422
53423
53424var sqrtm_name = 'sqrtm';
53425var sqrtm_dependencies = ['typed', 'abs', 'add', 'multiply', 'sqrt', 'subtract', 'inv', 'size', 'max', 'identity'];
53426var createSqrtm =
53427/* #__PURE__ */
53428Object(factory["a" /* factory */])(sqrtm_name, sqrtm_dependencies, function (_ref) {
53429 var typed = _ref.typed,
53430 abs = _ref.abs,
53431 add = _ref.add,
53432 multiply = _ref.multiply,
53433 sqrt = _ref.sqrt,
53434 subtract = _ref.subtract,
53435 inv = _ref.inv,
53436 size = _ref.size,
53437 max = _ref.max,
53438 identity = _ref.identity;
53439
53440 /**
53441 * Calculate the principal square root of a square matrix.
53442 * The principal square root matrix `X` of another matrix `A` is such that `X * X = A`.
53443 *
53444 * https://en.wikipedia.org/wiki/Square_root_of_a_matrix
53445 *
53446 * Syntax:
53447 *
53448 * X = math.sqrtm(A)
53449 *
53450 * Examples:
53451 *
53452 * math.sqrtm([[1, 2], [3, 4]]) // returns [[-2, 1], [1.5, -0.5]]
53453 *
53454 * See also:
53455 *
53456 * sqrt, pow
53457 *
53458 * @param {Array | Matrix} A The square matrix `A`
53459 * @return {Array | Matrix} The principal square root of matrix `A`
53460 */
53461 var sqrtm = typed(sqrtm_name, {
53462 'Array | Matrix': function ArrayMatrix(A) {
53463 var size = Object(is["v" /* isMatrix */])(A) ? A.size() : Object(utils_array["a" /* arraySize */])(A);
53464
53465 switch (size.length) {
53466 case 1:
53467 // Single element Array | Matrix
53468 if (size[0] === 1) {
53469 return sqrt(A);
53470 } else {
53471 throw new RangeError('Matrix must be square ' + '(size: ' + Object(utils_string["d" /* format */])(size) + ')');
53472 }
53473
53474 case 2:
53475 {
53476 // Two-dimensional Array | Matrix
53477 var rows = size[0];
53478 var cols = size[1];
53479
53480 if (rows === cols) {
53481 return _denmanBeavers(A);
53482 } else {
53483 throw new RangeError('Matrix must be square ' + '(size: ' + Object(utils_string["d" /* format */])(size) + ')');
53484 }
53485 }
53486 }
53487 }
53488 });
53489 var _maxIterations = 1e3;
53490 var _tolerance = 1e-6;
53491 /**
53492 * Calculate the principal square root matrix using the Denman–Beavers iterative method
53493 *
53494 * https://en.wikipedia.org/wiki/Square_root_of_a_matrix#By_Denman–Beavers_iteration
53495 *
53496 * @param {Array | Matrix} A The square matrix `A`
53497 * @return {Array | Matrix} The principal square root of matrix `A`
53498 * @private
53499 */
53500
53501 function _denmanBeavers(A) {
53502 var error;
53503 var iterations = 0;
53504 var Y = A;
53505 var Z = identity(size(A));
53506
53507 do {
53508 var Yk = Y;
53509 Y = multiply(0.5, add(Yk, inv(Z)));
53510 Z = multiply(0.5, add(Z, inv(Yk)));
53511 error = max(abs(subtract(Y, Yk)));
53512
53513 if (error > _tolerance && ++iterations > _maxIterations) {
53514 throw new Error('computing square root of matrix: iterative method could not converge');
53515 }
53516 } while (error > _tolerance);
53517
53518 return Y;
53519 }
53520
53521 return sqrtm;
53522});
53523// CONCATENATED MODULE: ./src/function/arithmetic/divide.js
53524
53525
53526
53527
53528var divide_name = 'divide';
53529var divide_dependencies = ['typed', 'matrix', 'multiply', 'equalScalar', 'divideScalar', 'inv'];
53530var createDivide =
53531/* #__PURE__ */
53532Object(factory["a" /* factory */])(divide_name, divide_dependencies, function (_ref) {
53533 var typed = _ref.typed,
53534 matrix = _ref.matrix,
53535 multiply = _ref.multiply,
53536 equalScalar = _ref.equalScalar,
53537 divideScalar = _ref.divideScalar,
53538 inv = _ref.inv;
53539 var algorithm11 = createAlgorithm11({
53540 typed: typed,
53541 equalScalar: equalScalar
53542 });
53543 var algorithm14 = createAlgorithm14({
53544 typed: typed
53545 });
53546 /**
53547 * Divide two values, `x / y`.
53548 * To divide matrices, `x` is multiplied with the inverse of `y`: `x * inv(y)`.
53549 *
53550 * Syntax:
53551 *
53552 * math.divide(x, y)
53553 *
53554 * Examples:
53555 *
53556 * math.divide(2, 3) // returns number 0.6666666666666666
53557 *
53558 * const a = math.complex(5, 14)
53559 * const b = math.complex(4, 1)
53560 * math.divide(a, b) // returns Complex 2 + 3i
53561 *
53562 * const c = [[7, -6], [13, -4]]
53563 * const d = [[1, 2], [4, 3]]
53564 * math.divide(c, d) // returns Array [[-9, 4], [-11, 6]]
53565 *
53566 * const e = math.unit('18 km')
53567 * math.divide(e, 4.5) // returns Unit 4 km
53568 *
53569 * See also:
53570 *
53571 * multiply
53572 *
53573 * @param {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} x Numerator
53574 * @param {number | BigNumber | Fraction | Complex | Array | Matrix} y Denominator
53575 * @return {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} Quotient, `x / y`
53576 */
53577
53578 return typed('divide', Object(utils_object["e" /* extend */])({
53579 // we extend the signatures of divideScalar with signatures dealing with matrices
53580 'Array | Matrix, Array | Matrix': function ArrayMatrixArrayMatrix(x, y) {
53581 // TODO: implement matrix right division using pseudo inverse
53582 // https://www.mathworks.nl/help/matlab/ref/mrdivide.html
53583 // https://www.gnu.org/software/octave/doc/interpreter/Arithmetic-Ops.html
53584 // https://stackoverflow.com/questions/12263932/how-does-gnu-octave-matrix-division-work-getting-unexpected-behaviour
53585 return multiply(x, inv(y));
53586 },
53587 'DenseMatrix, any': function DenseMatrixAny(x, y) {
53588 return algorithm14(x, y, divideScalar, false);
53589 },
53590 'SparseMatrix, any': function SparseMatrixAny(x, y) {
53591 return algorithm11(x, y, divideScalar, false);
53592 },
53593 'Array, any': function ArrayAny(x, y) {
53594 // use matrix implementation
53595 return algorithm14(matrix(x), y, divideScalar, false).valueOf();
53596 },
53597 'any, Array | Matrix': function anyArrayMatrix(x, y) {
53598 return multiply(x, inv(y));
53599 }
53600 }, divideScalar.signatures));
53601});
53602// CONCATENATED MODULE: ./src/function/geometry/distance.js
53603
53604
53605var distance_name = 'distance';
53606var distance_dependencies = ['typed', 'addScalar', 'subtract', 'divideScalar', 'multiplyScalar', 'unaryMinus', 'sqrt', 'abs'];
53607var createDistance =
53608/* #__PURE__ */
53609Object(factory["a" /* factory */])(distance_name, distance_dependencies, function (_ref) {
53610 var typed = _ref.typed,
53611 addScalar = _ref.addScalar,
53612 subtract = _ref.subtract,
53613 multiplyScalar = _ref.multiplyScalar,
53614 divideScalar = _ref.divideScalar,
53615 unaryMinus = _ref.unaryMinus,
53616 sqrt = _ref.sqrt,
53617 abs = _ref.abs;
53618
53619 /**
53620 * Calculates:
53621 * The eucledian distance between two points in 2 and 3 dimensional spaces.
53622 * Distance between point and a line in 2 and 3 dimensional spaces.
53623 * Pairwise distance between a set of 2D or 3D points
53624 * NOTE:
53625 * When substituting coefficients of a line(a, b and c), use ax + by + c = 0 instead of ax + by = c
53626 * For parametric equation of a 3D line, x0, y0, z0, a, b, c are from: (x−x0, y−y0, z−z0) = t(a, b, c)
53627 *
53628 * Syntax:
53629 * math.distance([x1, y1], [x2, y2])
53630 *- math.distance({pointOneX: 4, pointOneY: 5}, {pointTwoX: 2, pointTwoY: 7})
53631 * math.distance([x1, y1, z1], [x2, y2, z2])
53632 * math.distance({pointOneX: 4, pointOneY: 5, pointOneZ: 8}, {pointTwoX: 2, pointTwoY: 7, pointTwoZ: 9})
53633 * math.distance([[A], [B], [C]...])
53634 * math.distance([x1, y1], [LinePtX1, LinePtY1], [LinePtX2, LinePtY2])
53635 * math.distance({pointX: 1, pointY: 4}, {lineOnePtX: 6, lineOnePtY: 3}, {lineTwoPtX: 2, lineTwoPtY: 8})
53636 * math.distance([x1, y1, z1], [LinePtX1, LinePtY1, LinePtZ1], [LinePtX2, LinePtY2, LinePtZ2])
53637 * math.distance({pointX: 1, pointY: 4, pointZ: 7}, {lineOnePtX: 6, lineOnePtY: 3, lineOnePtZ: 4}, {lineTwoPtX: 2, lineTwoPtY: 8, lineTwoPtZ: 5})
53638 * math.distance([x1, y1], [xCoeffLine, yCoeffLine, constant])
53639 * math.distance({pointX: 10, pointY: 10}, {xCoeffLine: 8, yCoeffLine: 1, constant: 3})
53640 * math.distance([x1, y1, z1], [x0, y0, z0, a-tCoeff, b-tCoeff, c-tCoeff]) point and parametric equation of 3D line
53641 * math.distance([x, y, z], [x0, y0, z0, a, b, c])
53642 * math.distance({pointX: 2, pointY: 5, pointZ: 9}, {x0: 4, y0: 6, z0: 3, a: 4, b: 2, c: 0})
53643 *
53644 * Examples:
53645 * math.distance([0,0], [4,4]) // Returns 5.6569
53646 * math.distance(
53647 * {pointOneX: 0, pointOneY: 0},
53648 * {pointTwoX: 10, pointTwoY: 10}) // Returns 14.142135623730951
53649 * math.distance([1, 0, 1], [4, -2, 2]) // Returns 3.74166
53650 * math.distance(
53651 * {pointOneX: 4, pointOneY: 5, pointOneZ: 8},
53652 * {pointTwoX: 2, pointTwoY: 7, pointTwoZ: 9}) // Returns 3
53653 * math.distance([[1, 2], [1, 2], [1, 3]]) // Returns [0, 1, 1]
53654 * math.distance([[1,2,4], [1,2,6], [8,1,3]]) // Returns [2, 7.14142842854285, 7.681145747868608]
53655 * math.distance([10, 10], [8, 1, 3]) // Returns 11.535230316796387
53656 * math.distance([10, 10], [2, 3], [-8, 0]) // Returns 8.759953130362847
53657 * math.distance(
53658 * {pointX: 1, pointY: 4},
53659 * {lineOnePtX: 6, lineOnePtY: 3},
53660 * {lineTwoPtX: 2, lineTwoPtY: 8}) // Returns 2.720549372624744
53661 * math.distance([2, 3, 1], [1, 1, 2, 5, 0, 1]) // Returns 2.3204774044612857
53662 * math.distance(
53663 * {pointX: 2, pointY: 3, pointZ: 1},
53664 * {x0: 1, y0: 1, z0: 2, a: 5, b: 0, c: 1} // Returns 2.3204774044612857
53665 *
53666 * @param {Array | Matrix | Object} x Co-ordinates of first point
53667 * @param {Array | Matrix | Object} y Co-ordinates of second point
53668 * @return {Number | BigNumber} Returns the distance from two/three points
53669 */
53670 return typed(distance_name, {
53671 'Array, Array, Array': function ArrayArrayArray(x, y, z) {
53672 // Point to Line 2D (x=Point, y=LinePoint1, z=LinePoint2)
53673 if (x.length === 2 && y.length === 2 && z.length === 2) {
53674 if (!_2d(x)) {
53675 throw new TypeError('Array with 2 numbers or BigNumbers expected for first argument');
53676 }
53677
53678 if (!_2d(y)) {
53679 throw new TypeError('Array with 2 numbers or BigNumbers expected for second argument');
53680 }
53681
53682 if (!_2d(z)) {
53683 throw new TypeError('Array with 2 numbers or BigNumbers expected for third argument');
53684 }
53685
53686 var m = divideScalar(subtract(z[1], z[0]), subtract(y[1], y[0]));
53687 var xCoeff = multiplyScalar(multiplyScalar(m, m), y[0]);
53688 var yCoeff = unaryMinus(multiplyScalar(m, y[0]));
53689 var constant = x[1];
53690 return _distancePointLine2D(x[0], x[1], xCoeff, yCoeff, constant);
53691 } else {
53692 throw new TypeError('Invalid Arguments: Try again');
53693 }
53694 },
53695 'Object, Object, Object': function ObjectObjectObject(x, y, z) {
53696 if (Object.keys(x).length === 2 && Object.keys(y).length === 2 && Object.keys(z).length === 2) {
53697 if (!_2d(x)) {
53698 throw new TypeError('Values of pointX and pointY should be numbers or BigNumbers');
53699 }
53700
53701 if (!_2d(y)) {
53702 throw new TypeError('Values of lineOnePtX and lineOnePtY should be numbers or BigNumbers');
53703 }
53704
53705 if (!_2d(z)) {
53706 throw new TypeError('Values of lineTwoPtX and lineTwoPtY should be numbers or BigNumbers');
53707 }
53708
53709 if ('pointX' in x && 'pointY' in x && 'lineOnePtX' in y && 'lineOnePtY' in y && 'lineTwoPtX' in z && 'lineTwoPtY' in z) {
53710 var m = divideScalar(subtract(z.lineTwoPtY, z.lineTwoPtX), subtract(y.lineOnePtY, y.lineOnePtX));
53711 var xCoeff = multiplyScalar(multiplyScalar(m, m), y.lineOnePtX);
53712 var yCoeff = unaryMinus(multiplyScalar(m, y.lineOnePtX));
53713 var constant = x.pointX;
53714 return _distancePointLine2D(x.pointX, x.pointY, xCoeff, yCoeff, constant);
53715 } else {
53716 throw new TypeError('Key names do not match');
53717 }
53718 } else {
53719 throw new TypeError('Invalid Arguments: Try again');
53720 }
53721 },
53722 'Array, Array': function ArrayArray(x, y) {
53723 // Point to Line 2D (x=[pointX, pointY], y=[x-coeff, y-coeff, const])
53724 if (x.length === 2 && y.length === 3) {
53725 if (!_2d(x)) {
53726 throw new TypeError('Array with 2 numbers or BigNumbers expected for first argument');
53727 }
53728
53729 if (!_3d(y)) {
53730 throw new TypeError('Array with 3 numbers or BigNumbers expected for second argument');
53731 }
53732
53733 return _distancePointLine2D(x[0], x[1], y[0], y[1], y[2]);
53734 } else if (x.length === 3 && y.length === 6) {
53735 // Point to Line 3D
53736 if (!_3d(x)) {
53737 throw new TypeError('Array with 3 numbers or BigNumbers expected for first argument');
53738 }
53739
53740 if (!_parametricLine(y)) {
53741 throw new TypeError('Array with 6 numbers or BigNumbers expected for second argument');
53742 }
53743
53744 return _distancePointLine3D(x[0], x[1], x[2], y[0], y[1], y[2], y[3], y[4], y[5]);
53745 } else if (x.length === 2 && y.length === 2) {
53746 // Point to Point 2D
53747 if (!_2d(x)) {
53748 throw new TypeError('Array with 2 numbers or BigNumbers expected for first argument');
53749 }
53750
53751 if (!_2d(y)) {
53752 throw new TypeError('Array with 2 numbers or BigNumbers expected for second argument');
53753 }
53754
53755 return _distance2d(x[0], x[1], y[0], y[1]);
53756 } else if (x.length === 3 && y.length === 3) {
53757 // Point to Point 3D
53758 if (!_3d(x)) {
53759 throw new TypeError('Array with 3 numbers or BigNumbers expected for first argument');
53760 }
53761
53762 if (!_3d(y)) {
53763 throw new TypeError('Array with 3 numbers or BigNumbers expected for second argument');
53764 }
53765
53766 return _distance3d(x[0], x[1], x[2], y[0], y[1], y[2]);
53767 } else {
53768 throw new TypeError('Invalid Arguments: Try again');
53769 }
53770 },
53771 'Object, Object': function ObjectObject(x, y) {
53772 if (Object.keys(x).length === 2 && Object.keys(y).length === 3) {
53773 if (!_2d(x)) {
53774 throw new TypeError('Values of pointX and pointY should be numbers or BigNumbers');
53775 }
53776
53777 if (!_3d(y)) {
53778 throw new TypeError('Values of xCoeffLine, yCoeffLine and constant should be numbers or BigNumbers');
53779 }
53780
53781 if ('pointX' in x && 'pointY' in x && 'xCoeffLine' in y && 'yCoeffLine' in y && 'constant' in y) {
53782 return _distancePointLine2D(x.pointX, x.pointY, y.xCoeffLine, y.yCoeffLine, y.constant);
53783 } else {
53784 throw new TypeError('Key names do not match');
53785 }
53786 } else if (Object.keys(x).length === 3 && Object.keys(y).length === 6) {
53787 // Point to Line 3D
53788 if (!_3d(x)) {
53789 throw new TypeError('Values of pointX, pointY and pointZ should be numbers or BigNumbers');
53790 }
53791
53792 if (!_parametricLine(y)) {
53793 throw new TypeError('Values of x0, y0, z0, a, b and c should be numbers or BigNumbers');
53794 }
53795
53796 if ('pointX' in x && 'pointY' in x && 'x0' in y && 'y0' in y && 'z0' in y && 'a' in y && 'b' in y && 'c' in y) {
53797 return _distancePointLine3D(x.pointX, x.pointY, x.pointZ, y.x0, y.y0, y.z0, y.a, y.b, y.c);
53798 } else {
53799 throw new TypeError('Key names do not match');
53800 }
53801 } else if (Object.keys(x).length === 2 && Object.keys(y).length === 2) {
53802 // Point to Point 2D
53803 if (!_2d(x)) {
53804 throw new TypeError('Values of pointOneX and pointOneY should be numbers or BigNumbers');
53805 }
53806
53807 if (!_2d(y)) {
53808 throw new TypeError('Values of pointTwoX and pointTwoY should be numbers or BigNumbers');
53809 }
53810
53811 if ('pointOneX' in x && 'pointOneY' in x && 'pointTwoX' in y && 'pointTwoY' in y) {
53812 return _distance2d(x.pointOneX, x.pointOneY, y.pointTwoX, y.pointTwoY);
53813 } else {
53814 throw new TypeError('Key names do not match');
53815 }
53816 } else if (Object.keys(x).length === 3 && Object.keys(y).length === 3) {
53817 // Point to Point 3D
53818 if (!_3d(x)) {
53819 throw new TypeError('Values of pointOneX, pointOneY and pointOneZ should be numbers or BigNumbers');
53820 }
53821
53822 if (!_3d(y)) {
53823 throw new TypeError('Values of pointTwoX, pointTwoY and pointTwoZ should be numbers or BigNumbers');
53824 }
53825
53826 if ('pointOneX' in x && 'pointOneY' in x && 'pointOneZ' in x && 'pointTwoX' in y && 'pointTwoY' in y && 'pointTwoZ' in y) {
53827 return _distance3d(x.pointOneX, x.pointOneY, x.pointOneZ, y.pointTwoX, y.pointTwoY, y.pointTwoZ);
53828 } else {
53829 throw new TypeError('Key names do not match');
53830 }
53831 } else {
53832 throw new TypeError('Invalid Arguments: Try again');
53833 }
53834 },
53835 Array: function Array(arr) {
53836 if (!_pairwise(arr)) {
53837 throw new TypeError('Incorrect array format entered for pairwise distance calculation');
53838 }
53839
53840 return _distancePairwise(arr);
53841 }
53842 });
53843
53844 function _isNumber(a) {
53845 // distance supports numbers and bignumbers
53846 return typeof a === 'number' || Object(is["e" /* isBigNumber */])(a);
53847 }
53848
53849 function _2d(a) {
53850 // checks if the number of arguments are correct in count and are valid (should be numbers)
53851 if (a.constructor !== Array) {
53852 a = _objectToArray(a);
53853 }
53854
53855 return _isNumber(a[0]) && _isNumber(a[1]);
53856 }
53857
53858 function _3d(a) {
53859 // checks if the number of arguments are correct in count and are valid (should be numbers)
53860 if (a.constructor !== Array) {
53861 a = _objectToArray(a);
53862 }
53863
53864 return _isNumber(a[0]) && _isNumber(a[1]) && _isNumber(a[2]);
53865 }
53866
53867 function _parametricLine(a) {
53868 if (a.constructor !== Array) {
53869 a = _objectToArray(a);
53870 }
53871
53872 return _isNumber(a[0]) && _isNumber(a[1]) && _isNumber(a[2]) && _isNumber(a[3]) && _isNumber(a[4]) && _isNumber(a[5]);
53873 }
53874
53875 function _objectToArray(o) {
53876 var keys = Object.keys(o);
53877 var a = [];
53878
53879 for (var i = 0; i < keys.length; i++) {
53880 a.push(o[keys[i]]);
53881 }
53882
53883 return a;
53884 }
53885
53886 function _pairwise(a) {
53887 // checks for valid arguments passed to _distancePairwise(Array)
53888 if (a[0].length === 2 && _isNumber(a[0][0]) && _isNumber(a[0][1])) {
53889 if (a.some(function (aI) {
53890 return aI.length !== 2 || !_isNumber(aI[0]) || !_isNumber(aI[1]);
53891 })) {
53892 return false;
53893 }
53894 } else if (a[0].length === 3 && _isNumber(a[0][0]) && _isNumber(a[0][1]) && _isNumber(a[0][2])) {
53895 if (a.some(function (aI) {
53896 return aI.length !== 3 || !_isNumber(aI[0]) || !_isNumber(aI[1]) || !_isNumber(aI[2]);
53897 })) {
53898 return false;
53899 }
53900 } else {
53901 return false;
53902 }
53903
53904 return true;
53905 }
53906
53907 function _distancePointLine2D(x, y, a, b, c) {
53908 var num = abs(addScalar(addScalar(multiplyScalar(a, x), multiplyScalar(b, y)), c));
53909 var den = sqrt(addScalar(multiplyScalar(a, a), multiplyScalar(b, b)));
53910 return divideScalar(num, den);
53911 }
53912
53913 function _distancePointLine3D(x, y, z, x0, y0, z0, a, b, c) {
53914 var num = [subtract(multiplyScalar(subtract(y0, y), c), multiplyScalar(subtract(z0, z), b)), subtract(multiplyScalar(subtract(z0, z), a), multiplyScalar(subtract(x0, x), c)), subtract(multiplyScalar(subtract(x0, x), b), multiplyScalar(subtract(y0, y), a))];
53915 num = sqrt(addScalar(addScalar(multiplyScalar(num[0], num[0]), multiplyScalar(num[1], num[1])), multiplyScalar(num[2], num[2])));
53916 var den = sqrt(addScalar(addScalar(multiplyScalar(a, a), multiplyScalar(b, b)), multiplyScalar(c, c)));
53917 return divideScalar(num, den);
53918 }
53919
53920 function _distance2d(x1, y1, x2, y2) {
53921 var yDiff = subtract(y2, y1);
53922 var xDiff = subtract(x2, x1);
53923 var radicant = addScalar(multiplyScalar(yDiff, yDiff), multiplyScalar(xDiff, xDiff));
53924 return sqrt(radicant);
53925 }
53926
53927 function _distance3d(x1, y1, z1, x2, y2, z2) {
53928 var zDiff = subtract(z2, z1);
53929 var yDiff = subtract(y2, y1);
53930 var xDiff = subtract(x2, x1);
53931 var radicant = addScalar(addScalar(multiplyScalar(zDiff, zDiff), multiplyScalar(yDiff, yDiff)), multiplyScalar(xDiff, xDiff));
53932 return sqrt(radicant);
53933 }
53934
53935 function _distancePairwise(a) {
53936 var result = [];
53937
53938 for (var i = 0; i < a.length - 1; i++) {
53939 for (var j = i + 1; j < a.length; j++) {
53940 if (a[0].length === 2) {
53941 result.push(_distance2d(a[i][0], a[i][1], a[j][0], a[j][1]));
53942 } else if (a[0].length === 3) {
53943 result.push(_distance3d(a[i][0], a[i][1], a[i][2], a[j][0], a[j][1], a[j][2]));
53944 }
53945 }
53946 }
53947
53948 return result;
53949 }
53950});
53951// CONCATENATED MODULE: ./src/function/geometry/intersect.js
53952
53953
53954var intersect_name = 'intersect';
53955var intersect_dependencies = ['typed', 'config', 'abs', 'add', 'addScalar', 'matrix', 'multiply', 'multiplyScalar', 'divideScalar', 'subtract', 'smaller', 'equalScalar'];
53956var createIntersect =
53957/* #__PURE__ */
53958Object(factory["a" /* factory */])(intersect_name, intersect_dependencies, function (_ref) {
53959 var typed = _ref.typed,
53960 config = _ref.config,
53961 abs = _ref.abs,
53962 add = _ref.add,
53963 addScalar = _ref.addScalar,
53964 matrix = _ref.matrix,
53965 multiply = _ref.multiply,
53966 multiplyScalar = _ref.multiplyScalar,
53967 divideScalar = _ref.divideScalar,
53968 subtract = _ref.subtract,
53969 smaller = _ref.smaller,
53970 equalScalar = _ref.equalScalar;
53971
53972 /**
53973 * Calculates the point of intersection of two lines in two or three dimensions
53974 * and of a line and a plane in three dimensions. The inputs are in the form of
53975 * arrays or 1 dimensional matrices. The line intersection functions return null
53976 * if the lines do not meet.
53977 *
53978 * Note: Fill the plane coefficients as `x + y + z = c` and not as `x + y + z + c = 0`.
53979 *
53980 * Syntax:
53981 *
53982 * math.intersect(endPoint1Line1, endPoint2Line1, endPoint1Line2, endPoint2Line2)
53983 * math.intersect(endPoint1, endPoint2, planeCoefficients)
53984 *
53985 * Examples:
53986 *
53987 * math.intersect([0, 0], [10, 10], [10, 0], [0, 10]) // Returns [5, 5]
53988 * math.intersect([0, 0, 0], [10, 10, 0], [10, 0, 0], [0, 10, 0]) // Returns [5, 5, 0]
53989 * math.intersect([1, 0, 1], [4, -2, 2], [1, 1, 1, 6]) // Returns [7, -4, 3]
53990 *
53991 * @param {Array | Matrix} w Co-ordinates of first end-point of first line
53992 * @param {Array | Matrix} x Co-ordinates of second end-point of first line
53993 * @param {Array | Matrix} y Co-ordinates of first end-point of second line
53994 * OR Co-efficients of the plane's equation
53995 * @param {Array | Matrix} z Co-ordinates of second end-point of second line
53996 * OR null if the calculation is for line and plane
53997 * @return {Array} Returns the point of intersection of lines/lines-planes
53998 */
53999 var intersect = typed('intersect', {
54000 'Array, Array, Array': function ArrayArrayArray(x, y, plane) {
54001 if (!_3d(x)) {
54002 throw new TypeError('Array with 3 numbers or BigNumbers expected for first argument');
54003 }
54004
54005 if (!_3d(y)) {
54006 throw new TypeError('Array with 3 numbers or BigNumbers expected for second argument');
54007 }
54008
54009 if (!_4d(plane)) {
54010 throw new TypeError('Array with 4 numbers expected as third argument');
54011 }
54012
54013 return _intersectLinePlane(x[0], x[1], x[2], y[0], y[1], y[2], plane[0], plane[1], plane[2], plane[3]);
54014 },
54015 'Array, Array, Array, Array': function ArrayArrayArrayArray(w, x, y, z) {
54016 if (w.length === 2) {
54017 if (!_2d(w)) {
54018 throw new TypeError('Array with 2 numbers or BigNumbers expected for first argument');
54019 }
54020
54021 if (!_2d(x)) {
54022 throw new TypeError('Array with 2 numbers or BigNumbers expected for second argument');
54023 }
54024
54025 if (!_2d(y)) {
54026 throw new TypeError('Array with 2 numbers or BigNumbers expected for third argument');
54027 }
54028
54029 if (!_2d(z)) {
54030 throw new TypeError('Array with 2 numbers or BigNumbers expected for fourth argument');
54031 }
54032
54033 return _intersect2d(w, x, y, z);
54034 } else if (w.length === 3) {
54035 if (!_3d(w)) {
54036 throw new TypeError('Array with 3 numbers or BigNumbers expected for first argument');
54037 }
54038
54039 if (!_3d(x)) {
54040 throw new TypeError('Array with 3 numbers or BigNumbers expected for second argument');
54041 }
54042
54043 if (!_3d(y)) {
54044 throw new TypeError('Array with 3 numbers or BigNumbers expected for third argument');
54045 }
54046
54047 if (!_3d(z)) {
54048 throw new TypeError('Array with 3 numbers or BigNumbers expected for fourth argument');
54049 }
54050
54051 return _intersect3d(w[0], w[1], w[2], x[0], x[1], x[2], y[0], y[1], y[2], z[0], z[1], z[2]);
54052 } else {
54053 throw new TypeError('Arrays with two or thee dimensional points expected');
54054 }
54055 },
54056 'Matrix, Matrix, Matrix': function MatrixMatrixMatrix(x, y, plane) {
54057 return matrix(intersect(x.valueOf(), y.valueOf(), plane.valueOf()));
54058 },
54059 'Matrix, Matrix, Matrix, Matrix': function MatrixMatrixMatrixMatrix(w, x, y, z) {
54060 // TODO: output matrix type should match input matrix type
54061 return matrix(intersect(w.valueOf(), x.valueOf(), y.valueOf(), z.valueOf()));
54062 }
54063 });
54064
54065 function _isNumeric(a) {
54066 // intersect supports numbers and bignumbers
54067 return typeof a === 'number' || Object(is["e" /* isBigNumber */])(a);
54068 }
54069
54070 function _2d(x) {
54071 return x.length === 2 && _isNumeric(x[0]) && _isNumeric(x[1]);
54072 }
54073
54074 function _3d(x) {
54075 return x.length === 3 && _isNumeric(x[0]) && _isNumeric(x[1]) && _isNumeric(x[2]);
54076 }
54077
54078 function _4d(x) {
54079 return x.length === 4 && _isNumeric(x[0]) && _isNumeric(x[1]) && _isNumeric(x[2]) && _isNumeric(x[3]);
54080 }
54081
54082 function _intersect2d(p1a, p1b, p2a, p2b) {
54083 var o1 = p1a;
54084 var o2 = p2a;
54085 var d1 = subtract(o1, p1b);
54086 var d2 = subtract(o2, p2b);
54087 var det = subtract(multiplyScalar(d1[0], d2[1]), multiplyScalar(d2[0], d1[1]));
54088
54089 if (smaller(abs(det), config.epsilon)) {
54090 return null;
54091 }
54092
54093 var d20o11 = multiplyScalar(d2[0], o1[1]);
54094 var d21o10 = multiplyScalar(d2[1], o1[0]);
54095 var d20o21 = multiplyScalar(d2[0], o2[1]);
54096 var d21o20 = multiplyScalar(d2[1], o2[0]);
54097 var t = divideScalar(addScalar(subtract(subtract(d20o11, d21o10), d20o21), d21o20), det);
54098 return add(multiply(d1, t), o1);
54099 }
54100
54101 function _intersect3dHelper(a, b, c, d, e, f, g, h, i, j, k, l) {
54102 // (a - b)*(c - d) + (e - f)*(g - h) + (i - j)*(k - l)
54103 var add1 = multiplyScalar(subtract(a, b), subtract(c, d));
54104 var add2 = multiplyScalar(subtract(e, f), subtract(g, h));
54105 var add3 = multiplyScalar(subtract(i, j), subtract(k, l));
54106 return addScalar(addScalar(add1, add2), add3);
54107 }
54108
54109 function _intersect3d(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4) {
54110 var d1343 = _intersect3dHelper(x1, x3, x4, x3, y1, y3, y4, y3, z1, z3, z4, z3);
54111
54112 var d4321 = _intersect3dHelper(x4, x3, x2, x1, y4, y3, y2, y1, z4, z3, z2, z1);
54113
54114 var d1321 = _intersect3dHelper(x1, x3, x2, x1, y1, y3, y2, y1, z1, z3, z2, z1);
54115
54116 var d4343 = _intersect3dHelper(x4, x3, x4, x3, y4, y3, y4, y3, z4, z3, z4, z3);
54117
54118 var d2121 = _intersect3dHelper(x2, x1, x2, x1, y2, y1, y2, y1, z2, z1, z2, z1);
54119
54120 var ta = divideScalar(subtract(multiplyScalar(d1343, d4321), multiplyScalar(d1321, d4343)), subtract(multiplyScalar(d2121, d4343), multiplyScalar(d4321, d4321)));
54121 var tb = divideScalar(addScalar(d1343, multiplyScalar(ta, d4321)), d4343);
54122 var pax = addScalar(x1, multiplyScalar(ta, subtract(x2, x1)));
54123 var pay = addScalar(y1, multiplyScalar(ta, subtract(y2, y1)));
54124 var paz = addScalar(z1, multiplyScalar(ta, subtract(z2, z1)));
54125 var pbx = addScalar(x3, multiplyScalar(tb, subtract(x4, x3)));
54126 var pby = addScalar(y3, multiplyScalar(tb, subtract(y4, y3)));
54127 var pbz = addScalar(z3, multiplyScalar(tb, subtract(z4, z3)));
54128
54129 if (equalScalar(pax, pbx) && equalScalar(pay, pby) && equalScalar(paz, pbz)) {
54130 return [pax, pay, paz];
54131 } else {
54132 return null;
54133 }
54134 }
54135
54136 function _intersectLinePlane(x1, y1, z1, x2, y2, z2, x, y, z, c) {
54137 var x1x = multiplyScalar(x1, x);
54138 var x2x = multiplyScalar(x2, x);
54139 var y1y = multiplyScalar(y1, y);
54140 var y2y = multiplyScalar(y2, y);
54141 var z1z = multiplyScalar(z1, z);
54142 var z2z = multiplyScalar(z2, z);
54143 var t = divideScalar(subtract(subtract(subtract(c, x1x), y1y), z1z), subtract(subtract(subtract(addScalar(addScalar(x2x, y2y), z2z), x1x), y1y), z1z));
54144 var px = addScalar(x1, multiplyScalar(t, subtract(x2, x1)));
54145 var py = addScalar(y1, multiplyScalar(t, subtract(y2, y1)));
54146 var pz = addScalar(z1, multiplyScalar(t, subtract(z2, z1)));
54147 return [px, py, pz]; // TODO: Add cases when line is parallel to the plane:
54148 // (a) no intersection,
54149 // (b) line contained in plane
54150 }
54151
54152 return intersect;
54153});
54154// CONCATENATED MODULE: ./src/function/statistics/sum.js
54155
54156
54157
54158
54159var sum_name = 'sum';
54160var sum_dependencies = ['typed', 'config', 'add', '?bignumber', '?fraction'];
54161var createSum =
54162/* #__PURE__ */
54163Object(factory["a" /* factory */])(sum_name, sum_dependencies, function (_ref) {
54164 var typed = _ref.typed,
54165 config = _ref.config,
54166 add = _ref.add,
54167 bignumber = _ref.bignumber,
54168 fraction = _ref.fraction;
54169
54170 /**
54171 * Compute the sum of a matrix or a list with values.
54172 * In case of a (multi dimensional) array or matrix, the sum of all
54173 * elements will be calculated.
54174 *
54175 * Syntax:
54176 *
54177 * math.sum(a, b, c, ...)
54178 * math.sum(A)
54179 *
54180 * Examples:
54181 *
54182 * math.sum(2, 1, 4, 3) // returns 10
54183 * math.sum([2, 1, 4, 3]) // returns 10
54184 * math.sum([[2, 5], [4, 3], [1, 7]]) // returns 22
54185 *
54186 * See also:
54187 *
54188 * mean, median, min, max, prod, std, variance
54189 *
54190 * @param {... *} args A single matrix or or multiple scalar values
54191 * @return {*} The sum of all values
54192 */
54193 return typed(sum_name, {
54194 // sum([a, b, c, d, ...])
54195 'Array | Matrix': _sum,
54196 // sum([a, b, c, d, ...], dim)
54197 'Array | Matrix, number | BigNumber': _nsumDim,
54198 // sum(a, b, c, d, ...)
54199 '...': function _(args) {
54200 if (containsCollections(args)) {
54201 throw new TypeError('Scalar values expected in function sum');
54202 }
54203
54204 return _sum(args);
54205 }
54206 });
54207 /**
54208 * Recursively calculate the sum of an n-dimensional array
54209 * @param {Array} array
54210 * @return {number} sum
54211 * @private
54212 */
54213
54214 function _sum(array) {
54215 var sum;
54216 deepForEach(array, function (value) {
54217 try {
54218 sum = sum === undefined ? value : add(sum, value);
54219 } catch (err) {
54220 throw improveErrorMessage(err, 'sum', value);
54221 }
54222 });
54223
54224 if (sum === undefined) {
54225 switch (config.number) {
54226 case 'number':
54227 return 0;
54228
54229 case 'BigNumber':
54230 return bignumber ? bignumber(0) : noBignumber();
54231
54232 case 'Fraction':
54233 return fraction ? fraction(0) : noFraction();
54234
54235 default:
54236 return 0;
54237 }
54238 }
54239
54240 return sum;
54241 }
54242
54243 function _nsumDim(array, dim) {
54244 try {
54245 var sum = reduce(array, dim, add);
54246 return sum;
54247 } catch (err) {
54248 throw improveErrorMessage(err, 'sum');
54249 }
54250 }
54251});
54252// CONCATENATED MODULE: ./src/function/statistics/mean.js
54253
54254
54255
54256
54257var mean_name = 'mean';
54258var mean_dependencies = ['typed', 'add', 'divide'];
54259var createMean =
54260/* #__PURE__ */
54261Object(factory["a" /* factory */])(mean_name, mean_dependencies, function (_ref) {
54262 var typed = _ref.typed,
54263 add = _ref.add,
54264 divide = _ref.divide;
54265
54266 /**
54267 * Compute the mean value of matrix or a list with values.
54268 * In case of a multi dimensional array, the mean of the flattened array
54269 * will be calculated. When `dim` is provided, the maximum over the selected
54270 * dimension will be calculated. Parameter `dim` is zero-based.
54271 *
54272 * Syntax:
54273 *
54274 * math.mean(a, b, c, ...)
54275 * math.mean(A)
54276 * math.mean(A, dim)
54277 *
54278 * Examples:
54279 *
54280 * math.mean(2, 1, 4, 3) // returns 2.5
54281 * math.mean([1, 2.7, 3.2, 4]) // returns 2.725
54282 *
54283 * math.mean([[2, 5], [6, 3], [1, 7]], 0) // returns [3, 5]
54284 * math.mean([[2, 5], [6, 3], [1, 7]], 1) // returns [3.5, 4.5, 4]
54285 *
54286 * See also:
54287 *
54288 * median, min, max, sum, prod, std, variance
54289 *
54290 * @param {... *} args A single matrix or or multiple scalar values
54291 * @return {*} The mean of all values
54292 */
54293 return typed(mean_name, {
54294 // mean([a, b, c, d, ...])
54295 'Array | Matrix': _mean,
54296 // mean([a, b, c, d, ...], dim)
54297 'Array | Matrix, number | BigNumber': _nmeanDim,
54298 // mean(a, b, c, d, ...)
54299 '...': function _(args) {
54300 if (containsCollections(args)) {
54301 throw new TypeError('Scalar values expected in function mean');
54302 }
54303
54304 return _mean(args);
54305 }
54306 });
54307 /**
54308 * Calculate the mean value in an n-dimensional array, returning a
54309 * n-1 dimensional array
54310 * @param {Array} array
54311 * @param {number} dim
54312 * @return {number} mean
54313 * @private
54314 */
54315
54316 function _nmeanDim(array, dim) {
54317 try {
54318 var sum = reduce(array, dim, add);
54319 var s = Array.isArray(array) ? Object(utils_array["a" /* arraySize */])(array) : array.size();
54320 return divide(sum, s[dim]);
54321 } catch (err) {
54322 throw improveErrorMessage(err, 'mean');
54323 }
54324 }
54325 /**
54326 * Recursively calculate the mean value in an n-dimensional array
54327 * @param {Array} array
54328 * @return {number} mean
54329 * @private
54330 */
54331
54332
54333 function _mean(array) {
54334 var sum;
54335 var num = 0;
54336 deepForEach(array, function (value) {
54337 try {
54338 sum = sum === undefined ? value : add(sum, value);
54339 num++;
54340 } catch (err) {
54341 throw improveErrorMessage(err, 'mean', value);
54342 }
54343 });
54344
54345 if (num === 0) {
54346 throw new Error('Cannot calculate the mean of an empty array');
54347 }
54348
54349 return divide(sum, num);
54350 }
54351});
54352// CONCATENATED MODULE: ./src/function/statistics/median.js
54353
54354
54355
54356
54357var median_name = 'median';
54358var median_dependencies = ['typed', 'add', 'divide', 'compare', 'partitionSelect'];
54359var createMedian =
54360/* #__PURE__ */
54361Object(factory["a" /* factory */])(median_name, median_dependencies, function (_ref) {
54362 var typed = _ref.typed,
54363 add = _ref.add,
54364 divide = _ref.divide,
54365 compare = _ref.compare,
54366 partitionSelect = _ref.partitionSelect;
54367
54368 /**
54369 * Compute the median of a matrix or a list with values. The values are
54370 * sorted and the middle value is returned. In case of an even number of
54371 * values, the average of the two middle values is returned.
54372 * Supported types of values are: Number, BigNumber, Unit
54373 *
54374 * In case of a (multi dimensional) array or matrix, the median of all
54375 * elements will be calculated.
54376 *
54377 * Syntax:
54378 *
54379 * math.median(a, b, c, ...)
54380 * math.median(A)
54381 *
54382 * Examples:
54383 *
54384 * math.median(5, 2, 7) // returns 5
54385 * math.median([3, -1, 5, 7]) // returns 4
54386 *
54387 * See also:
54388 *
54389 * mean, min, max, sum, prod, std, variance, quantileSeq
54390 *
54391 * @param {... *} args A single matrix or or multiple scalar values
54392 * @return {*} The median
54393 */
54394 var median = typed(median_name, {
54395 // median([a, b, c, d, ...])
54396 'Array | Matrix': _median,
54397 // median([a, b, c, d, ...], dim)
54398 'Array | Matrix, number | BigNumber': function ArrayMatrixNumberBigNumber(array, dim) {
54399 // TODO: implement median(A, dim)
54400 throw new Error('median(A, dim) is not yet supported'); // return reduce(arguments[0], arguments[1], ...)
54401 },
54402 // median(a, b, c, d, ...)
54403 '...': function _(args) {
54404 if (containsCollections(args)) {
54405 throw new TypeError('Scalar values expected in function median');
54406 }
54407
54408 return _median(args);
54409 }
54410 });
54411 /**
54412 * Recursively calculate the median of an n-dimensional array
54413 * @param {Array} array
54414 * @return {Number} median
54415 * @private
54416 */
54417
54418 function _median(array) {
54419 try {
54420 array = Object(utils_array["e" /* flatten */])(array.valueOf());
54421 var num = array.length;
54422
54423 if (num === 0) {
54424 throw new Error('Cannot calculate median of an empty array');
54425 }
54426
54427 if (num % 2 === 0) {
54428 // even: return the average of the two middle values
54429 var mid = num / 2 - 1;
54430 var right = partitionSelect(array, mid + 1); // array now partitioned at mid + 1, take max of left part
54431
54432 var left = array[mid];
54433
54434 for (var i = 0; i < mid; ++i) {
54435 if (compare(array[i], left) > 0) {
54436 left = array[i];
54437 }
54438 }
54439
54440 return middle2(left, right);
54441 } else {
54442 // odd: return the middle value
54443 var m = partitionSelect(array, (num - 1) / 2);
54444 return middle(m);
54445 }
54446 } catch (err) {
54447 throw improveErrorMessage(err, 'median');
54448 }
54449 } // helper function to type check the middle value of the array
54450
54451
54452 var middle = typed({
54453 'number | BigNumber | Complex | Unit': function numberBigNumberComplexUnit(value) {
54454 return value;
54455 }
54456 }); // helper function to type check the two middle value of the array
54457
54458 var middle2 = typed({
54459 'number | BigNumber | Complex | Unit, number | BigNumber | Complex | Unit': function numberBigNumberComplexUnitNumberBigNumberComplexUnit(left, right) {
54460 return divide(add(left, right), 2);
54461 }
54462 });
54463 return median;
54464});
54465// CONCATENATED MODULE: ./src/function/statistics/mad.js
54466
54467
54468
54469var mad_name = 'mad';
54470var mad_dependencies = ['typed', 'abs', 'map', 'median', 'subtract'];
54471var createMad =
54472/* #__PURE__ */
54473Object(factory["a" /* factory */])(mad_name, mad_dependencies, function (_ref) {
54474 var typed = _ref.typed,
54475 abs = _ref.abs,
54476 map = _ref.map,
54477 median = _ref.median,
54478 subtract = _ref.subtract;
54479
54480 /**
54481 * Compute the median absolute deviation of a matrix or a list with values.
54482 * The median absolute deviation is defined as the median of the absolute
54483 * deviations from the median.
54484 *
54485 * Syntax:
54486 *
54487 * math.mad(a, b, c, ...)
54488 * math.mad(A)
54489 *
54490 * Examples:
54491 *
54492 * math.mad(10, 20, 30) // returns 10
54493 * math.mad([1, 2, 3]) // returns 1
54494 * math.mad([[1, 2, 3], [4, 5, 6]]) // returns 1.5
54495 *
54496 * See also:
54497 *
54498 * median, mean, std, abs
54499 *
54500 * @param {Array | Matrix} array
54501 * A single matrix or multiple scalar values.
54502 * @return {*} The median absolute deviation.
54503 */
54504 return typed(mad_name, {
54505 // mad([a, b, c, d, ...])
54506 'Array | Matrix': _mad,
54507 // mad(a, b, c, d, ...)
54508 '...': function _(args) {
54509 return _mad(args);
54510 }
54511 });
54512
54513 function _mad(array) {
54514 array = Object(utils_array["e" /* flatten */])(array.valueOf());
54515
54516 if (array.length === 0) {
54517 throw new Error('Cannot calculate median absolute deviation (mad) of an empty array');
54518 }
54519
54520 try {
54521 var med = median(array);
54522 return median(map(array, function (value) {
54523 return abs(subtract(value, med));
54524 }));
54525 } catch (err) {
54526 if (err instanceof TypeError && err.message.indexOf('median') !== -1) {
54527 throw new TypeError(err.message.replace('median', 'mad'));
54528 } else {
54529 throw improveErrorMessage(err, 'mad');
54530 }
54531 }
54532 }
54533});
54534// CONCATENATED MODULE: ./src/function/statistics/variance.js
54535
54536
54537
54538
54539
54540var DEFAULT_NORMALIZATION = 'unbiased';
54541var variance_name = 'variance';
54542var variance_dependencies = ['typed', 'add', 'subtract', 'multiply', 'divide', 'apply', 'isNaN'];
54543var createVariance =
54544/* #__PURE__ */
54545Object(factory["a" /* factory */])(variance_name, variance_dependencies, function (_ref) {
54546 var typed = _ref.typed,
54547 add = _ref.add,
54548 subtract = _ref.subtract,
54549 multiply = _ref.multiply,
54550 divide = _ref.divide,
54551 apply = _ref.apply,
54552 isNaN = _ref.isNaN;
54553
54554 /**
54555 * Compute the variance of a matrix or a list with values.
54556 * In case of a (multi dimensional) array or matrix, the variance over all
54557 * elements will be calculated.
54558 *
54559 * Additionally, it is possible to compute the variance along the rows
54560 * or columns of a matrix by specifying the dimension as the second argument.
54561 *
54562 * Optionally, the type of normalization can be specified as the final
54563 * parameter. The parameter `normalization` can be one of the following values:
54564 *
54565 * - 'unbiased' (default) The sum of squared errors is divided by (n - 1)
54566 * - 'uncorrected' The sum of squared errors is divided by n
54567 * - 'biased' The sum of squared errors is divided by (n + 1)
54568 *
54569 *
54570 * Note that older browser may not like the variable name `var`. In that
54571 * case, the function can be called as `math['var'](...)` instead of
54572 * `math.var(...)`.
54573 *
54574 * Syntax:
54575 *
54576 * math.variance(a, b, c, ...)
54577 * math.variance(A)
54578 * math.variance(A, normalization)
54579 * math.variance(A, dimension)
54580 * math.variance(A, dimension, normalization)
54581 *
54582 * Examples:
54583 *
54584 * math.variance(2, 4, 6) // returns 4
54585 * math.variance([2, 4, 6, 8]) // returns 6.666666666666667
54586 * math.variance([2, 4, 6, 8], 'uncorrected') // returns 5
54587 * math.variance([2, 4, 6, 8], 'biased') // returns 4
54588 *
54589 * math.variance([[1, 2, 3], [4, 5, 6]]) // returns 3.5
54590 * math.variance([[1, 2, 3], [4, 6, 8]], 0) // returns [4.5, 8, 12.5]
54591 * math.variance([[1, 2, 3], [4, 6, 8]], 1) // returns [1, 4]
54592 * math.variance([[1, 2, 3], [4, 6, 8]], 1, 'biased') // returns [0.5, 2]
54593 *
54594 * See also:
54595 *
54596 * mean, median, max, min, prod, std, sum
54597 *
54598 * @param {Array | Matrix} array
54599 * A single matrix or or multiple scalar values
54600 * @param {string} [normalization='unbiased']
54601 * Determines how to normalize the variance.
54602 * Choose 'unbiased' (default), 'uncorrected', or 'biased'.
54603 * @param dimension {number | BigNumber}
54604 * Determines the axis to compute the variance for a matrix
54605 * @return {*} The variance
54606 */
54607 return typed(variance_name, {
54608 // variance([a, b, c, d, ...])
54609 'Array | Matrix': function ArrayMatrix(array) {
54610 return _var(array, DEFAULT_NORMALIZATION);
54611 },
54612 // variance([a, b, c, d, ...], normalization)
54613 'Array | Matrix, string': _var,
54614 // variance([a, b, c, c, ...], dim)
54615 'Array | Matrix, number | BigNumber': function ArrayMatrixNumberBigNumber(array, dim) {
54616 return _varDim(array, dim, DEFAULT_NORMALIZATION);
54617 },
54618 // variance([a, b, c, c, ...], dim, normalization)
54619 'Array | Matrix, number | BigNumber, string': _varDim,
54620 // variance(a, b, c, d, ...)
54621 '...': function _(args) {
54622 return _var(args, DEFAULT_NORMALIZATION);
54623 }
54624 });
54625 /**
54626 * Recursively calculate the variance of an n-dimensional array
54627 * @param {Array} array
54628 * @param {string} normalization
54629 * Determines how to normalize the variance:
54630 * - 'unbiased' The sum of squared errors is divided by (n - 1)
54631 * - 'uncorrected' The sum of squared errors is divided by n
54632 * - 'biased' The sum of squared errors is divided by (n + 1)
54633 * @return {number | BigNumber} variance
54634 * @private
54635 */
54636
54637 function _var(array, normalization) {
54638 var sum = 0;
54639 var num = 0;
54640
54641 if (array.length === 0) {
54642 throw new SyntaxError('Function variance requires one or more parameters (0 provided)');
54643 } // calculate the mean and number of elements
54644
54645
54646 deepForEach(array, function (value) {
54647 try {
54648 sum = add(sum, value);
54649 num++;
54650 } catch (err) {
54651 throw improveErrorMessage(err, 'variance', value);
54652 }
54653 });
54654 if (num === 0) throw new Error('Cannot calculate variance of an empty array');
54655 var mean = divide(sum, num); // calculate the variance
54656
54657 sum = 0;
54658 deepForEach(array, function (value) {
54659 var diff = subtract(value, mean);
54660 sum = add(sum, multiply(diff, diff));
54661 });
54662
54663 if (isNaN(sum)) {
54664 return sum;
54665 }
54666
54667 switch (normalization) {
54668 case 'uncorrected':
54669 return divide(sum, num);
54670
54671 case 'biased':
54672 return divide(sum, num + 1);
54673
54674 case 'unbiased':
54675 {
54676 var zero = Object(is["e" /* isBigNumber */])(sum) ? sum.mul(0) : 0;
54677 return num === 1 ? zero : divide(sum, num - 1);
54678 }
54679
54680 default:
54681 throw new Error('Unknown normalization "' + normalization + '". ' + 'Choose "unbiased" (default), "uncorrected", or "biased".');
54682 }
54683 }
54684
54685 function _varDim(array, dim, normalization) {
54686 try {
54687 if (array.length === 0) {
54688 throw new SyntaxError('Function variance requires one or more parameters (0 provided)');
54689 }
54690
54691 return apply(array, dim, function (x) {
54692 return _var(x, normalization);
54693 });
54694 } catch (err) {
54695 throw improveErrorMessage(err, 'variance');
54696 }
54697 }
54698}); // For backward compatibility, deprecated since version 6.0.0. Date: 2018-11-09
54699
54700var createDeprecatedVar =
54701/* #__PURE__ */
54702Object(factory["a" /* factory */])('var', ['variance'], function (_ref2) {
54703 var variance = _ref2.variance;
54704 return function () {
54705 Object(utils_log["a" /* warnOnce */])('Function "var" has been renamed to "variance" in v6.0.0, please use the new function instead.');
54706
54707 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
54708 args[_key] = arguments[_key];
54709 }
54710
54711 return variance.apply(variance, args);
54712 };
54713});
54714// CONCATENATED MODULE: ./src/function/statistics/quantileSeq.js
54715
54716
54717
54718
54719var quantileSeq_name = 'quantileSeq';
54720var quantileSeq_dependencies = ['typed', 'add', 'multiply', 'partitionSelect', 'compare'];
54721var createQuantileSeq =
54722/* #__PURE__ */
54723Object(factory["a" /* factory */])(quantileSeq_name, quantileSeq_dependencies, function (_ref) {
54724 var typed = _ref.typed,
54725 add = _ref.add,
54726 multiply = _ref.multiply,
54727 partitionSelect = _ref.partitionSelect,
54728 compare = _ref.compare;
54729
54730 /**
54731 * Compute the prob order quantile of a matrix or a list with values.
54732 * The sequence is sorted and the middle value is returned.
54733 * Supported types of sequence values are: Number, BigNumber, Unit
54734 * Supported types of probability are: Number, BigNumber
54735 *
54736 * In case of a (multi dimensional) array or matrix, the prob order quantile
54737 * of all elements will be calculated.
54738 *
54739 * Syntax:
54740 *
54741 * math.quantileSeq(A, prob[, sorted])
54742 * math.quantileSeq(A, [prob1, prob2, ...][, sorted])
54743 * math.quantileSeq(A, N[, sorted])
54744 *
54745 * Examples:
54746 *
54747 * math.quantileSeq([3, -1, 5, 7], 0.5) // returns 4
54748 * math.quantileSeq([3, -1, 5, 7], [1/3, 2/3]) // returns [3, 5]
54749 * math.quantileSeq([3, -1, 5, 7], 2) // returns [3, 5]
54750 * math.quantileSeq([-1, 3, 5, 7], 0.5, true) // returns 4
54751 *
54752 * See also:
54753 *
54754 * median, mean, min, max, sum, prod, std, variance
54755 *
54756 * @param {Array, Matrix} data A single matrix or Array
54757 * @param {Number, BigNumber, Array} probOrN prob is the order of the quantile, while N is
54758 * the amount of evenly distributed steps of
54759 * probabilities; only one of these options can
54760 * be provided
54761 * @param {Boolean} sorted=false is data sorted in ascending order
54762 * @return {Number, BigNumber, Unit, Array} Quantile(s)
54763 */
54764 function quantileSeq(data, probOrN, sorted) {
54765 var probArr, dataArr, one;
54766
54767 if (arguments.length < 2 || arguments.length > 3) {
54768 throw new SyntaxError('Function quantileSeq requires two or three parameters');
54769 }
54770
54771 if (Object(is["i" /* isCollection */])(data)) {
54772 sorted = sorted || false;
54773
54774 if (typeof sorted === 'boolean') {
54775 dataArr = data.valueOf();
54776
54777 if (Object(is["y" /* isNumber */])(probOrN)) {
54778 if (probOrN < 0) {
54779 throw new Error('N/prob must be non-negative');
54780 }
54781
54782 if (probOrN <= 1) {
54783 // quantileSeq([a, b, c, d, ...], prob[,sorted])
54784 return _quantileSeq(dataArr, probOrN, sorted);
54785 }
54786
54787 if (probOrN > 1) {
54788 // quantileSeq([a, b, c, d, ...], N[,sorted])
54789 if (!Object(utils_number["i" /* isInteger */])(probOrN)) {
54790 throw new Error('N must be a positive integer');
54791 }
54792
54793 var nPlusOne = probOrN + 1;
54794 probArr = new Array(probOrN);
54795
54796 for (var i = 0; i < probOrN;) {
54797 probArr[i] = _quantileSeq(dataArr, ++i / nPlusOne, sorted);
54798 }
54799
54800 return probArr;
54801 }
54802 }
54803
54804 if (Object(is["e" /* isBigNumber */])(probOrN)) {
54805 var BigNumber = probOrN.constructor;
54806
54807 if (probOrN.isNegative()) {
54808 throw new Error('N/prob must be non-negative');
54809 }
54810
54811 one = new BigNumber(1);
54812
54813 if (probOrN.lte(one)) {
54814 // quantileSeq([a, b, c, d, ...], prob[,sorted])
54815 return new BigNumber(_quantileSeq(dataArr, probOrN, sorted));
54816 }
54817
54818 if (probOrN.gt(one)) {
54819 // quantileSeq([a, b, c, d, ...], N[,sorted])
54820 if (!probOrN.isInteger()) {
54821 throw new Error('N must be a positive integer');
54822 } // largest possible Array length is 2^32-1
54823 // 2^32 < 10^15, thus safe conversion guaranteed
54824
54825
54826 var intN = probOrN.toNumber();
54827
54828 if (intN > 4294967295) {
54829 throw new Error('N must be less than or equal to 2^32-1, as that is the maximum length of an Array');
54830 }
54831
54832 var _nPlusOne = new BigNumber(intN + 1);
54833
54834 probArr = new Array(intN);
54835
54836 for (var _i = 0; _i < intN;) {
54837 probArr[_i] = new BigNumber(_quantileSeq(dataArr, new BigNumber(++_i).div(_nPlusOne), sorted));
54838 }
54839
54840 return probArr;
54841 }
54842 }
54843
54844 if (Array.isArray(probOrN)) {
54845 // quantileSeq([a, b, c, d, ...], [prob1, prob2, ...][,sorted])
54846 probArr = new Array(probOrN.length);
54847
54848 for (var _i2 = 0; _i2 < probArr.length; ++_i2) {
54849 var currProb = probOrN[_i2];
54850
54851 if (Object(is["y" /* isNumber */])(currProb)) {
54852 if (currProb < 0 || currProb > 1) {
54853 throw new Error('Probability must be between 0 and 1, inclusive');
54854 }
54855 } else if (Object(is["e" /* isBigNumber */])(currProb)) {
54856 one = new currProb.constructor(1);
54857
54858 if (currProb.isNegative() || currProb.gt(one)) {
54859 throw new Error('Probability must be between 0 and 1, inclusive');
54860 }
54861 } else {
54862 throw new TypeError('Unexpected type of argument in function quantileSeq'); // FIXME: becomes redundant when converted to typed-function
54863 }
54864
54865 probArr[_i2] = _quantileSeq(dataArr, currProb, sorted);
54866 }
54867
54868 return probArr;
54869 }
54870
54871 throw new TypeError('Unexpected type of argument in function quantileSeq'); // FIXME: becomes redundant when converted to typed-function
54872 }
54873
54874 throw new TypeError('Unexpected type of argument in function quantileSeq'); // FIXME: becomes redundant when converted to typed-function
54875 }
54876
54877 throw new TypeError('Unexpected type of argument in function quantileSeq'); // FIXME: becomes redundant when converted to typed-function
54878 }
54879 /**
54880 * Calculate the prob order quantile of an n-dimensional array.
54881 *
54882 * @param {Array} array
54883 * @param {Number, BigNumber} prob
54884 * @param {Boolean} sorted
54885 * @return {Number, BigNumber, Unit} prob order quantile
54886 * @private
54887 */
54888
54889
54890 function _quantileSeq(array, prob, sorted) {
54891 var flat = Object(utils_array["e" /* flatten */])(array);
54892 var len = flat.length;
54893
54894 if (len === 0) {
54895 throw new Error('Cannot calculate quantile of an empty sequence');
54896 }
54897
54898 if (Object(is["y" /* isNumber */])(prob)) {
54899 var _index = prob * (len - 1);
54900
54901 var _fracPart = _index % 1;
54902
54903 if (_fracPart === 0) {
54904 var value = sorted ? flat[_index] : partitionSelect(flat, _index);
54905 validate(value);
54906 return value;
54907 }
54908
54909 var _integerPart = Math.floor(_index);
54910
54911 var _left;
54912
54913 var _right;
54914
54915 if (sorted) {
54916 _left = flat[_integerPart];
54917 _right = flat[_integerPart + 1];
54918 } else {
54919 _right = partitionSelect(flat, _integerPart + 1); // max of partition is kth largest
54920
54921 _left = flat[_integerPart];
54922
54923 for (var i = 0; i < _integerPart; ++i) {
54924 if (compare(flat[i], _left) > 0) {
54925 _left = flat[i];
54926 }
54927 }
54928 }
54929
54930 validate(_left);
54931 validate(_right); // Q(prob) = (1-f)*A[floor(index)] + f*A[floor(index)+1]
54932
54933 return add(multiply(_left, 1 - _fracPart), multiply(_right, _fracPart));
54934 } // If prob is a BigNumber
54935
54936
54937 var index = prob.times(len - 1);
54938
54939 if (index.isInteger()) {
54940 index = index.toNumber();
54941
54942 var _value = sorted ? flat[index] : partitionSelect(flat, index);
54943
54944 validate(_value);
54945 return _value;
54946 }
54947
54948 var integerPart = index.floor();
54949 var fracPart = index.minus(integerPart);
54950 var integerPartNumber = integerPart.toNumber();
54951 var left;
54952 var right;
54953
54954 if (sorted) {
54955 left = flat[integerPartNumber];
54956 right = flat[integerPartNumber + 1];
54957 } else {
54958 right = partitionSelect(flat, integerPartNumber + 1); // max of partition is kth largest
54959
54960 left = flat[integerPartNumber];
54961
54962 for (var _i3 = 0; _i3 < integerPartNumber; ++_i3) {
54963 if (compare(flat[_i3], left) > 0) {
54964 left = flat[_i3];
54965 }
54966 }
54967 }
54968
54969 validate(left);
54970 validate(right); // Q(prob) = (1-f)*A[floor(index)] + f*A[floor(index)+1]
54971
54972 var one = new fracPart.constructor(1);
54973 return add(multiply(left, one.minus(fracPart)), multiply(right, fracPart));
54974 }
54975 /**
54976 * Check if array value types are valid, throw error otherwise.
54977 * @param {number | BigNumber | Unit} x
54978 * @param {number | BigNumber | Unit} x
54979 * @private
54980 */
54981
54982
54983 var validate = typed({
54984 'number | BigNumber | Unit': function numberBigNumberUnit(x) {
54985 return x;
54986 }
54987 });
54988 return quantileSeq;
54989});
54990// CONCATENATED MODULE: ./src/function/statistics/std.js
54991
54992var std_name = 'std';
54993var std_dependencies = ['typed', 'sqrt', 'variance'];
54994var createStd =
54995/* #__PURE__ */
54996Object(factory["a" /* factory */])(std_name, std_dependencies, function (_ref) {
54997 var typed = _ref.typed,
54998 sqrt = _ref.sqrt,
54999 variance = _ref.variance;
55000
55001 /**
55002 * Compute the standard deviation of a matrix or a list with values.
55003 * The standard deviations is defined as the square root of the variance:
55004 * `std(A) = sqrt(variance(A))`.
55005 * In case of a (multi dimensional) array or matrix, the standard deviation
55006 * over all elements will be calculated by default, unless an axis is specified
55007 * in which case the standard deviation will be computed along that axis.
55008 *
55009 * Additionally, it is possible to compute the standard deviation along the rows
55010 * or columns of a matrix by specifying the dimension as the second argument.
55011 *
55012 * Optionally, the type of normalization can be specified as the final
55013 * parameter. The parameter `normalization` can be one of the following values:
55014 *
55015 * - 'unbiased' (default) The sum of squared errors is divided by (n - 1)
55016 * - 'uncorrected' The sum of squared errors is divided by n
55017 * - 'biased' The sum of squared errors is divided by (n + 1)
55018 *
55019 *
55020 * Syntax:
55021 *
55022 * math.std(a, b, c, ...)
55023 * math.std(A)
55024 * math.std(A, normalization)
55025 * math.std(A, dimension)
55026 * math.std(A, dimension, normalization)
55027 *
55028 * Examples:
55029 *
55030 * math.std(2, 4, 6) // returns 2
55031 * math.std([2, 4, 6, 8]) // returns 2.581988897471611
55032 * math.std([2, 4, 6, 8], 'uncorrected') // returns 2.23606797749979
55033 * math.std([2, 4, 6, 8], 'biased') // returns 2
55034 *
55035 * math.std([[1, 2, 3], [4, 5, 6]]) // returns 1.8708286933869707
55036 * math.std([[1, 2, 3], [4, 6, 8]], 0) // returns [2.1213203435596424, 2.8284271247461903, 3.5355339059327378]
55037 * math.std([[1, 2, 3], [4, 6, 8]], 1) // returns [1, 2]
55038 * math.std([[1, 2, 3], [4, 6, 8]], 1, 'biased') // returns [0.7071067811865476, 1.4142135623730951]
55039 *
55040 * See also:
55041 *
55042 * mean, median, max, min, prod, sum, variance
55043 *
55044 * @param {Array | Matrix} array
55045 * A single matrix or or multiple scalar values
55046 * @param {string} [normalization='unbiased']
55047 * Determines how to normalize the variance.
55048 * Choose 'unbiased' (default), 'uncorrected', or 'biased'.
55049 * @param dimension {number | BigNumber}
55050 * Determines the axis to compute the standard deviation for a matrix
55051 * @return {*} The standard deviation
55052 */
55053 return typed(std_name, {
55054 // std([a, b, c, d, ...])
55055 'Array | Matrix': _std,
55056 // std([a, b, c, d, ...], normalization)
55057 'Array | Matrix, string': _std,
55058 // std([a, b, c, c, ...], dim)
55059 'Array | Matrix, number | BigNumber': _std,
55060 // std([a, b, c, c, ...], dim, normalization)
55061 'Array | Matrix, number | BigNumber, string': _std,
55062 // std(a, b, c, d, ...)
55063 '...': function _(args) {
55064 return _std(args);
55065 }
55066 });
55067
55068 function _std(array, normalization) {
55069 if (array.length === 0) {
55070 throw new SyntaxError('Function std requires one or more parameters (0 provided)');
55071 }
55072
55073 try {
55074 return sqrt(variance.apply(null, arguments));
55075 } catch (err) {
55076 if (err instanceof TypeError && err.message.indexOf(' variance') !== -1) {
55077 throw new TypeError(err.message.replace(' variance', ' std'));
55078 } else {
55079 throw err;
55080 }
55081 }
55082 }
55083});
55084// CONCATENATED MODULE: ./src/utils/product.js
55085/** @param {number} i
55086 * @param {number} n
55087 * @returns {number} product of i to n
55088 */
55089function product_product(i, n) {
55090 if (n < i) {
55091 return 1;
55092 }
55093
55094 if (n === i) {
55095 return n;
55096 }
55097
55098 var half = n + i >> 1; // divide (n + i) by 2 and truncate to integer
55099
55100 return product_product(i, half) * product_product(half + 1, n);
55101}
55102// CONCATENATED MODULE: ./src/plain/number/combinations.js
55103
55104
55105function combinationsNumber(n, k) {
55106 if (!Object(utils_number["i" /* isInteger */])(n) || n < 0) {
55107 throw new TypeError('Positive integer value expected in function combinations');
55108 }
55109
55110 if (!Object(utils_number["i" /* isInteger */])(k) || k < 0) {
55111 throw new TypeError('Positive integer value expected in function combinations');
55112 }
55113
55114 if (k > n) {
55115 throw new TypeError('k must be less than or equal to n');
55116 }
55117
55118 var nMinusk = n - k;
55119 var prodrange;
55120
55121 if (k < nMinusk) {
55122 prodrange = product_product(nMinusk + 1, n);
55123 return prodrange / product_product(1, k);
55124 }
55125
55126 prodrange = product_product(k + 1, n);
55127 return prodrange / product_product(1, nMinusk);
55128}
55129combinationsNumber.signature = 'number, number';
55130// CONCATENATED MODULE: ./src/function/probability/combinations.js
55131
55132
55133var combinations_name = 'combinations';
55134var combinations_dependencies = ['typed'];
55135var createCombinations =
55136/* #__PURE__ */
55137Object(factory["a" /* factory */])(combinations_name, combinations_dependencies, function (_ref) {
55138 var typed = _ref.typed;
55139
55140 /**
55141 * Compute the number of ways of picking `k` unordered outcomes from `n`
55142 * possibilities.
55143 *
55144 * Combinations only takes integer arguments.
55145 * The following condition must be enforced: k <= n.
55146 *
55147 * Syntax:
55148 *
55149 * math.combinations(n, k)
55150 *
55151 * Examples:
55152 *
55153 * math.combinations(7, 5) // returns 21
55154 *
55155 * See also:
55156 *
55157 * combinationsWithRep, permutations, factorial
55158 *
55159 * @param {number | BigNumber} n Total number of objects in the set
55160 * @param {number | BigNumber} k Number of objects in the subset
55161 * @return {number | BigNumber} Number of possible combinations.
55162 */
55163 return typed(combinations_name, {
55164 'number, number': combinationsNumber,
55165 'BigNumber, BigNumber': function BigNumberBigNumber(n, k) {
55166 var BigNumber = n.constructor;
55167 var result, i;
55168 var nMinusk = n.minus(k);
55169 var one = new BigNumber(1);
55170
55171 if (!isPositiveInteger(n) || !isPositiveInteger(k)) {
55172 throw new TypeError('Positive integer value expected in function combinations');
55173 }
55174
55175 if (k.gt(n)) {
55176 throw new TypeError('k must be less than n in function combinations');
55177 }
55178
55179 result = one;
55180
55181 if (k.lt(nMinusk)) {
55182 for (i = one; i.lte(nMinusk); i = i.plus(one)) {
55183 result = result.times(k.plus(i)).dividedBy(i);
55184 }
55185 } else {
55186 for (i = one; i.lte(k); i = i.plus(one)) {
55187 result = result.times(nMinusk.plus(i)).dividedBy(i);
55188 }
55189 }
55190
55191 return result;
55192 } // TODO: implement support for collection in combinations
55193
55194 });
55195});
55196/**
55197 * Test whether BigNumber n is a positive integer
55198 * @param {BigNumber} n
55199 * @returns {boolean} isPositiveInteger
55200 */
55201
55202function isPositiveInteger(n) {
55203 return n.isInteger() && n.gte(0);
55204}
55205// CONCATENATED MODULE: ./src/function/probability/combinationsWithRep.js
55206
55207
55208
55209var combinationsWithRep_name = 'combinationsWithRep';
55210var combinationsWithRep_dependencies = ['typed'];
55211var createCombinationsWithRep =
55212/* #__PURE__ */
55213Object(factory["a" /* factory */])(combinationsWithRep_name, combinationsWithRep_dependencies, function (_ref) {
55214 var typed = _ref.typed;
55215
55216 /**
55217 * Compute the number of ways of picking `k` unordered outcomes from `n`
55218 * possibilities, allowing individual outcomes to be repeated more than once.
55219 *
55220 * CombinationsWithRep only takes integer arguments.
55221 * The following condition must be enforced: k <= n + k -1.
55222 *
55223 * Syntax:
55224 *
55225 * math.combinationsWithRep(n, k)
55226 *
55227 * Examples:
55228 *
55229 * math.combinationsWithRep(7, 5) // returns 462
55230 *
55231 * See also:
55232 *
55233 * combinations, permutations, factorial
55234 *
55235 * @param {number | BigNumber} n Total number of objects in the set
55236 * @param {number | BigNumber} k Number of objects in the subset
55237 * @return {number | BigNumber} Number of possible combinations with replacement.
55238 */
55239 return typed(combinationsWithRep_name, {
55240 'number, number': function numberNumber(n, k) {
55241 if (!Object(utils_number["i" /* isInteger */])(n) || n < 0) {
55242 throw new TypeError('Positive integer value expected in function combinationsWithRep');
55243 }
55244
55245 if (!Object(utils_number["i" /* isInteger */])(k) || k < 0) {
55246 throw new TypeError('Positive integer value expected in function combinationsWithRep');
55247 }
55248
55249 if (n < 1) {
55250 throw new TypeError('k must be less than or equal to n + k - 1');
55251 }
55252
55253 if (k < n - 1) {
55254 var _prodrange = product_product(n, n + k - 1);
55255
55256 return _prodrange / product_product(1, k);
55257 }
55258
55259 var prodrange = product_product(k + 1, n + k - 1);
55260 return prodrange / product_product(1, n - 1);
55261 },
55262 'BigNumber, BigNumber': function BigNumberBigNumber(n, k) {
55263 var BigNumber = n.constructor;
55264 var result, i;
55265 var one = new BigNumber(1);
55266 var nMinusOne = n.minus(one);
55267
55268 if (!combinationsWithRep_isPositiveInteger(n) || !combinationsWithRep_isPositiveInteger(k)) {
55269 throw new TypeError('Positive integer value expected in function combinationsWithRep');
55270 }
55271
55272 if (n.lt(one)) {
55273 throw new TypeError('k must be less than or equal to n + k - 1 in function combinationsWithRep');
55274 }
55275
55276 result = one;
55277
55278 if (k.lt(nMinusOne)) {
55279 for (i = one; i.lte(nMinusOne); i = i.plus(one)) {
55280 result = result.times(k.plus(i)).dividedBy(i);
55281 }
55282 } else {
55283 for (i = one; i.lte(k); i = i.plus(one)) {
55284 result = result.times(nMinusOne.plus(i)).dividedBy(i);
55285 }
55286 }
55287
55288 return result;
55289 }
55290 });
55291});
55292/**
55293 * Test whether BigNumber n is a positive integer
55294 * @param {BigNumber} n
55295 * @returns {boolean} isPositiveInteger
55296 */
55297
55298function combinationsWithRep_isPositiveInteger(n) {
55299 return n.isInteger() && n.gte(0);
55300}
55301// CONCATENATED MODULE: ./src/plain/number/probability.js
55302
55303
55304function gammaNumber(n) {
55305 var x;
55306
55307 if (Object(utils_number["i" /* isInteger */])(n)) {
55308 if (n <= 0) {
55309 return isFinite(n) ? Infinity : NaN;
55310 }
55311
55312 if (n > 171) {
55313 return Infinity; // Will overflow
55314 }
55315
55316 return product_product(1, n - 1);
55317 }
55318
55319 if (n < 0.5) {
55320 return Math.PI / (Math.sin(Math.PI * n) * gammaNumber(1 - n));
55321 }
55322
55323 if (n >= 171.35) {
55324 return Infinity; // will overflow
55325 }
55326
55327 if (n > 85.0) {
55328 // Extended Stirling Approx
55329 var twoN = n * n;
55330 var threeN = twoN * n;
55331 var fourN = threeN * n;
55332 var fiveN = fourN * n;
55333 return Math.sqrt(2 * Math.PI / n) * Math.pow(n / Math.E, n) * (1 + 1 / (12 * n) + 1 / (288 * twoN) - 139 / (51840 * threeN) - 571 / (2488320 * fourN) + 163879 / (209018880 * fiveN) + 5246819 / (75246796800 * fiveN * n));
55334 }
55335
55336 --n;
55337 x = gammaP[0];
55338
55339 for (var i = 1; i < gammaP.length; ++i) {
55340 x += gammaP[i] / (n + i);
55341 }
55342
55343 var t = n + gammaG + 0.5;
55344 return Math.sqrt(2 * Math.PI) * Math.pow(t, n + 0.5) * Math.exp(-t) * x;
55345}
55346gammaNumber.signature = 'number'; // TODO: comment on the variables g and p
55347
55348var gammaG = 4.7421875;
55349var gammaP = [0.99999999999999709182, 57.156235665862923517, -59.597960355475491248, 14.136097974741747174, -0.49191381609762019978, 0.33994649984811888699e-4, 0.46523628927048575665e-4, -0.98374475304879564677e-4, 0.15808870322491248884e-3, -0.21026444172410488319e-3, 0.21743961811521264320e-3, -0.16431810653676389022e-3, 0.84418223983852743293e-4, -0.26190838401581408670e-4, 0.36899182659531622704e-5];
55350// CONCATENATED MODULE: ./src/function/probability/gamma.js
55351
55352
55353
55354var gamma_name = 'gamma';
55355var gamma_dependencies = ['typed', 'config', 'multiplyScalar', 'pow', 'BigNumber', 'Complex'];
55356var createGamma =
55357/* #__PURE__ */
55358Object(factory["a" /* factory */])(gamma_name, gamma_dependencies, function (_ref) {
55359 var typed = _ref.typed,
55360 config = _ref.config,
55361 multiplyScalar = _ref.multiplyScalar,
55362 pow = _ref.pow,
55363 _BigNumber = _ref.BigNumber,
55364 _Complex = _ref.Complex;
55365
55366 /**
55367 * Compute the gamma function of a value using Lanczos approximation for
55368 * small values, and an extended Stirling approximation for large values.
55369 *
55370 * For matrices, the function is evaluated element wise.
55371 *
55372 * Syntax:
55373 *
55374 * math.gamma(n)
55375 *
55376 * Examples:
55377 *
55378 * math.gamma(5) // returns 24
55379 * math.gamma(-0.5) // returns -3.5449077018110335
55380 * math.gamma(math.i) // returns -0.15494982830180973 - 0.49801566811835596i
55381 *
55382 * See also:
55383 *
55384 * combinations, factorial, permutations
55385 *
55386 * @param {number | Array | Matrix} n A real or complex number
55387 * @return {number | Array | Matrix} The gamma of `n`
55388 */
55389 var gamma = typed(gamma_name, {
55390 number: gammaNumber,
55391 Complex: function Complex(n) {
55392 if (n.im === 0) {
55393 return gamma(n.re);
55394 }
55395
55396 n = new _Complex(n.re - 1, n.im);
55397 var x = new _Complex(gammaP[0], 0);
55398
55399 for (var i = 1; i < gammaP.length; ++i) {
55400 var real = n.re + i; // x += p[i]/(n+i)
55401
55402 var den = real * real + n.im * n.im;
55403
55404 if (den !== 0) {
55405 x.re += gammaP[i] * real / den;
55406 x.im += -(gammaP[i] * n.im) / den;
55407 } else {
55408 x.re = gammaP[i] < 0 ? -Infinity : Infinity;
55409 }
55410 }
55411
55412 var t = new _Complex(n.re + gammaG + 0.5, n.im);
55413 var twoPiSqrt = Math.sqrt(2 * Math.PI);
55414 n.re += 0.5;
55415 var result = pow(t, n);
55416
55417 if (result.im === 0) {
55418 // sqrt(2*PI)*result
55419 result.re *= twoPiSqrt;
55420 } else if (result.re === 0) {
55421 result.im *= twoPiSqrt;
55422 } else {
55423 result.re *= twoPiSqrt;
55424 result.im *= twoPiSqrt;
55425 }
55426
55427 var r = Math.exp(-t.re); // exp(-t)
55428
55429 t.re = r * Math.cos(-t.im);
55430 t.im = r * Math.sin(-t.im);
55431 return multiplyScalar(multiplyScalar(result, t), x);
55432 },
55433 BigNumber: function BigNumber(n) {
55434 if (n.isInteger()) {
55435 return n.isNegative() || n.isZero() ? new _BigNumber(Infinity) : bigFactorial(n.minus(1));
55436 }
55437
55438 if (!n.isFinite()) {
55439 return new _BigNumber(n.isNegative() ? NaN : Infinity);
55440 }
55441
55442 throw new Error('Integer BigNumber expected');
55443 },
55444 'Array | Matrix': function ArrayMatrix(n) {
55445 return deepMap(n, gamma);
55446 }
55447 });
55448 /**
55449 * Calculate factorial for a BigNumber
55450 * @param {BigNumber} n
55451 * @returns {BigNumber} Returns the factorial of n
55452 */
55453
55454 function bigFactorial(n) {
55455 if (n.isZero()) {
55456 return new _BigNumber(1); // 0! is per definition 1
55457 }
55458
55459 var precision = config.precision + (Math.log(n.toNumber()) | 0);
55460
55461 var Big = _BigNumber.clone({
55462 precision: precision
55463 });
55464
55465 var res = new Big(n);
55466 var value = n.toNumber() - 1; // number
55467
55468 while (value > 1) {
55469 res = res.times(value);
55470 value--;
55471 }
55472
55473 return new _BigNumber(res.toPrecision(_BigNumber.precision));
55474 }
55475
55476 return gamma;
55477});
55478// CONCATENATED MODULE: ./src/function/probability/factorial.js
55479
55480
55481var factorial_name = 'factorial';
55482var factorial_dependencies = ['typed', 'gamma'];
55483var createFactorial =
55484/* #__PURE__ */
55485Object(factory["a" /* factory */])(factorial_name, factorial_dependencies, function (_ref) {
55486 var typed = _ref.typed,
55487 gamma = _ref.gamma;
55488
55489 /**
55490 * Compute the factorial of a value
55491 *
55492 * Factorial only supports an integer value as argument.
55493 * For matrices, the function is evaluated element wise.
55494 *
55495 * Syntax:
55496 *
55497 * math.factorial(n)
55498 *
55499 * Examples:
55500 *
55501 * math.factorial(5) // returns 120
55502 * math.factorial(3) // returns 6
55503 *
55504 * See also:
55505 *
55506 * combinations, combinationsWithRep, gamma, permutations
55507 *
55508 * @param {number | BigNumber | Array | Matrix} n An integer number
55509 * @return {number | BigNumber | Array | Matrix} The factorial of `n`
55510 */
55511 var factorial = typed(factorial_name, {
55512 number: function number(n) {
55513 if (n < 0) {
55514 throw new Error('Value must be non-negative');
55515 }
55516
55517 return gamma(n + 1);
55518 },
55519 BigNumber: function BigNumber(n) {
55520 if (n.isNegative()) {
55521 throw new Error('Value must be non-negative');
55522 }
55523
55524 return gamma(n.plus(1));
55525 },
55526 'Array | Matrix': function ArrayMatrix(n) {
55527 return deepMap(n, factorial);
55528 }
55529 });
55530 return factorial;
55531});
55532// CONCATENATED MODULE: ./src/function/probability/kldivergence.js
55533
55534var kldivergence_name = 'kldivergence';
55535var kldivergence_dependencies = ['typed', 'matrix', 'divide', 'sum', 'multiply', 'dotDivide', 'log', 'isNumeric'];
55536var createKldivergence =
55537/* #__PURE__ */
55538Object(factory["a" /* factory */])(kldivergence_name, kldivergence_dependencies, function (_ref) {
55539 var typed = _ref.typed,
55540 matrix = _ref.matrix,
55541 divide = _ref.divide,
55542 sum = _ref.sum,
55543 multiply = _ref.multiply,
55544 dotDivide = _ref.dotDivide,
55545 log = _ref.log,
55546 isNumeric = _ref.isNumeric;
55547
55548 /**
55549 * Calculate the Kullback-Leibler (KL) divergence between two distributions
55550 *
55551 * Syntax:
55552 *
55553 * math.kldivergence(x, y)
55554 *
55555 * Examples:
55556 *
55557 * math.kldivergence([0.7,0.5,0.4], [0.2,0.9,0.5]) //returns 0.24376698773121153
55558 *
55559 *
55560 * @param {Array | Matrix} q First vector
55561 * @param {Array | Matrix} p Second vector
55562 * @return {number} Returns distance between q and p
55563 */
55564 return typed(kldivergence_name, {
55565 'Array, Array': function ArrayArray(q, p) {
55566 return _kldiv(matrix(q), matrix(p));
55567 },
55568 'Matrix, Array': function MatrixArray(q, p) {
55569 return _kldiv(q, matrix(p));
55570 },
55571 'Array, Matrix': function ArrayMatrix(q, p) {
55572 return _kldiv(matrix(q), p);
55573 },
55574 'Matrix, Matrix': function MatrixMatrix(q, p) {
55575 return _kldiv(q, p);
55576 }
55577 });
55578
55579 function _kldiv(q, p) {
55580 var plength = p.size().length;
55581 var qlength = q.size().length;
55582
55583 if (plength > 1) {
55584 throw new Error('first object must be one dimensional');
55585 }
55586
55587 if (qlength > 1) {
55588 throw new Error('second object must be one dimensional');
55589 }
55590
55591 if (plength !== qlength) {
55592 throw new Error('Length of two vectors must be equal');
55593 } // Before calculation, apply normalization
55594
55595
55596 var sumq = sum(q);
55597
55598 if (sumq === 0) {
55599 throw new Error('Sum of elements in first object must be non zero');
55600 }
55601
55602 var sump = sum(p);
55603
55604 if (sump === 0) {
55605 throw new Error('Sum of elements in second object must be non zero');
55606 }
55607
55608 var qnorm = divide(q, sum(q));
55609 var pnorm = divide(p, sum(p));
55610 var result = sum(multiply(qnorm, log(dotDivide(qnorm, pnorm))));
55611
55612 if (isNumeric(result)) {
55613 return result;
55614 } else {
55615 return Number.NaN;
55616 }
55617 }
55618});
55619// CONCATENATED MODULE: ./src/function/probability/multinomial.js
55620
55621
55622var multinomial_name = 'multinomial';
55623var multinomial_dependencies = ['typed', 'add', 'divide', 'multiply', 'factorial', 'isInteger', 'isPositive'];
55624var createMultinomial =
55625/* #__PURE__ */
55626Object(factory["a" /* factory */])(multinomial_name, multinomial_dependencies, function (_ref) {
55627 var typed = _ref.typed,
55628 add = _ref.add,
55629 divide = _ref.divide,
55630 multiply = _ref.multiply,
55631 factorial = _ref.factorial,
55632 isInteger = _ref.isInteger,
55633 isPositive = _ref.isPositive;
55634
55635 /**
55636 * Multinomial Coefficients compute the number of ways of picking a1, a2, ..., ai unordered outcomes from `n` possibilities.
55637 *
55638 * multinomial takes one array of integers as an argument.
55639 * The following condition must be enforced: every ai <= 0
55640 *
55641 * Syntax:
55642 *
55643 * math.multinomial(a) // a is an array type
55644 *
55645 * Examples:
55646 *
55647 * math.multinomial([1,2,1]) // returns 12
55648 *
55649 * See also:
55650 *
55651 * combinations, factorial
55652 *
55653 * @param {number[] | BigNumber[]} a Integer numbers of objects in the subset
55654 * @return {Number | BigNumber} Multinomial coefficient.
55655 */
55656 return typed(multinomial_name, {
55657 'Array | Matrix': function ArrayMatrix(a) {
55658 var sum = 0;
55659 var denom = 1;
55660 deepForEach(a, function (ai) {
55661 if (!isInteger(ai) || !isPositive(ai)) {
55662 throw new TypeError('Positive integer value expected in function multinomial');
55663 }
55664
55665 sum = add(sum, ai);
55666 denom = multiply(denom, factorial(ai));
55667 });
55668 return divide(factorial(sum), denom);
55669 }
55670 });
55671});
55672// CONCATENATED MODULE: ./src/function/probability/permutations.js
55673
55674
55675
55676var permutations_name = 'permutations';
55677var permutations_dependencies = ['typed', 'factorial'];
55678var createPermutations =
55679/* #__PURE__ */
55680Object(factory["a" /* factory */])(permutations_name, permutations_dependencies, function (_ref) {
55681 var typed = _ref.typed,
55682 factorial = _ref.factorial;
55683
55684 /**
55685 * Compute the number of ways of obtaining an ordered subset of `k` elements
55686 * from a set of `n` elements.
55687 *
55688 * Permutations only takes integer arguments.
55689 * The following condition must be enforced: k <= n.
55690 *
55691 * Syntax:
55692 *
55693 * math.permutations(n)
55694 * math.permutations(n, k)
55695 *
55696 * Examples:
55697 *
55698 * math.permutations(5) // 120
55699 * math.permutations(5, 3) // 60
55700 *
55701 * See also:
55702 *
55703 * combinations, combinationsWithRep, factorial
55704 *
55705 * @param {number | BigNumber} n The number of objects in total
55706 * @param {number | BigNumber} [k] The number of objects in the subset
55707 * @return {number | BigNumber} The number of permutations
55708 */
55709 return typed(permutations_name, {
55710 'number | BigNumber': factorial,
55711 'number, number': function numberNumber(n, k) {
55712 if (!Object(utils_number["i" /* isInteger */])(n) || n < 0) {
55713 throw new TypeError('Positive integer value expected in function permutations');
55714 }
55715
55716 if (!Object(utils_number["i" /* isInteger */])(k) || k < 0) {
55717 throw new TypeError('Positive integer value expected in function permutations');
55718 }
55719
55720 if (k > n) {
55721 throw new TypeError('second argument k must be less than or equal to first argument n');
55722 } // Permute n objects, k at a time
55723
55724
55725 return product_product(n - k + 1, n);
55726 },
55727 'BigNumber, BigNumber': function BigNumberBigNumber(n, k) {
55728 var result, i;
55729
55730 if (!permutations_isPositiveInteger(n) || !permutations_isPositiveInteger(k)) {
55731 throw new TypeError('Positive integer value expected in function permutations');
55732 }
55733
55734 if (k.gt(n)) {
55735 throw new TypeError('second argument k must be less than or equal to first argument n');
55736 }
55737
55738 var one = n.mul(0).add(1);
55739 result = one;
55740
55741 for (i = n.minus(k).plus(1); i.lte(n); i = i.plus(1)) {
55742 result = result.times(i);
55743 }
55744
55745 return result;
55746 } // TODO: implement support for collection in permutations
55747
55748 });
55749});
55750/**
55751 * Test whether BigNumber n is a positive integer
55752 * @param {BigNumber} n
55753 * @returns {boolean} isPositiveInteger
55754 */
55755
55756function permutations_isPositiveInteger(n) {
55757 return n.isInteger() && n.gte(0);
55758}
55759// EXTERNAL MODULE: ./node_modules/seed-random/index.js
55760var seed_random = __webpack_require__(15);
55761var seed_random_default = /*#__PURE__*/__webpack_require__.n(seed_random);
55762
55763// CONCATENATED MODULE: ./src/function/probability/util/seededRNG.js
55764// create a random seed here to prevent an infinite loop from seed-random
55765// inside the factory. Reason is that math.random is defined as a getter/setter
55766// and seed-random generates a seed from the local entropy by reading every
55767// defined object including `math` itself. That means that whilst getting
55768// math.random, it tries to get math.random, etc... an infinite loop.
55769// See https://github.com/ForbesLindesay/seed-random/issues/6
55770
55771var singletonRandom =
55772/* #__PURE__ */
55773seed_random_default()();
55774function createRng(randomSeed) {
55775 var random; // create a new random generator with given seed
55776
55777 function setSeed(seed) {
55778 random = seed === null ? singletonRandom : seed_random_default()(String(seed));
55779 } // initialize a seeded pseudo random number generator with config's random seed
55780
55781
55782 setSeed(randomSeed); // wrapper function so the rng can be updated via generator
55783
55784 function rng() {
55785 return random();
55786 }
55787
55788 return rng;
55789}
55790// CONCATENATED MODULE: ./src/function/probability/pickRandom.js
55791
55792
55793
55794
55795var pickRandom_name = 'pickRandom';
55796var pickRandom_dependencies = ['typed', 'config', '?on'];
55797var createPickRandom =
55798/* #__PURE__ */
55799Object(factory["a" /* factory */])(pickRandom_name, pickRandom_dependencies, function (_ref) {
55800 var typed = _ref.typed,
55801 config = _ref.config,
55802 on = _ref.on;
55803 // seeded pseudo random number generator
55804 var rng = createRng(config.randomSeed);
55805
55806 if (on) {
55807 on('config', function (curr, prev) {
55808 if (curr.randomSeed !== prev.randomSeed) {
55809 rng = createRng(curr.randomSeed);
55810 }
55811 });
55812 }
55813 /**
55814 * Random pick one or more values from a one dimensional array.
55815 * Array elements are picked using a random function with uniform or weighted distribution.
55816 *
55817 * Syntax:
55818 *
55819 * math.pickRandom(array)
55820 * math.pickRandom(array, number)
55821 * math.pickRandom(array, weights)
55822 * math.pickRandom(array, number, weights)
55823 * math.pickRandom(array, weights, number)
55824 *
55825 * Examples:
55826 *
55827 * math.pickRandom([3, 6, 12, 2]) // returns one of the values in the array
55828 * math.pickRandom([3, 6, 12, 2], 2) // returns an array of two of the values in the array
55829 * math.pickRandom([3, 6, 12, 2], [1, 3, 2, 1]) // returns one of the values in the array with weighted distribution
55830 * math.pickRandom([3, 6, 12, 2], 2, [1, 3, 2, 1]) // returns an array of two of the values in the array with weighted distribution
55831 * math.pickRandom([3, 6, 12, 2], [1, 3, 2, 1], 2) // returns an array of two of the values in the array with weighted distribution
55832 *
55833 * See also:
55834 *
55835 * random, randomInt
55836 *
55837 * @param {Array | Matrix} array A one dimensional array
55838 * @param {Int} number An int or float
55839 * @param {Array | Matrix} weights An array of ints or floats
55840 * @return {number | Array} Returns a single random value from array when number is 1 or undefined.
55841 * Returns an array with the configured number of elements when number is > 1.
55842 */
55843
55844
55845 return typed({
55846 'Array | Matrix': function ArrayMatrix(possibles) {
55847 return _pickRandom(possibles);
55848 },
55849 'Array | Matrix, number': function ArrayMatrixNumber(possibles, number) {
55850 return _pickRandom(possibles, number, undefined);
55851 },
55852 'Array | Matrix, Array': function ArrayMatrixArray(possibles, weights) {
55853 return _pickRandom(possibles, undefined, weights);
55854 },
55855 'Array | Matrix, Array | Matrix, number': function ArrayMatrixArrayMatrixNumber(possibles, weights, number) {
55856 return _pickRandom(possibles, number, weights);
55857 },
55858 'Array | Matrix, number, Array | Matrix': function ArrayMatrixNumberArrayMatrix(possibles, number, weights) {
55859 return _pickRandom(possibles, number, weights);
55860 }
55861 });
55862
55863 function _pickRandom(possibles, number, weights) {
55864 var single = typeof number === 'undefined';
55865
55866 if (single) {
55867 number = 1;
55868 }
55869
55870 possibles = possibles.valueOf(); // get Array
55871
55872 if (weights) {
55873 weights = weights.valueOf(); // get Array
55874 }
55875
55876 if (Object(utils_array["a" /* arraySize */])(possibles).length > 1) {
55877 throw new Error('Only one dimensional vectors supported');
55878 }
55879
55880 var totalWeights = 0;
55881
55882 if (typeof weights !== 'undefined') {
55883 if (weights.length !== possibles.length) {
55884 throw new Error('Weights must have the same length as possibles');
55885 }
55886
55887 for (var i = 0, len = weights.length; i < len; i++) {
55888 if (!Object(is["y" /* isNumber */])(weights[i]) || weights[i] < 0) {
55889 throw new Error('Weights must be an array of positive numbers');
55890 }
55891
55892 totalWeights += weights[i];
55893 }
55894 }
55895
55896 var length = possibles.length;
55897
55898 if (length === 0) {
55899 return [];
55900 } else if (number >= length) {
55901 return number > 1 ? possibles : possibles[0];
55902 }
55903
55904 var result = [];
55905 var pick;
55906
55907 while (result.length < number) {
55908 if (typeof weights === 'undefined') {
55909 pick = possibles[Math.floor(rng() * length)];
55910 } else {
55911 var randKey = rng() * totalWeights;
55912
55913 for (var _i = 0, _len = possibles.length; _i < _len; _i++) {
55914 randKey -= weights[_i];
55915
55916 if (randKey < 0) {
55917 pick = possibles[_i];
55918 break;
55919 }
55920 }
55921 }
55922
55923 if (result.indexOf(pick) === -1) {
55924 result.push(pick);
55925 }
55926 }
55927
55928 return single ? result[0] : result; // TODO: return matrix when input was a matrix
55929 // TODO: add support for multi dimensional matrices
55930 }
55931});
55932// CONCATENATED MODULE: ./src/function/probability/util/randomMatrix.js
55933/**
55934 * This is a util function for generating a random matrix recursively.
55935 * @param {number[]} size
55936 * @param {function} random
55937 * @returns {Array}
55938 */
55939function randomMatrix(size, random) {
55940 var data = [];
55941 size = size.slice(0);
55942
55943 if (size.length > 1) {
55944 for (var i = 0, length = size.shift(); i < length; i++) {
55945 data.push(randomMatrix(size, random));
55946 }
55947 } else {
55948 for (var _i = 0, _length = size.shift(); _i < _length; _i++) {
55949 data.push(random());
55950 }
55951 }
55952
55953 return data;
55954}
55955// CONCATENATED MODULE: ./src/function/probability/random.js
55956
55957
55958
55959
55960var random_name = 'random';
55961var random_dependencies = ['typed', 'config', '?on'];
55962var createRandom =
55963/* #__PURE__ */
55964Object(factory["a" /* factory */])(random_name, random_dependencies, function (_ref) {
55965 var typed = _ref.typed,
55966 config = _ref.config,
55967 on = _ref.on;
55968 // seeded pseudo random number generator
55969 var rng = createRng(config.randomSeed);
55970
55971 if (on) {
55972 on('config', function (curr, prev) {
55973 if (curr.randomSeed !== prev.randomSeed) {
55974 rng = createRng(curr.randomSeed);
55975 }
55976 });
55977 }
55978 /**
55979 * Return a random number larger or equal to `min` and smaller than `max`
55980 * using a uniform distribution.
55981 *
55982 * Syntax:
55983 *
55984 * math.random() // generate a random number between 0 and 1
55985 * math.random(max) // generate a random number between 0 and max
55986 * math.random(min, max) // generate a random number between min and max
55987 * math.random(size) // generate a matrix with random numbers between 0 and 1
55988 * math.random(size, max) // generate a matrix with random numbers between 0 and max
55989 * math.random(size, min, max) // generate a matrix with random numbers between min and max
55990 *
55991 * Examples:
55992 *
55993 * math.random() // returns a random number between 0 and 1
55994 * math.random(100) // returns a random number between 0 and 100
55995 * math.random(30, 40) // returns a random number between 30 and 40
55996 * math.random([2, 3]) // returns a 2x3 matrix with random numbers between 0 and 1
55997 *
55998 * See also:
55999 *
56000 * randomInt, pickRandom
56001 *
56002 * @param {Array | Matrix} [size] If provided, an array or matrix with given
56003 * size and filled with random values is returned
56004 * @param {number} [min] Minimum boundary for the random value, included
56005 * @param {number} [max] Maximum boundary for the random value, excluded
56006 * @return {number | Array | Matrix} A random number
56007 */
56008
56009
56010 return typed(random_name, {
56011 '': function _() {
56012 return _random(0, 1);
56013 },
56014 number: function number(max) {
56015 return _random(0, max);
56016 },
56017 'number, number': function numberNumber(min, max) {
56018 return _random(min, max);
56019 },
56020 'Array | Matrix': function ArrayMatrix(size) {
56021 return _randomMatrix(size, 0, 1);
56022 },
56023 'Array | Matrix, number': function ArrayMatrixNumber(size, max) {
56024 return _randomMatrix(size, 0, max);
56025 },
56026 'Array | Matrix, number, number': function ArrayMatrixNumberNumber(size, min, max) {
56027 return _randomMatrix(size, min, max);
56028 }
56029 });
56030
56031 function _randomMatrix(size, min, max) {
56032 var res = randomMatrix(size.valueOf(), function () {
56033 return _random(min, max);
56034 });
56035 return Object(is["v" /* isMatrix */])(size) ? size.create(res) : res;
56036 }
56037
56038 function _random(min, max) {
56039 return min + rng() * (max - min);
56040 }
56041}); // number only implementation of random, no matrix support
56042// TODO: there is quite some duplicate code in both createRandom and createRandomNumber, can we improve that?
56043
56044var createRandomNumber =
56045/* #__PURE__ */
56046Object(factory["a" /* factory */])(random_name, ['typed', 'config', '?on'], function (_ref2) {
56047 var typed = _ref2.typed,
56048 config = _ref2.config,
56049 on = _ref2.on,
56050 matrix = _ref2.matrix;
56051 // seeded pseudo random number generator1
56052 var rng = createRng(config.randomSeed);
56053
56054 if (on) {
56055 on('config', function (curr, prev) {
56056 if (curr.randomSeed !== prev.randomSeed) {
56057 rng = createRng(curr.randomSeed);
56058 }
56059 });
56060 }
56061
56062 return typed(random_name, {
56063 '': function _() {
56064 return _random(0, 1);
56065 },
56066 number: function number(max) {
56067 return _random(0, max);
56068 },
56069 'number, number': function numberNumber(min, max) {
56070 return _random(min, max);
56071 }
56072 });
56073
56074 function _random(min, max) {
56075 return min + rng() * (max - min);
56076 }
56077});
56078// CONCATENATED MODULE: ./src/function/probability/randomInt.js
56079
56080
56081
56082
56083var randomInt_name = 'randomInt';
56084var randomInt_dependencies = ['typed', 'config', '?on'];
56085var createRandomInt =
56086/* #__PURE__ */
56087Object(factory["a" /* factory */])(randomInt_name, randomInt_dependencies, function (_ref) {
56088 var typed = _ref.typed,
56089 config = _ref.config,
56090 on = _ref.on;
56091 // seeded pseudo random number generator
56092 var rng = createRng(config.randomSeed);
56093
56094 if (on) {
56095 on('config', function (curr, prev) {
56096 if (curr.randomSeed !== prev.randomSeed) {
56097 rng = createRng(curr.randomSeed);
56098 }
56099 });
56100 }
56101 /**
56102 * Return a random integer number larger or equal to `min` and smaller than `max`
56103 * using a uniform distribution.
56104 *
56105 * Syntax:
56106 *
56107 * math.randomInt() // generate a random integer between 0 and 1
56108 * math.randomInt(max) // generate a random integer between 0 and max
56109 * math.randomInt(min, max) // generate a random integer between min and max
56110 * math.randomInt(size) // generate a matrix with random integer between 0 and 1
56111 * math.randomInt(size, max) // generate a matrix with random integer between 0 and max
56112 * math.randomInt(size, min, max) // generate a matrix with random integer between min and max
56113 *
56114 * Examples:
56115 *
56116 * math.randomInt(100) // returns a random integer between 0 and 100
56117 * math.randomInt(30, 40) // returns a random integer between 30 and 40
56118 * math.randomInt([2, 3]) // returns a 2x3 matrix with random integers between 0 and 1
56119 *
56120 * See also:
56121 *
56122 * random, pickRandom
56123 *
56124 * @param {Array | Matrix} [size] If provided, an array or matrix with given
56125 * size and filled with random values is returned
56126 * @param {number} [min] Minimum boundary for the random value, included
56127 * @param {number} [max] Maximum boundary for the random value, excluded
56128 * @return {number | Array | Matrix} A random integer value
56129 */
56130
56131
56132 return typed(randomInt_name, {
56133 '': function _() {
56134 return _randomInt(0, 1);
56135 },
56136 number: function number(max) {
56137 return _randomInt(0, max);
56138 },
56139 'number, number': function numberNumber(min, max) {
56140 return _randomInt(min, max);
56141 },
56142 'Array | Matrix': function ArrayMatrix(size) {
56143 return _randomIntMatrix(size, 0, 1);
56144 },
56145 'Array | Matrix, number': function ArrayMatrixNumber(size, max) {
56146 return _randomIntMatrix(size, 0, max);
56147 },
56148 'Array | Matrix, number, number': function ArrayMatrixNumberNumber(size, min, max) {
56149 return _randomIntMatrix(size, min, max);
56150 }
56151 });
56152
56153 function _randomIntMatrix(size, min, max) {
56154 var res = randomMatrix(size.valueOf(), function () {
56155 return _randomInt(min, max);
56156 });
56157 return Object(is["v" /* isMatrix */])(size) ? size.create(res) : res;
56158 }
56159
56160 function _randomInt(min, max) {
56161 return Math.floor(min + rng() * (max - min));
56162 }
56163});
56164// CONCATENATED MODULE: ./src/function/combinatorics/stirlingS2.js
56165
56166var stirlingS2_name = 'stirlingS2';
56167var stirlingS2_dependencies = ['typed', 'addScalar', 'subtract', 'multiplyScalar', 'divideScalar', 'pow', 'factorial', 'combinations', 'isNegative', 'isInteger', 'larger'];
56168var createStirlingS2 =
56169/* #__PURE__ */
56170Object(factory["a" /* factory */])(stirlingS2_name, stirlingS2_dependencies, function (_ref) {
56171 var typed = _ref.typed,
56172 addScalar = _ref.addScalar,
56173 subtract = _ref.subtract,
56174 multiplyScalar = _ref.multiplyScalar,
56175 divideScalar = _ref.divideScalar,
56176 pow = _ref.pow,
56177 factorial = _ref.factorial,
56178 combinations = _ref.combinations,
56179 isNegative = _ref.isNegative,
56180 isInteger = _ref.isInteger,
56181 larger = _ref.larger;
56182
56183 /**
56184 * The Stirling numbers of the second kind, counts the number of ways to partition
56185 * a set of n labelled objects into k nonempty unlabelled subsets.
56186 * stirlingS2 only takes integer arguments.
56187 * The following condition must be enforced: k <= n.
56188 *
56189 * If n = k or k = 1, then s(n,k) = 1
56190 *
56191 * Syntax:
56192 *
56193 * math.stirlingS2(n, k)
56194 *
56195 * Examples:
56196 *
56197 * math.stirlingS2(5, 3) //returns 25
56198 *
56199 * See also:
56200 *
56201 * bellNumbers
56202 *
56203 * @param {Number | BigNumber} n Total number of objects in the set
56204 * @param {Number | BigNumber} k Number of objects in the subset
56205 * @return {Number | BigNumber} S(n,k)
56206 */
56207 return typed(stirlingS2_name, {
56208 'number | BigNumber, number | BigNumber': function numberBigNumberNumberBigNumber(n, k) {
56209 if (!isInteger(n) || isNegative(n) || !isInteger(k) || isNegative(k)) {
56210 throw new TypeError('Non-negative integer value expected in function stirlingS2');
56211 } else if (larger(k, n)) {
56212 throw new TypeError('k must be less than or equal to n in function stirlingS2');
56213 } // 1/k! Sum(i=0 -> k) [(-1)^(k-i)*C(k,j)* i^n]
56214
56215
56216 var kFactorial = factorial(k);
56217 var result = 0;
56218
56219 for (var i = 0; i <= k; i++) {
56220 var negativeOne = pow(-1, subtract(k, i));
56221 var kChooseI = combinations(k, i);
56222 var iPower = pow(i, n);
56223 result = addScalar(result, multiplyScalar(multiplyScalar(kChooseI, iPower), negativeOne));
56224 }
56225
56226 return divideScalar(result, kFactorial);
56227 }
56228 });
56229});
56230// CONCATENATED MODULE: ./src/function/combinatorics/bellNumbers.js
56231
56232var bellNumbers_name = 'bellNumbers';
56233var bellNumbers_dependencies = ['typed', 'addScalar', 'isNegative', 'isInteger', 'stirlingS2'];
56234var createBellNumbers =
56235/* #__PURE__ */
56236Object(factory["a" /* factory */])(bellNumbers_name, bellNumbers_dependencies, function (_ref) {
56237 var typed = _ref.typed,
56238 addScalar = _ref.addScalar,
56239 isNegative = _ref.isNegative,
56240 isInteger = _ref.isInteger,
56241 stirlingS2 = _ref.stirlingS2;
56242
56243 /**
56244 * The Bell Numbers count the number of partitions of a set. A partition is a pairwise disjoint subset of S whose union is S.
56245 * bellNumbers only takes integer arguments.
56246 * The following condition must be enforced: n >= 0
56247 *
56248 * Syntax:
56249 *
56250 * math.bellNumbers(n)
56251 *
56252 * Examples:
56253 *
56254 * math.bellNumbers(3) // returns 5
56255 * math.bellNumbers(8) // returns 4140
56256 *
56257 * See also:
56258 *
56259 * stirlingS2
56260 *
56261 * @param {Number | BigNumber} n Total number of objects in the set
56262 * @return {Number | BigNumber} B(n)
56263 */
56264 return typed(bellNumbers_name, {
56265 'number | BigNumber': function numberBigNumber(n) {
56266 if (!isInteger(n) || isNegative(n)) {
56267 throw new TypeError('Non-negative integer value expected in function bellNumbers');
56268 } // Sum (k=0, n) S(n,k).
56269
56270
56271 var result = 0;
56272
56273 for (var i = 0; i <= n; i++) {
56274 result = addScalar(result, stirlingS2(n, i));
56275 }
56276
56277 return result;
56278 }
56279 });
56280});
56281// CONCATENATED MODULE: ./src/function/combinatorics/catalan.js
56282
56283var catalan_name = 'catalan';
56284var catalan_dependencies = ['typed', 'addScalar', 'divideScalar', 'multiplyScalar', 'combinations', 'isNegative', 'isInteger'];
56285var createCatalan =
56286/* #__PURE__ */
56287Object(factory["a" /* factory */])(catalan_name, catalan_dependencies, function (_ref) {
56288 var typed = _ref.typed,
56289 addScalar = _ref.addScalar,
56290 divideScalar = _ref.divideScalar,
56291 multiplyScalar = _ref.multiplyScalar,
56292 combinations = _ref.combinations,
56293 isNegative = _ref.isNegative,
56294 isInteger = _ref.isInteger;
56295
56296 /**
56297 * The Catalan Numbers enumerate combinatorial structures of many different types.
56298 * catalan only takes integer arguments.
56299 * The following condition must be enforced: n >= 0
56300 *
56301 * Syntax:
56302 *
56303 * math.catalan(n)
56304 *
56305 * Examples:
56306 *
56307 * math.catalan(3) // returns 5
56308 * math.catalan(8) // returns 1430
56309 *
56310 * See also:
56311 *
56312 * bellNumbers
56313 *
56314 * @param {Number | BigNumber} n nth Catalan number
56315 * @return {Number | BigNumber} Cn(n)
56316 */
56317 return typed(catalan_name, {
56318 'number | BigNumber': function numberBigNumber(n) {
56319 if (!isInteger(n) || isNegative(n)) {
56320 throw new TypeError('Non-negative integer value expected in function catalan');
56321 }
56322
56323 return divideScalar(combinations(multiplyScalar(n, 2), n), addScalar(n, 1));
56324 }
56325 });
56326});
56327// CONCATENATED MODULE: ./src/function/combinatorics/composition.js
56328
56329var composition_name = 'composition';
56330var composition_dependencies = ['typed', 'addScalar', 'combinations', 'isNegative', 'isPositive', 'isInteger', 'larger'];
56331var createComposition =
56332/* #__PURE__ */
56333Object(factory["a" /* factory */])(composition_name, composition_dependencies, function (_ref) {
56334 var typed = _ref.typed,
56335 addScalar = _ref.addScalar,
56336 combinations = _ref.combinations,
56337 isPositive = _ref.isPositive,
56338 isNegative = _ref.isNegative,
56339 isInteger = _ref.isInteger,
56340 larger = _ref.larger;
56341
56342 /**
56343 * The composition counts of n into k parts.
56344 *
56345 * composition only takes integer arguments.
56346 * The following condition must be enforced: k <= n.
56347 *
56348 * Syntax:
56349 *
56350 * math.composition(n, k)
56351 *
56352 * Examples:
56353 *
56354 * math.composition(5, 3) // returns 6
56355 *
56356 * See also:
56357 *
56358 * combinations
56359 *
56360 * @param {Number | BigNumber} n Total number of objects in the set
56361 * @param {Number | BigNumber} k Number of objects in the subset
56362 * @return {Number | BigNumber} Returns the composition counts of n into k parts.
56363 */
56364 return typed(composition_name, {
56365 'number | BigNumber, number | BigNumber': function numberBigNumberNumberBigNumber(n, k) {
56366 if (!isInteger(n) || !isPositive(n) || !isInteger(k) || !isPositive(k)) {
56367 throw new TypeError('Positive integer value expected in function composition');
56368 } else if (larger(k, n)) {
56369 throw new TypeError('k must be less than or equal to n in function composition');
56370 }
56371
56372 return combinations(addScalar(n, -1), addScalar(k, -1));
56373 }
56374 });
56375});
56376// CONCATENATED MODULE: ./src/function/algebra/simplify/util.js
56377
56378
56379
56380var util_name = 'simplifyUtil';
56381var util_dependencies = ['FunctionNode', 'OperatorNode', 'SymbolNode'];
56382var createUtil =
56383/* #__PURE__ */
56384Object(factory["a" /* factory */])(util_name, util_dependencies, function (_ref) {
56385 var FunctionNode = _ref.FunctionNode,
56386 OperatorNode = _ref.OperatorNode,
56387 SymbolNode = _ref.SymbolNode;
56388 // TODO commutative/associative properties rely on the arguments
56389 // e.g. multiply is not commutative for matrices
56390 // The properties should be calculated from an argument to simplify, or possibly something in math.config
56391 // the other option is for typed() to specify a return type so that we can evaluate the type of arguments
56392 var commutative = {
56393 add: true,
56394 multiply: true
56395 };
56396 var associative = {
56397 add: true,
56398 multiply: true
56399 };
56400
56401 function isCommutative(node, context) {
56402 if (!Object(is["B" /* isOperatorNode */])(node)) {
56403 return true;
56404 }
56405
56406 var name = node.fn.toString();
56407
56408 if (context && Object(utils_object["f" /* hasOwnProperty */])(context, name) && Object(utils_object["f" /* hasOwnProperty */])(context[name], 'commutative')) {
56409 return context[name].commutative;
56410 }
56411
56412 return commutative[name] || false;
56413 }
56414
56415 function isAssociative(node, context) {
56416 if (!Object(is["B" /* isOperatorNode */])(node)) {
56417 return false;
56418 }
56419
56420 var name = node.fn.toString();
56421
56422 if (context && Object(utils_object["f" /* hasOwnProperty */])(context, name) && Object(utils_object["f" /* hasOwnProperty */])(context[name], 'associative')) {
56423 return context[name].associative;
56424 }
56425
56426 return associative[name] || false;
56427 }
56428 /**
56429 * Flatten all associative operators in an expression tree.
56430 * Assumes parentheses have already been removed.
56431 */
56432
56433
56434 function flatten(node) {
56435 if (!node.args || node.args.length === 0) {
56436 return node;
56437 }
56438
56439 node.args = allChildren(node);
56440
56441 for (var i = 0; i < node.args.length; i++) {
56442 flatten(node.args[i]);
56443 }
56444 }
56445 /**
56446 * Get the children of a node as if it has been flattened.
56447 * TODO implement for FunctionNodes
56448 */
56449
56450
56451 function allChildren(node) {
56452 var op;
56453 var children = [];
56454
56455 var findChildren = function findChildren(node) {
56456 for (var i = 0; i < node.args.length; i++) {
56457 var child = node.args[i];
56458
56459 if (Object(is["B" /* isOperatorNode */])(child) && op === child.op) {
56460 findChildren(child);
56461 } else {
56462 children.push(child);
56463 }
56464 }
56465 };
56466
56467 if (isAssociative(node)) {
56468 op = node.op;
56469 findChildren(node);
56470 return children;
56471 } else {
56472 return node.args;
56473 }
56474 }
56475 /**
56476 * Unflatten all flattened operators to a right-heavy binary tree.
56477 */
56478
56479
56480 function unflattenr(node) {
56481 if (!node.args || node.args.length === 0) {
56482 return;
56483 }
56484
56485 var makeNode = createMakeNodeFunction(node);
56486 var l = node.args.length;
56487
56488 for (var i = 0; i < l; i++) {
56489 unflattenr(node.args[i]);
56490 }
56491
56492 if (l > 2 && isAssociative(node)) {
56493 var curnode = node.args.pop();
56494
56495 while (node.args.length > 0) {
56496 curnode = makeNode([node.args.pop(), curnode]);
56497 }
56498
56499 node.args = curnode.args;
56500 }
56501 }
56502 /**
56503 * Unflatten all flattened operators to a left-heavy binary tree.
56504 */
56505
56506
56507 function unflattenl(node) {
56508 if (!node.args || node.args.length === 0) {
56509 return;
56510 }
56511
56512 var makeNode = createMakeNodeFunction(node);
56513 var l = node.args.length;
56514
56515 for (var i = 0; i < l; i++) {
56516 unflattenl(node.args[i]);
56517 }
56518
56519 if (l > 2 && isAssociative(node)) {
56520 var curnode = node.args.shift();
56521
56522 while (node.args.length > 0) {
56523 curnode = makeNode([curnode, node.args.shift()]);
56524 }
56525
56526 node.args = curnode.args;
56527 }
56528 }
56529
56530 function createMakeNodeFunction(node) {
56531 if (Object(is["B" /* isOperatorNode */])(node)) {
56532 return function (args) {
56533 try {
56534 return new OperatorNode(node.op, node.fn, args, node.implicit);
56535 } catch (err) {
56536 console.error(err);
56537 return [];
56538 }
56539 };
56540 } else {
56541 return function (args) {
56542 return new FunctionNode(new SymbolNode(node.name), args);
56543 };
56544 }
56545 }
56546
56547 return {
56548 createMakeNodeFunction: createMakeNodeFunction,
56549 isCommutative: isCommutative,
56550 isAssociative: isAssociative,
56551 flatten: flatten,
56552 allChildren: allChildren,
56553 unflattenr: unflattenr,
56554 unflattenl: unflattenl
56555 };
56556});
56557// CONCATENATED MODULE: ./src/function/algebra/simplify/simplifyCore.js
56558
56559
56560var simplifyCore_name = 'simplifyCore';
56561var simplifyCore_dependencies = ['equal', 'isZero', 'add', 'subtract', 'multiply', 'divide', 'pow', 'ConstantNode', 'OperatorNode', 'FunctionNode', 'ParenthesisNode'];
56562var createSimplifyCore =
56563/* #__PURE__ */
56564Object(factory["a" /* factory */])(simplifyCore_name, simplifyCore_dependencies, function (_ref) {
56565 var equal = _ref.equal,
56566 isZero = _ref.isZero,
56567 add = _ref.add,
56568 subtract = _ref.subtract,
56569 multiply = _ref.multiply,
56570 divide = _ref.divide,
56571 pow = _ref.pow,
56572 ConstantNode = _ref.ConstantNode,
56573 OperatorNode = _ref.OperatorNode,
56574 FunctionNode = _ref.FunctionNode,
56575 ParenthesisNode = _ref.ParenthesisNode;
56576 var node0 = new ConstantNode(0);
56577 var node1 = new ConstantNode(1);
56578 /**
56579 * simplifyCore() performs single pass simplification suitable for
56580 * applications requiring ultimate performance. In contrast, simplify()
56581 * extends simplifyCore() with additional passes to provide deeper
56582 * simplification.
56583 *
56584 * Syntax:
56585 *
56586 * simplify.simplifyCore(expr)
56587 *
56588 * Examples:
56589 *
56590 * const f = math.parse('2 * 1 * x ^ (2 - 1)')
56591 * math.simplify.simpifyCore(f) // Node {2 * x}
56592 * math.simplify('2 * 1 * x ^ (2 - 1)', [math.simplify.simpifyCore]) // Node {2 * x}
56593 *
56594 * See also:
56595 *
56596 * derivative
56597 *
56598 * @param {Node} node
56599 * The expression to be simplified
56600 */
56601
56602 function simplifyCore(node) {
56603 if (Object(is["B" /* isOperatorNode */])(node) && node.isUnary()) {
56604 var a0 = simplifyCore(node.args[0]);
56605
56606 if (node.op === '+') {
56607 // unary plus
56608 return a0;
56609 }
56610
56611 if (node.op === '-') {
56612 // unary minus
56613 if (Object(is["B" /* isOperatorNode */])(a0)) {
56614 if (a0.isUnary() && a0.op === '-') {
56615 return a0.args[0];
56616 } else if (a0.isBinary() && a0.fn === 'subtract') {
56617 return new OperatorNode('-', 'subtract', [a0.args[1], a0.args[0]]);
56618 }
56619 }
56620
56621 return new OperatorNode(node.op, node.fn, [a0]);
56622 }
56623 } else if (Object(is["B" /* isOperatorNode */])(node) && node.isBinary()) {
56624 var _a = simplifyCore(node.args[0]);
56625
56626 var a1 = simplifyCore(node.args[1]);
56627
56628 if (node.op === '+') {
56629 if (Object(is["l" /* isConstantNode */])(_a)) {
56630 if (isZero(_a.value)) {
56631 return a1;
56632 } else if (Object(is["l" /* isConstantNode */])(a1)) {
56633 return new ConstantNode(add(_a.value, a1.value));
56634 }
56635 }
56636
56637 if (Object(is["l" /* isConstantNode */])(a1) && isZero(a1.value)) {
56638 return _a;
56639 }
56640
56641 if (Object(is["B" /* isOperatorNode */])(a1) && a1.isUnary() && a1.op === '-') {
56642 return new OperatorNode('-', 'subtract', [_a, a1.args[0]]);
56643 }
56644
56645 return new OperatorNode(node.op, node.fn, a1 ? [_a, a1] : [_a]);
56646 } else if (node.op === '-') {
56647 if (Object(is["l" /* isConstantNode */])(_a) && a1) {
56648 if (Object(is["l" /* isConstantNode */])(a1)) {
56649 return new ConstantNode(subtract(_a.value, a1.value));
56650 } else if (isZero(_a.value)) {
56651 return new OperatorNode('-', 'unaryMinus', [a1]);
56652 }
56653 } // if (node.fn === "subtract" && node.args.length === 2) {
56654
56655
56656 if (node.fn === 'subtract') {
56657 if (Object(is["l" /* isConstantNode */])(a1) && isZero(a1.value)) {
56658 return _a;
56659 }
56660
56661 if (Object(is["B" /* isOperatorNode */])(a1) && a1.isUnary() && a1.op === '-') {
56662 return simplifyCore(new OperatorNode('+', 'add', [_a, a1.args[0]]));
56663 }
56664
56665 return new OperatorNode(node.op, node.fn, [_a, a1]);
56666 }
56667 } else if (node.op === '*') {
56668 if (Object(is["l" /* isConstantNode */])(_a)) {
56669 if (isZero(_a.value)) {
56670 return node0;
56671 } else if (equal(_a.value, 1)) {
56672 return a1;
56673 } else if (Object(is["l" /* isConstantNode */])(a1)) {
56674 return new ConstantNode(multiply(_a.value, a1.value));
56675 }
56676 }
56677
56678 if (Object(is["l" /* isConstantNode */])(a1)) {
56679 if (isZero(a1.value)) {
56680 return node0;
56681 } else if (equal(a1.value, 1)) {
56682 return _a;
56683 } else if (Object(is["B" /* isOperatorNode */])(_a) && _a.isBinary() && _a.op === node.op) {
56684 var a00 = _a.args[0];
56685
56686 if (Object(is["l" /* isConstantNode */])(a00)) {
56687 var a00a1 = new ConstantNode(multiply(a00.value, a1.value));
56688 return new OperatorNode(node.op, node.fn, [a00a1, _a.args[1]], node.implicit); // constants on left
56689 }
56690 }
56691
56692 return new OperatorNode(node.op, node.fn, [a1, _a], node.implicit); // constants on left
56693 }
56694
56695 return new OperatorNode(node.op, node.fn, [_a, a1], node.implicit);
56696 } else if (node.op === '/') {
56697 if (Object(is["l" /* isConstantNode */])(_a)) {
56698 if (isZero(_a.value)) {
56699 return node0;
56700 } else if (Object(is["l" /* isConstantNode */])(a1) && (equal(a1.value, 1) || equal(a1.value, 2) || equal(a1.value, 4))) {
56701 return new ConstantNode(divide(_a.value, a1.value));
56702 }
56703 }
56704
56705 return new OperatorNode(node.op, node.fn, [_a, a1]);
56706 } else if (node.op === '^') {
56707 if (Object(is["l" /* isConstantNode */])(a1)) {
56708 if (isZero(a1.value)) {
56709 return node1;
56710 } else if (equal(a1.value, 1)) {
56711 return _a;
56712 } else {
56713 if (Object(is["l" /* isConstantNode */])(_a)) {
56714 // fold constant
56715 return new ConstantNode(pow(_a.value, a1.value));
56716 } else if (Object(is["B" /* isOperatorNode */])(_a) && _a.isBinary() && _a.op === '^') {
56717 var a01 = _a.args[1];
56718
56719 if (Object(is["l" /* isConstantNode */])(a01)) {
56720 return new OperatorNode(node.op, node.fn, [_a.args[0], new ConstantNode(multiply(a01.value, a1.value))]);
56721 }
56722 }
56723 }
56724 }
56725
56726 return new OperatorNode(node.op, node.fn, [_a, a1]);
56727 }
56728 } else if (Object(is["C" /* isParenthesisNode */])(node)) {
56729 var c = simplifyCore(node.content);
56730
56731 if (Object(is["C" /* isParenthesisNode */])(c) || Object(is["J" /* isSymbolNode */])(c) || Object(is["l" /* isConstantNode */])(c)) {
56732 return c;
56733 }
56734
56735 return new ParenthesisNode(c);
56736 } else if (Object(is["r" /* isFunctionNode */])(node)) {
56737 var args = node.args.map(simplifyCore).map(function (arg) {
56738 return Object(is["C" /* isParenthesisNode */])(arg) ? arg.content : arg;
56739 });
56740 return new FunctionNode(simplifyCore(node.fn), args);
56741 } else {// cannot simplify
56742 }
56743
56744 return node;
56745 }
56746
56747 return simplifyCore;
56748});
56749// CONCATENATED MODULE: ./src/function/algebra/simplify/simplifyConstant.js
56750// TODO this could be improved by simplifying seperated constants under associative and commutative operators
56751
56752
56753
56754
56755var simplifyConstant_name = 'simplifyConstant';
56756var simplifyConstant_dependencies = ['typed', 'config', 'mathWithTransform', '?fraction', '?bignumber', 'ConstantNode', 'OperatorNode', 'FunctionNode', 'SymbolNode'];
56757var createSimplifyConstant =
56758/* #__PURE__ */
56759Object(factory["a" /* factory */])(simplifyConstant_name, simplifyConstant_dependencies, function (_ref) {
56760 var typed = _ref.typed,
56761 config = _ref.config,
56762 mathWithTransform = _ref.mathWithTransform,
56763 fraction = _ref.fraction,
56764 bignumber = _ref.bignumber,
56765 ConstantNode = _ref.ConstantNode,
56766 OperatorNode = _ref.OperatorNode,
56767 FunctionNode = _ref.FunctionNode,
56768 SymbolNode = _ref.SymbolNode;
56769
56770 var _createUtil = createUtil({
56771 FunctionNode: FunctionNode,
56772 OperatorNode: OperatorNode,
56773 SymbolNode: SymbolNode
56774 }),
56775 isCommutative = _createUtil.isCommutative,
56776 isAssociative = _createUtil.isAssociative,
56777 allChildren = _createUtil.allChildren,
56778 createMakeNodeFunction = _createUtil.createMakeNodeFunction;
56779
56780 function simplifyConstant(expr, options) {
56781 var res = foldFraction(expr, options);
56782 return Object(is["w" /* isNode */])(res) ? res : _toNode(res);
56783 }
56784
56785 function _eval(fnname, args, options) {
56786 try {
56787 return _toNumber(mathWithTransform[fnname].apply(null, args), options);
56788 } catch (ignore) {
56789 // sometimes the implicit type conversion causes the evaluation to fail, so we'll try again after removing Fractions
56790 args = args.map(function (x) {
56791 if (Object(is["o" /* isFraction */])(x)) {
56792 return x.valueOf();
56793 }
56794
56795 return x;
56796 });
56797 return _toNumber(mathWithTransform[fnname].apply(null, args), options);
56798 }
56799 }
56800
56801 var _toNode = typed({
56802 Fraction: _fractionToNode,
56803 number: function number(n) {
56804 if (n < 0) {
56805 return unaryMinusNode(new ConstantNode(-n));
56806 }
56807
56808 return new ConstantNode(n);
56809 },
56810 BigNumber: function BigNumber(n) {
56811 if (n < 0) {
56812 return unaryMinusNode(new ConstantNode(-n));
56813 }
56814
56815 return new ConstantNode(n); // old parameters: (n.toString(), 'number')
56816 },
56817 Complex: function Complex(s) {
56818 throw new Error('Cannot convert Complex number to Node');
56819 }
56820 }); // convert a number to a fraction only if it can be expressed exactly
56821
56822
56823 function _exactFraction(n, options) {
56824 var exactFractions = options && options.exactFractions !== false;
56825
56826 if (exactFractions && isFinite(n) && fraction) {
56827 var f = fraction(n);
56828
56829 if (f.valueOf() === n) {
56830 return f;
56831 }
56832 }
56833
56834 return n;
56835 } // Convert numbers to a preferred number type in preference order: Fraction, number, Complex
56836 // BigNumbers are left alone
56837
56838
56839 var _toNumber = typed({
56840 'string, Object': function stringObject(s, options) {
56841 if (config.number === 'BigNumber') {
56842 if (bignumber === undefined) {
56843 noBignumber();
56844 }
56845
56846 return bignumber(s);
56847 } else if (config.number === 'Fraction') {
56848 if (fraction === undefined) {
56849 noFraction();
56850 }
56851
56852 return fraction(s);
56853 } else {
56854 var n = parseFloat(s);
56855 return _exactFraction(n, options);
56856 }
56857 },
56858 'Fraction, Object': function FractionObject(s, options) {
56859 return s;
56860 },
56861 // we don't need options here
56862 'BigNumber, Object': function BigNumberObject(s, options) {
56863 return s;
56864 },
56865 // we don't need options here
56866 'number, Object': function numberObject(s, options) {
56867 return _exactFraction(s, options);
56868 },
56869 'Complex, Object': function ComplexObject(s, options) {
56870 if (s.im !== 0) {
56871 return s;
56872 }
56873
56874 return _exactFraction(s.re, options);
56875 }
56876 });
56877
56878 function unaryMinusNode(n) {
56879 return new OperatorNode('-', 'unaryMinus', [n]);
56880 }
56881
56882 function _fractionToNode(f) {
56883 var n;
56884 var vn = f.s * f.n;
56885
56886 if (vn < 0) {
56887 n = new OperatorNode('-', 'unaryMinus', [new ConstantNode(-vn)]);
56888 } else {
56889 n = new ConstantNode(vn);
56890 }
56891
56892 if (f.d === 1) {
56893 return n;
56894 }
56895
56896 return new OperatorNode('/', 'divide', [n, new ConstantNode(f.d)]);
56897 }
56898 /*
56899 * Create a binary tree from a list of Fractions and Nodes.
56900 * Tries to fold Fractions by evaluating them until the first Node in the list is hit, so
56901 * `args` should be sorted to have the Fractions at the start (if the operator is commutative).
56902 * @param args - list of Fractions and Nodes
56903 * @param fn - evaluator for the binary operation evaluator that accepts two Fractions
56904 * @param makeNode - creates a binary OperatorNode/FunctionNode from a list of child Nodes
56905 * if args.length is 1, returns args[0]
56906 * @return - Either a Node representing a binary expression or Fraction
56907 */
56908
56909
56910 function foldOp(fn, args, makeNode, options) {
56911 return args.reduce(function (a, b) {
56912 if (!Object(is["w" /* isNode */])(a) && !Object(is["w" /* isNode */])(b)) {
56913 try {
56914 return _eval(fn, [a, b], options);
56915 } catch (ignoreandcontinue) {}
56916
56917 a = _toNode(a);
56918 b = _toNode(b);
56919 } else if (!Object(is["w" /* isNode */])(a)) {
56920 a = _toNode(a);
56921 } else if (!Object(is["w" /* isNode */])(b)) {
56922 b = _toNode(b);
56923 }
56924
56925 return makeNode([a, b]);
56926 });
56927 } // destroys the original node and returns a folded one
56928
56929
56930 function foldFraction(node, options) {
56931 switch (node.type) {
56932 case 'SymbolNode':
56933 return node;
56934
56935 case 'ConstantNode':
56936 if (typeof node.value === 'number' || !isNaN(node.value)) {
56937 return _toNumber(node.value, options);
56938 }
56939
56940 return node;
56941
56942 case 'FunctionNode':
56943 if (mathWithTransform[node.name] && mathWithTransform[node.name].rawArgs) {
56944 return node;
56945 }
56946
56947 {
56948 // Process operators as OperatorNode
56949 var operatorFunctions = ['add', 'multiply'];
56950
56951 if (operatorFunctions.indexOf(node.name) === -1) {
56952 var args = node.args.map(function (arg) {
56953 return foldFraction(arg, options);
56954 }); // If all args are numbers
56955
56956 if (!args.some(is["w" /* isNode */])) {
56957 try {
56958 return _eval(node.name, args, options);
56959 } catch (ignoreandcontine) {}
56960 } // Convert all args to nodes and construct a symbolic function call
56961
56962
56963 args = args.map(function (arg) {
56964 return Object(is["w" /* isNode */])(arg) ? arg : _toNode(arg);
56965 });
56966 return new FunctionNode(node.name, args);
56967 } else {// treat as operator
56968 }
56969 }
56970
56971 /* falls through */
56972
56973 case 'OperatorNode':
56974 {
56975 var fn = node.fn.toString();
56976
56977 var _args;
56978
56979 var res;
56980 var makeNode = createMakeNodeFunction(node);
56981
56982 if (Object(is["B" /* isOperatorNode */])(node) && node.isUnary()) {
56983 _args = [foldFraction(node.args[0], options)];
56984
56985 if (!Object(is["w" /* isNode */])(_args[0])) {
56986 res = _eval(fn, _args, options);
56987 } else {
56988 res = makeNode(_args);
56989 }
56990 } else if (isAssociative(node)) {
56991 _args = allChildren(node);
56992 _args = _args.map(function (arg) {
56993 return foldFraction(arg, options);
56994 });
56995
56996 if (isCommutative(fn)) {
56997 // commutative binary operator
56998 var consts = [];
56999 var vars = [];
57000
57001 for (var i = 0; i < _args.length; i++) {
57002 if (!Object(is["w" /* isNode */])(_args[i])) {
57003 consts.push(_args[i]);
57004 } else {
57005 vars.push(_args[i]);
57006 }
57007 }
57008
57009 if (consts.length > 1) {
57010 res = foldOp(fn, consts, makeNode, options);
57011 vars.unshift(res);
57012 res = foldOp(fn, vars, makeNode, options);
57013 } else {
57014 // we won't change the children order since it's not neccessary
57015 res = foldOp(fn, _args, makeNode, options);
57016 }
57017 } else {
57018 // non-commutative binary operator
57019 res = foldOp(fn, _args, makeNode, options);
57020 }
57021 } else {
57022 // non-associative binary operator
57023 _args = node.args.map(function (arg) {
57024 return foldFraction(arg, options);
57025 });
57026 res = foldOp(fn, _args, makeNode, options);
57027 }
57028
57029 return res;
57030 }
57031
57032 case 'ParenthesisNode':
57033 // remove the uneccessary parenthesis
57034 return foldFraction(node.content, options);
57035
57036 case 'AccessorNode':
57037 /* falls through */
57038
57039 case 'ArrayNode':
57040 /* falls through */
57041
57042 case 'AssignmentNode':
57043 /* falls through */
57044
57045 case 'BlockNode':
57046 /* falls through */
57047
57048 case 'FunctionAssignmentNode':
57049 /* falls through */
57050
57051 case 'IndexNode':
57052 /* falls through */
57053
57054 case 'ObjectNode':
57055 /* falls through */
57056
57057 case 'RangeNode':
57058 /* falls through */
57059
57060 case 'ConditionalNode':
57061 /* falls through */
57062
57063 default:
57064 throw new Error("Unimplemented node type in simplifyConstant: ".concat(node.type));
57065 }
57066 }
57067
57068 return simplifyConstant;
57069});
57070// CONCATENATED MODULE: ./src/function/algebra/simplify/resolve.js
57071
57072
57073var resolve_name = 'resolve';
57074var resolve_dependencies = ['parse', 'FunctionNode', 'OperatorNode', 'ParenthesisNode'];
57075var createResolve =
57076/* #__PURE__ */
57077Object(factory["a" /* factory */])(resolve_name, resolve_dependencies, function (_ref) {
57078 var parse = _ref.parse,
57079 FunctionNode = _ref.FunctionNode,
57080 OperatorNode = _ref.OperatorNode,
57081 ParenthesisNode = _ref.ParenthesisNode;
57082
57083 /**
57084 * resolve(expr, scope) replaces variable nodes with their scoped values
57085 *
57086 * Syntax:
57087 *
57088 * simplify.resolve(expr, scope)
57089 *
57090 * Examples:
57091 *
57092 * math.simplify.resolve('x + y', {x:1, y:2}) // Node {1 + 2}
57093 * math.simplify.resolve(math.parse('x+y'), {x:1, y:2}) // Node {1 + 2}
57094 * math.simplify('x+y', {x:2, y:'x+x'}).toString() // "6"
57095 *
57096 * @param {Node} node
57097 * The expression tree to be simplified
57098 * @param {Object} scope with variables to be resolved
57099 */
57100 function resolve(node, scope) {
57101 if (!scope) {
57102 return node;
57103 }
57104
57105 if (Object(is["J" /* isSymbolNode */])(node)) {
57106 var value = scope[node.name];
57107
57108 if (Object(is["w" /* isNode */])(value)) {
57109 return resolve(value, scope);
57110 } else if (typeof value === 'number') {
57111 return parse(String(value));
57112 }
57113 } else if (Object(is["B" /* isOperatorNode */])(node)) {
57114 var args = node.args.map(function (arg) {
57115 return resolve(arg, scope);
57116 });
57117 return new OperatorNode(node.op, node.fn, args, node.implicit);
57118 } else if (Object(is["C" /* isParenthesisNode */])(node)) {
57119 return new ParenthesisNode(resolve(node.content, scope));
57120 } else if (Object(is["r" /* isFunctionNode */])(node)) {
57121 var _args = node.args.map(function (arg) {
57122 return resolve(arg, scope);
57123 });
57124
57125 return new FunctionNode(node.name, _args);
57126 }
57127
57128 return node;
57129 }
57130
57131 return resolve;
57132});
57133// CONCATENATED MODULE: ./src/function/algebra/simplify.js
57134function simplify_typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { simplify_typeof = function _typeof(obj) { return typeof obj; }; } else { simplify_typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return simplify_typeof(obj); }
57135
57136
57137
57138
57139
57140
57141
57142
57143var simplify_name = 'simplify';
57144var simplify_dependencies = ['config', 'typed', 'parse', 'add', 'subtract', 'multiply', 'divide', 'pow', 'isZero', 'equal', '?fraction', '?bignumber', 'mathWithTransform', 'ConstantNode', 'FunctionNode', 'OperatorNode', 'ParenthesisNode', 'SymbolNode'];
57145var createSimplify =
57146/* #__PURE__ */
57147Object(factory["a" /* factory */])(simplify_name, simplify_dependencies, function (_ref) {
57148 var config = _ref.config,
57149 typed = _ref.typed,
57150 parse = _ref.parse,
57151 add = _ref.add,
57152 subtract = _ref.subtract,
57153 multiply = _ref.multiply,
57154 divide = _ref.divide,
57155 pow = _ref.pow,
57156 isZero = _ref.isZero,
57157 equal = _ref.equal,
57158 fraction = _ref.fraction,
57159 bignumber = _ref.bignumber,
57160 mathWithTransform = _ref.mathWithTransform,
57161 ConstantNode = _ref.ConstantNode,
57162 FunctionNode = _ref.FunctionNode,
57163 OperatorNode = _ref.OperatorNode,
57164 ParenthesisNode = _ref.ParenthesisNode,
57165 SymbolNode = _ref.SymbolNode;
57166 var simplifyConstant = createSimplifyConstant({
57167 typed: typed,
57168 config: config,
57169 mathWithTransform: mathWithTransform,
57170 fraction: fraction,
57171 bignumber: bignumber,
57172 ConstantNode: ConstantNode,
57173 OperatorNode: OperatorNode,
57174 FunctionNode: FunctionNode,
57175 SymbolNode: SymbolNode
57176 });
57177 var simplifyCore = createSimplifyCore({
57178 equal: equal,
57179 isZero: isZero,
57180 add: add,
57181 subtract: subtract,
57182 multiply: multiply,
57183 divide: divide,
57184 pow: pow,
57185 ConstantNode: ConstantNode,
57186 OperatorNode: OperatorNode,
57187 FunctionNode: FunctionNode,
57188 ParenthesisNode: ParenthesisNode
57189 });
57190 var resolve = createResolve({
57191 parse: parse,
57192 FunctionNode: FunctionNode,
57193 OperatorNode: OperatorNode,
57194 ParenthesisNode: ParenthesisNode
57195 });
57196
57197 var _createUtil = createUtil({
57198 FunctionNode: FunctionNode,
57199 OperatorNode: OperatorNode,
57200 SymbolNode: SymbolNode
57201 }),
57202 isCommutative = _createUtil.isCommutative,
57203 isAssociative = _createUtil.isAssociative,
57204 flatten = _createUtil.flatten,
57205 unflattenr = _createUtil.unflattenr,
57206 unflattenl = _createUtil.unflattenl,
57207 createMakeNodeFunction = _createUtil.createMakeNodeFunction;
57208 /**
57209 * Simplify an expression tree.
57210 *
57211 * A list of rules are applied to an expression, repeating over the list until
57212 * no further changes are made.
57213 * It's possible to pass a custom set of rules to the function as second
57214 * argument. A rule can be specified as an object, string, or function:
57215 *
57216 * const rules = [
57217 * { l: 'n1*n3 + n2*n3', r: '(n1+n2)*n3' },
57218 * 'n1*n3 + n2*n3 -> (n1+n2)*n3',
57219 * function (node) {
57220 * // ... return a new node or return the node unchanged
57221 * return node
57222 * }
57223 * ]
57224 *
57225 * String and object rules consist of a left and right pattern. The left is
57226 * used to match against the expression and the right determines what matches
57227 * are replaced with. The main difference between a pattern and a normal
57228 * expression is that variables starting with the following characters are
57229 * interpreted as wildcards:
57230 *
57231 * - 'n' - matches any Node
57232 * - 'c' - matches any ConstantNode
57233 * - 'v' - matches any Node that is not a ConstantNode
57234 *
57235 * The default list of rules is exposed on the function as `simplify.rules`
57236 * and can be used as a basis to built a set of custom rules.
57237 *
57238 * For more details on the theory, see:
57239 *
57240 * - [Strategies for simplifying math expressions (Stackoverflow)](https://stackoverflow.com/questions/7540227/strategies-for-simplifying-math-expressions)
57241 * - [Symbolic computation - Simplification (Wikipedia)](https://en.wikipedia.org/wiki/Symbolic_computation#Simplification)
57242 *
57243 * An optional `options` argument can be passed as last argument of `simplify`.
57244 * There is currently one option available: `exactFractions`, a boolean which
57245 * is `true` by default.
57246 *
57247 * Syntax:
57248 *
57249 * simplify(expr)
57250 * simplify(expr, rules)
57251 * simplify(expr, rules)
57252 * simplify(expr, rules, scope)
57253 * simplify(expr, rules, scope, options)
57254 * simplify(expr, scope)
57255 * simplify(expr, scope, options)
57256 *
57257 * Examples:
57258 *
57259 * math.simplify('2 * 1 * x ^ (2 - 1)') // Node "2 * x"
57260 * math.simplify('2 * 3 * x', {x: 4}) // Node "24"
57261 * const f = math.parse('2 * 1 * x ^ (2 - 1)')
57262 * math.simplify(f) // Node "2 * x"
57263 * math.simplify('0.4 * x', {}, {exactFractions: true}) // Node "x * 2 / 5"
57264 * math.simplify('0.4 * x', {}, {exactFractions: false}) // Node "0.4 * x"
57265 *
57266 * See also:
57267 *
57268 * derivative, parse, evaluate, rationalize
57269 *
57270 * @param {Node | string} expr
57271 * The expression to be simplified
57272 * @param {Array<{l:string, r: string} | string | function>} [rules]
57273 * Optional list with custom rules
57274 * @return {Node} Returns the simplified form of `expr`
57275 */
57276
57277
57278 var simplify = typed('simplify', {
57279 string: function string(expr) {
57280 return simplify(parse(expr), simplify.rules, {}, {});
57281 },
57282 'string, Object': function stringObject(expr, scope) {
57283 return simplify(parse(expr), simplify.rules, scope, {});
57284 },
57285 'string, Object, Object': function stringObjectObject(expr, scope, options) {
57286 return simplify(parse(expr), simplify.rules, scope, options);
57287 },
57288 'string, Array': function stringArray(expr, rules) {
57289 return simplify(parse(expr), rules, {}, {});
57290 },
57291 'string, Array, Object': function stringArrayObject(expr, rules, scope) {
57292 return simplify(parse(expr), rules, scope, {});
57293 },
57294 'string, Array, Object, Object': function stringArrayObjectObject(expr, rules, scope, options) {
57295 return simplify(parse(expr), rules, scope, options);
57296 },
57297 'Node, Object': function NodeObject(expr, scope) {
57298 return simplify(expr, simplify.rules, scope, {});
57299 },
57300 'Node, Object, Object': function NodeObjectObject(expr, scope, options) {
57301 return simplify(expr, simplify.rules, scope, options);
57302 },
57303 Node: function Node(expr) {
57304 return simplify(expr, simplify.rules, {}, {});
57305 },
57306 'Node, Array': function NodeArray(expr, rules) {
57307 return simplify(expr, rules, {}, {});
57308 },
57309 'Node, Array, Object': function NodeArrayObject(expr, rules, scope) {
57310 return simplify(expr, rules, scope, {});
57311 },
57312 'Node, Array, Object, Object': function NodeArrayObjectObject(expr, rules, scope, options) {
57313 rules = _buildRules(rules);
57314 var res = resolve(expr, scope);
57315 res = removeParens(res);
57316 var visited = {};
57317 var str = res.toString({
57318 parenthesis: 'all'
57319 });
57320
57321 while (!visited[str]) {
57322 visited[str] = true;
57323 _lastsym = 0; // counter for placeholder symbols
57324
57325 for (var i = 0; i < rules.length; i++) {
57326 if (typeof rules[i] === 'function') {
57327 res = rules[i](res, options);
57328 } else {
57329 flatten(res);
57330 res = applyRule(res, rules[i]);
57331 }
57332
57333 unflattenl(res); // using left-heavy binary tree here since custom rule functions may expect it
57334 }
57335
57336 str = res.toString({
57337 parenthesis: 'all'
57338 });
57339 }
57340
57341 return res;
57342 }
57343 });
57344 simplify.simplifyCore = simplifyCore;
57345 simplify.resolve = resolve;
57346
57347 function removeParens(node) {
57348 return node.transform(function (node, path, parent) {
57349 return Object(is["C" /* isParenthesisNode */])(node) ? removeParens(node.content) : node;
57350 });
57351 } // All constants that are allowed in rules
57352
57353
57354 var SUPPORTED_CONSTANTS = {
57355 "true": true,
57356 "false": true,
57357 e: true,
57358 i: true,
57359 Infinity: true,
57360 LN2: true,
57361 LN10: true,
57362 LOG2E: true,
57363 LOG10E: true,
57364 NaN: true,
57365 phi: true,
57366 pi: true,
57367 SQRT1_2: true,
57368 SQRT2: true,
57369 tau: true // null: false,
57370 // undefined: false,
57371 // version: false,
57372
57373 }; // Array of strings, used to build the ruleSet.
57374 // Each l (left side) and r (right side) are parsed by
57375 // the expression parser into a node tree.
57376 // Left hand sides are matched to subtrees within the
57377 // expression to be parsed and replaced with the right
57378 // hand side.
57379 // TODO: Add support for constraints on constants (either in the form of a '=' expression or a callback [callback allows things like comparing symbols alphabetically])
57380 // To evaluate lhs constants for rhs constants, use: { l: 'c1+c2', r: 'c3', evaluate: 'c3 = c1 + c2' }. Multiple assignments are separated by ';' in block format.
57381 // It is possible to get into an infinite loop with conflicting rules
57382
57383 simplify.rules = [simplifyCore, // { l: 'n+0', r: 'n' }, // simplifyCore
57384 // { l: 'n^0', r: '1' }, // simplifyCore
57385 // { l: '0*n', r: '0' }, // simplifyCore
57386 // { l: 'n/n', r: '1'}, // simplifyCore
57387 // { l: 'n^1', r: 'n' }, // simplifyCore
57388 // { l: '+n1', r:'n1' }, // simplifyCore
57389 // { l: 'n--n1', r:'n+n1' }, // simplifyCore
57390 {
57391 l: 'log(e)',
57392 r: '1'
57393 }, // temporary rules
57394 {
57395 l: 'n-n1',
57396 r: 'n+-n1'
57397 }, // temporarily replace 'subtract' so we can further flatten the 'add' operator
57398 {
57399 l: '-(c*v)',
57400 r: '(-c) * v'
57401 }, // make non-constant terms positive
57402 {
57403 l: '-v',
57404 r: '(-1) * v'
57405 }, {
57406 l: 'n/n1^n2',
57407 r: 'n*n1^-n2'
57408 }, // temporarily replace 'divide' so we can further flatten the 'multiply' operator
57409 {
57410 l: 'n/n1',
57411 r: 'n*n1^-1'
57412 }, // expand nested exponentiation
57413 {
57414 l: '(n ^ n1) ^ n2',
57415 r: 'n ^ (n1 * n2)'
57416 }, // collect like factors
57417 {
57418 l: 'n*n',
57419 r: 'n^2'
57420 }, {
57421 l: 'n * n^n1',
57422 r: 'n^(n1+1)'
57423 }, {
57424 l: 'n^n1 * n^n2',
57425 r: 'n^(n1+n2)'
57426 }, // collect like terms
57427 {
57428 l: 'n+n',
57429 r: '2*n'
57430 }, {
57431 l: 'n+-n',
57432 r: '0'
57433 }, {
57434 l: 'n1*n2 + n2',
57435 r: '(n1+1)*n2'
57436 }, {
57437 l: 'n1*n3 + n2*n3',
57438 r: '(n1+n2)*n3'
57439 }, // remove parenthesis in the case of negating a quantitiy
57440 {
57441 l: 'n1 + -1 * (n2 + n3)',
57442 r: 'n1 + -1 * n2 + -1 * n3'
57443 }, simplifyConstant, {
57444 l: '(-n)*n1',
57445 r: '-(n*n1)'
57446 }, // make factors positive (and undo 'make non-constant terms positive')
57447 // ordering of constants
57448 {
57449 l: 'c+v',
57450 r: 'v+c',
57451 context: {
57452 add: {
57453 commutative: false
57454 }
57455 }
57456 }, {
57457 l: 'v*c',
57458 r: 'c*v',
57459 context: {
57460 multiply: {
57461 commutative: false
57462 }
57463 }
57464 }, // undo temporary rules
57465 // { l: '(-1) * n', r: '-n' }, // #811 added test which proved this is redundant
57466 {
57467 l: 'n+-n1',
57468 r: 'n-n1'
57469 }, // undo replace 'subtract'
57470 {
57471 l: 'n*(n1^-1)',
57472 r: 'n/n1'
57473 }, // undo replace 'divide'
57474 {
57475 l: 'n*n1^-n2',
57476 r: 'n/n1^n2'
57477 }, {
57478 l: 'n1^-1',
57479 r: '1/n1'
57480 }, {
57481 l: 'n*(n1/n2)',
57482 r: '(n*n1)/n2'
57483 }, // '*' before '/'
57484 {
57485 l: 'n-(n1+n2)',
57486 r: 'n-n1-n2'
57487 }, // '-' before '+'
57488 // { l: '(n1/n2)/n3', r: 'n1/(n2*n3)' },
57489 // { l: '(n*n1)/(n*n2)', r: 'n1/n2' },
57490 {
57491 l: '1*n',
57492 r: 'n'
57493 } // this pattern can be produced by simplifyConstant
57494 ];
57495 /**
57496 * Parse the string array of rules into nodes
57497 *
57498 * Example syntax for rules:
57499 *
57500 * Position constants to the left in a product:
57501 * { l: 'n1 * c1', r: 'c1 * n1' }
57502 * n1 is any Node, and c1 is a ConstantNode.
57503 *
57504 * Apply difference of squares formula:
57505 * { l: '(n1 - n2) * (n1 + n2)', r: 'n1^2 - n2^2' }
57506 * n1, n2 mean any Node.
57507 *
57508 * Short hand notation:
57509 * 'n1 * c1 -> c1 * n1'
57510 */
57511
57512 function _buildRules(rules) {
57513 // Array of rules to be used to simplify expressions
57514 var ruleSet = [];
57515
57516 for (var i = 0; i < rules.length; i++) {
57517 var rule = rules[i];
57518 var newRule = void 0;
57519
57520 var ruleType = simplify_typeof(rule);
57521
57522 switch (ruleType) {
57523 case 'string':
57524 {
57525 var lr = rule.split('->');
57526
57527 if (lr.length === 2) {
57528 rule = {
57529 l: lr[0],
57530 r: lr[1]
57531 };
57532 } else {
57533 throw SyntaxError('Could not parse rule: ' + rule);
57534 }
57535 }
57536
57537 /* falls through */
57538
57539 case 'object':
57540 newRule = {
57541 l: removeParens(parse(rule.l)),
57542 r: removeParens(parse(rule.r))
57543 };
57544
57545 if (rule.context) {
57546 newRule.evaluate = rule.context;
57547 }
57548
57549 if (rule.evaluate) {
57550 newRule.evaluate = parse(rule.evaluate);
57551 }
57552
57553 if (isAssociative(newRule.l)) {
57554 var makeNode = createMakeNodeFunction(newRule.l);
57555
57556 var expandsym = _getExpandPlaceholderSymbol();
57557
57558 newRule.expanded = {};
57559 newRule.expanded.l = makeNode([newRule.l.clone(), expandsym]); // Push the expandsym into the deepest possible branch.
57560 // This helps to match the newRule against nodes returned from getSplits() later on.
57561
57562 flatten(newRule.expanded.l);
57563 unflattenr(newRule.expanded.l);
57564 newRule.expanded.r = makeNode([newRule.r, expandsym]);
57565 }
57566
57567 break;
57568
57569 case 'function':
57570 newRule = rule;
57571 break;
57572
57573 default:
57574 throw TypeError('Unsupported type of rule: ' + ruleType);
57575 } // console.log('Adding rule: ' + rules[i])
57576 // console.log(newRule)
57577
57578
57579 ruleSet.push(newRule);
57580 }
57581
57582 return ruleSet;
57583 }
57584
57585 var _lastsym = 0;
57586
57587 function _getExpandPlaceholderSymbol() {
57588 return new SymbolNode('_p' + _lastsym++);
57589 }
57590 /**
57591 * Returns a simplfied form of node, or the original node if no simplification was possible.
57592 *
57593 * @param {ConstantNode | SymbolNode | ParenthesisNode | FunctionNode | OperatorNode} node
57594 * @return {ConstantNode | SymbolNode | ParenthesisNode | FunctionNode | OperatorNode} The simplified form of `expr`, or the original node if no simplification was possible.
57595 */
57596
57597
57598 var applyRule = typed('applyRule', {
57599 'Node, Object': function NodeObject(node, rule) {
57600 // console.log('Entering applyRule(' + node.toString() + ')')
57601 // Do not clone node unless we find a match
57602 var res = node; // First replace our child nodes with their simplified versions
57603 // If a child could not be simplified, the assignments will have
57604 // no effect since the node is returned unchanged
57605
57606 if (res instanceof OperatorNode || res instanceof FunctionNode) {
57607 if (res.args) {
57608 for (var i = 0; i < res.args.length; i++) {
57609 res.args[i] = applyRule(res.args[i], rule);
57610 }
57611 }
57612 } else if (res instanceof ParenthesisNode) {
57613 if (res.content) {
57614 res.content = applyRule(res.content, rule);
57615 }
57616 } // Try to match a rule against this node
57617
57618
57619 var repl = rule.r;
57620
57621 var matches = _ruleMatch(rule.l, res)[0]; // If the rule is associative operator, we can try matching it while allowing additional terms.
57622 // This allows us to match rules like 'n+n' to the expression '(1+x)+x' or even 'x+1+x' if the operator is commutative.
57623
57624
57625 if (!matches && rule.expanded) {
57626 repl = rule.expanded.r;
57627 matches = _ruleMatch(rule.expanded.l, res)[0];
57628 }
57629
57630 if (matches) {
57631 // const before = res.toString({parenthesis: 'all'})
57632 // Create a new node by cloning the rhs of the matched rule
57633 // we keep any implicit multiplication state if relevant
57634 var implicit = res.implicit;
57635 res = repl.clone();
57636
57637 if (implicit && 'implicit' in repl) {
57638 res.implicit = true;
57639 } // Replace placeholders with their respective nodes without traversing deeper into the replaced nodes
57640
57641
57642 res = res.transform(function (node) {
57643 if (node.isSymbolNode && Object(utils_object["f" /* hasOwnProperty */])(matches.placeholders, node.name)) {
57644 return matches.placeholders[node.name].clone();
57645 } else {
57646 return node;
57647 }
57648 }); // const after = res.toString({parenthesis: 'all'})
57649 // console.log('Simplified ' + before + ' to ' + after)
57650 }
57651
57652 return res;
57653 }
57654 });
57655 /**
57656 * Get (binary) combinations of a flattened binary node
57657 * e.g. +(node1, node2, node3) -> [
57658 * +(node1, +(node2, node3)),
57659 * +(node2, +(node1, node3)),
57660 * +(node3, +(node1, node2))]
57661 *
57662 */
57663
57664 function getSplits(node, context) {
57665 var res = [];
57666 var right, rightArgs;
57667 var makeNode = createMakeNodeFunction(node);
57668
57669 if (isCommutative(node, context)) {
57670 for (var i = 0; i < node.args.length; i++) {
57671 rightArgs = node.args.slice(0);
57672 rightArgs.splice(i, 1);
57673 right = rightArgs.length === 1 ? rightArgs[0] : makeNode(rightArgs);
57674 res.push(makeNode([node.args[i], right]));
57675 }
57676 } else {
57677 rightArgs = node.args.slice(1);
57678 right = rightArgs.length === 1 ? rightArgs[0] : makeNode(rightArgs);
57679 res.push(makeNode([node.args[0], right]));
57680 }
57681
57682 return res;
57683 }
57684 /**
57685 * Returns the set union of two match-placeholders or null if there is a conflict.
57686 */
57687
57688
57689 function mergeMatch(match1, match2) {
57690 var res = {
57691 placeholders: {}
57692 }; // Some matches may not have placeholders; this is OK
57693
57694 if (!match1.placeholders && !match2.placeholders) {
57695 return res;
57696 } else if (!match1.placeholders) {
57697 return match2;
57698 } else if (!match2.placeholders) {
57699 return match1;
57700 } // Placeholders with the same key must match exactly
57701
57702
57703 for (var key in match1.placeholders) {
57704 res.placeholders[key] = match1.placeholders[key];
57705
57706 if (Object(utils_object["f" /* hasOwnProperty */])(match2.placeholders, key)) {
57707 if (!_exactMatch(match1.placeholders[key], match2.placeholders[key])) {
57708 return null;
57709 }
57710 }
57711 }
57712
57713 for (var _key in match2.placeholders) {
57714 res.placeholders[_key] = match2.placeholders[_key];
57715 }
57716
57717 return res;
57718 }
57719 /**
57720 * Combine two lists of matches by applying mergeMatch to the cartesian product of two lists of matches.
57721 * Each list represents matches found in one child of a node.
57722 */
57723
57724
57725 function combineChildMatches(list1, list2) {
57726 var res = [];
57727
57728 if (list1.length === 0 || list2.length === 0) {
57729 return res;
57730 }
57731
57732 var merged;
57733
57734 for (var i1 = 0; i1 < list1.length; i1++) {
57735 for (var i2 = 0; i2 < list2.length; i2++) {
57736 merged = mergeMatch(list1[i1], list2[i2]);
57737
57738 if (merged) {
57739 res.push(merged);
57740 }
57741 }
57742 }
57743
57744 return res;
57745 }
57746 /**
57747 * Combine multiple lists of matches by applying mergeMatch to the cartesian product of two lists of matches.
57748 * Each list represents matches found in one child of a node.
57749 * Returns a list of unique matches.
57750 */
57751
57752
57753 function mergeChildMatches(childMatches) {
57754 if (childMatches.length === 0) {
57755 return childMatches;
57756 }
57757
57758 var sets = childMatches.reduce(combineChildMatches);
57759 var uniqueSets = [];
57760 var unique = {};
57761
57762 for (var i = 0; i < sets.length; i++) {
57763 var s = JSON.stringify(sets[i]);
57764
57765 if (!unique[s]) {
57766 unique[s] = true;
57767 uniqueSets.push(sets[i]);
57768 }
57769 }
57770
57771 return uniqueSets;
57772 }
57773 /**
57774 * Determines whether node matches rule.
57775 *
57776 * @param {ConstantNode | SymbolNode | ParenthesisNode | FunctionNode | OperatorNode} rule
57777 * @param {ConstantNode | SymbolNode | ParenthesisNode | FunctionNode | OperatorNode} node
57778 * @return {Object} Information about the match, if it exists.
57779 */
57780
57781
57782 function _ruleMatch(rule, node, isSplit) {
57783 // console.log('Entering _ruleMatch(' + JSON.stringify(rule) + ', ' + JSON.stringify(node) + ')')
57784 // console.log('rule = ' + rule)
57785 // console.log('node = ' + node)
57786 // console.log('Entering _ruleMatch(' + rule.toString() + ', ' + node.toString() + ')')
57787 var res = [{
57788 placeholders: {}
57789 }];
57790
57791 if (rule instanceof OperatorNode && node instanceof OperatorNode || rule instanceof FunctionNode && node instanceof FunctionNode) {
57792 // If the rule is an OperatorNode or a FunctionNode, then node must match exactly
57793 if (rule instanceof OperatorNode) {
57794 if (rule.op !== node.op || rule.fn !== node.fn) {
57795 return [];
57796 }
57797 } else if (rule instanceof FunctionNode) {
57798 if (rule.name !== node.name) {
57799 return [];
57800 }
57801 } // rule and node match. Search the children of rule and node.
57802
57803
57804 if (node.args.length === 1 && rule.args.length === 1 || !isAssociative(node) || isSplit) {
57805 // Expect non-associative operators to match exactly
57806 var childMatches = [];
57807
57808 for (var i = 0; i < rule.args.length; i++) {
57809 var childMatch = _ruleMatch(rule.args[i], node.args[i]);
57810
57811 if (childMatch.length === 0) {
57812 // Child did not match, so stop searching immediately
57813 return [];
57814 } // The child matched, so add the information returned from the child to our result
57815
57816
57817 childMatches.push(childMatch);
57818 }
57819
57820 res = mergeChildMatches(childMatches);
57821 } else if (node.args.length >= 2 && rule.args.length === 2) {
57822 // node is flattened, rule is not
57823 // Associative operators/functions can be split in different ways so we check if the rule matches each
57824 // them and return their union.
57825 var splits = getSplits(node, rule.context);
57826 var splitMatches = [];
57827
57828 for (var _i = 0; _i < splits.length; _i++) {
57829 var matchSet = _ruleMatch(rule, splits[_i], true); // recursing at the same tree depth here
57830
57831
57832 splitMatches = splitMatches.concat(matchSet);
57833 }
57834
57835 return splitMatches;
57836 } else if (rule.args.length > 2) {
57837 throw Error('Unexpected non-binary associative function: ' + rule.toString());
57838 } else {
57839 // Incorrect number of arguments in rule and node, so no match
57840 return [];
57841 }
57842 } else if (rule instanceof SymbolNode) {
57843 // If the rule is a SymbolNode, then it carries a special meaning
57844 // according to the first character of the symbol node name.
57845 // c.* matches a ConstantNode
57846 // n.* matches any node
57847 if (rule.name.length === 0) {
57848 throw new Error('Symbol in rule has 0 length...!?');
57849 }
57850
57851 if (SUPPORTED_CONSTANTS[rule.name]) {
57852 // built-in constant must match exactly
57853 if (rule.name !== node.name) {
57854 return [];
57855 }
57856 } else if (rule.name[0] === 'n' || rule.name.substring(0, 2) === '_p') {
57857 // rule matches _anything_, so assign this node to the rule.name placeholder
57858 // Assign node to the rule.name placeholder.
57859 // Our parent will check for matches among placeholders.
57860 res[0].placeholders[rule.name] = node;
57861 } else if (rule.name[0] === 'v') {
57862 // rule matches any variable thing (not a ConstantNode)
57863 if (!Object(is["l" /* isConstantNode */])(node)) {
57864 res[0].placeholders[rule.name] = node;
57865 } else {
57866 // Mis-match: rule was expecting something other than a ConstantNode
57867 return [];
57868 }
57869 } else if (rule.name[0] === 'c') {
57870 // rule matches any ConstantNode
57871 if (node instanceof ConstantNode) {
57872 res[0].placeholders[rule.name] = node;
57873 } else {
57874 // Mis-match: rule was expecting a ConstantNode
57875 return [];
57876 }
57877 } else {
57878 throw new Error('Invalid symbol in rule: ' + rule.name);
57879 }
57880 } else if (rule instanceof ConstantNode) {
57881 // Literal constant must match exactly
57882 if (!equal(rule.value, node.value)) {
57883 return [];
57884 }
57885 } else {
57886 // Some other node was encountered which we aren't prepared for, so no match
57887 return [];
57888 } // It's a match!
57889 // console.log('_ruleMatch(' + rule.toString() + ', ' + node.toString() + ') found a match')
57890
57891
57892 return res;
57893 }
57894 /**
57895 * Determines whether p and q (and all their children nodes) are identical.
57896 *
57897 * @param {ConstantNode | SymbolNode | ParenthesisNode | FunctionNode | OperatorNode} p
57898 * @param {ConstantNode | SymbolNode | ParenthesisNode | FunctionNode | OperatorNode} q
57899 * @return {Object} Information about the match, if it exists.
57900 */
57901
57902
57903 function _exactMatch(p, q) {
57904 if (p instanceof ConstantNode && q instanceof ConstantNode) {
57905 if (!equal(p.value, q.value)) {
57906 return false;
57907 }
57908 } else if (p instanceof SymbolNode && q instanceof SymbolNode) {
57909 if (p.name !== q.name) {
57910 return false;
57911 }
57912 } else if (p instanceof OperatorNode && q instanceof OperatorNode || p instanceof FunctionNode && q instanceof FunctionNode) {
57913 if (p instanceof OperatorNode) {
57914 if (p.op !== q.op || p.fn !== q.fn) {
57915 return false;
57916 }
57917 } else if (p instanceof FunctionNode) {
57918 if (p.name !== q.name) {
57919 return false;
57920 }
57921 }
57922
57923 if (p.args.length !== q.args.length) {
57924 return false;
57925 }
57926
57927 for (var i = 0; i < p.args.length; i++) {
57928 if (!_exactMatch(p.args[i], q.args[i])) {
57929 return false;
57930 }
57931 }
57932 } else {
57933 return false;
57934 }
57935
57936 return true;
57937 }
57938
57939 return simplify;
57940});
57941// CONCATENATED MODULE: ./src/function/algebra/derivative.js
57942
57943
57944var derivative_name = 'derivative';
57945var derivative_dependencies = ['typed', 'config', 'parse', 'simplify', 'equal', 'isZero', 'numeric', 'ConstantNode', 'FunctionNode', 'OperatorNode', 'ParenthesisNode', 'SymbolNode'];
57946var createDerivative =
57947/* #__PURE__ */
57948Object(factory["a" /* factory */])(derivative_name, derivative_dependencies, function (_ref) {
57949 var typed = _ref.typed,
57950 config = _ref.config,
57951 parse = _ref.parse,
57952 simplify = _ref.simplify,
57953 equal = _ref.equal,
57954 isZero = _ref.isZero,
57955 numeric = _ref.numeric,
57956 ConstantNode = _ref.ConstantNode,
57957 FunctionNode = _ref.FunctionNode,
57958 OperatorNode = _ref.OperatorNode,
57959 ParenthesisNode = _ref.ParenthesisNode,
57960 SymbolNode = _ref.SymbolNode;
57961
57962 /**
57963 * Takes the derivative of an expression expressed in parser Nodes.
57964 * The derivative will be taken over the supplied variable in the
57965 * second parameter. If there are multiple variables in the expression,
57966 * it will return a partial derivative.
57967 *
57968 * This uses rules of differentiation which can be found here:
57969 *
57970 * - [Differentiation rules (Wikipedia)](https://en.wikipedia.org/wiki/Differentiation_rules)
57971 *
57972 * Syntax:
57973 *
57974 * derivative(expr, variable)
57975 * derivative(expr, variable, options)
57976 *
57977 * Examples:
57978 *
57979 * math.derivative('x^2', 'x') // Node {2 * x}
57980 * math.derivative('x^2', 'x', {simplify: false}) // Node {2 * 1 * x ^ (2 - 1)
57981 * math.derivative('sin(2x)', 'x')) // Node {2 * cos(2 * x)}
57982 * math.derivative('2*x', 'x').evaluate() // number 2
57983 * math.derivative('x^2', 'x').evaluate({x: 4}) // number 8
57984 * const f = math.parse('x^2')
57985 * const x = math.parse('x')
57986 * math.derivative(f, x) // Node {2 * x}
57987 *
57988 * See also:
57989 *
57990 * simplify, parse, evaluate
57991 *
57992 * @param {Node | string} expr The expression to differentiate
57993 * @param {SymbolNode | string} variable The variable over which to differentiate
57994 * @param {{simplify: boolean}} [options]
57995 * There is one option available, `simplify`, which
57996 * is true by default. When false, output will not
57997 * be simplified.
57998 * @return {ConstantNode | SymbolNode | ParenthesisNode | FunctionNode | OperatorNode} The derivative of `expr`
57999 */
58000 var derivative = typed('derivative', {
58001 'Node, SymbolNode, Object': function NodeSymbolNodeObject(expr, variable, options) {
58002 var constNodes = {};
58003 constTag(constNodes, expr, variable.name);
58004
58005 var res = _derivative(expr, constNodes);
58006
58007 return options.simplify ? simplify(res) : res;
58008 },
58009 'Node, SymbolNode': function NodeSymbolNode(expr, variable) {
58010 return derivative(expr, variable, {
58011 simplify: true
58012 });
58013 },
58014 'string, SymbolNode': function stringSymbolNode(expr, variable) {
58015 return derivative(parse(expr), variable);
58016 },
58017 'string, SymbolNode, Object': function stringSymbolNodeObject(expr, variable, options) {
58018 return derivative(parse(expr), variable, options);
58019 },
58020 'string, string': function stringString(expr, variable) {
58021 return derivative(parse(expr), parse(variable));
58022 },
58023 'string, string, Object': function stringStringObject(expr, variable, options) {
58024 return derivative(parse(expr), parse(variable), options);
58025 },
58026 'Node, string': function NodeString(expr, variable) {
58027 return derivative(expr, parse(variable));
58028 },
58029 'Node, string, Object': function NodeStringObject(expr, variable, options) {
58030 return derivative(expr, parse(variable), options);
58031 } // TODO: replace the 8 signatures above with 4 as soon as typed-function supports optional arguments
58032
58033 /* TODO: implement and test syntax with order of derivatives -> implement as an option {order: number}
58034 'Node, SymbolNode, ConstantNode': function (expr, variable, {order}) {
58035 let res = expr
58036 for (let i = 0; i < order; i++) {
58037 let constNodes = {}
58038 constTag(constNodes, expr, variable.name)
58039 res = _derivative(res, constNodes)
58040 }
58041 return res
58042 }
58043 */
58044
58045 });
58046 derivative._simplify = true;
58047
58048 derivative.toTex = function (deriv) {
58049 return _derivTex.apply(null, deriv.args);
58050 }; // FIXME: move the toTex method of derivative to latex.js. Difficulty is that it relies on parse.
58051 // NOTE: the optional "order" parameter here is currently unused
58052
58053
58054 var _derivTex = typed('_derivTex', {
58055 'Node, SymbolNode': function NodeSymbolNode(expr, x) {
58056 if (Object(is["l" /* isConstantNode */])(expr) && Object(is["M" /* typeOf */])(expr.value) === 'string') {
58057 return _derivTex(parse(expr.value).toString(), x.toString(), 1);
58058 } else {
58059 return _derivTex(expr.toString(), x.toString(), 1);
58060 }
58061 },
58062 'Node, ConstantNode': function NodeConstantNode(expr, x) {
58063 if (Object(is["M" /* typeOf */])(x.value) === 'string') {
58064 return _derivTex(expr, parse(x.value));
58065 } else {
58066 throw new Error("The second parameter to 'derivative' is a non-string constant");
58067 }
58068 },
58069 'Node, SymbolNode, ConstantNode': function NodeSymbolNodeConstantNode(expr, x, order) {
58070 return _derivTex(expr.toString(), x.name, order.value);
58071 },
58072 'string, string, number': function stringStringNumber(expr, x, order) {
58073 var d;
58074
58075 if (order === 1) {
58076 d = '{d\\over d' + x + '}';
58077 } else {
58078 d = '{d^{' + order + '}\\over d' + x + '^{' + order + '}}';
58079 }
58080
58081 return d + "\\left[".concat(expr, "\\right]");
58082 }
58083 });
58084 /**
58085 * Does a depth-first search on the expression tree to identify what Nodes
58086 * are constants (e.g. 2 + 2), and stores the ones that are constants in
58087 * constNodes. Classification is done as follows:
58088 *
58089 * 1. ConstantNodes are constants.
58090 * 2. If there exists a SymbolNode, of which we are differentiating over,
58091 * in the subtree it is not constant.
58092 *
58093 * @param {Object} constNodes Holds the nodes that are constant
58094 * @param {ConstantNode | SymbolNode | ParenthesisNode | FunctionNode | OperatorNode} node
58095 * @param {string} varName Variable that we are differentiating
58096 * @return {boolean} if node is constant
58097 */
58098 // TODO: can we rewrite constTag into a pure function?
58099
58100
58101 var constTag = typed('constTag', {
58102 'Object, ConstantNode, string': function ObjectConstantNodeString(constNodes, node) {
58103 constNodes[node] = true;
58104 return true;
58105 },
58106 'Object, SymbolNode, string': function ObjectSymbolNodeString(constNodes, node, varName) {
58107 // Treat other variables like constants. For reasoning, see:
58108 // https://en.wikipedia.org/wiki/Partial_derivative
58109 if (node.name !== varName) {
58110 constNodes[node] = true;
58111 return true;
58112 }
58113
58114 return false;
58115 },
58116 'Object, ParenthesisNode, string': function ObjectParenthesisNodeString(constNodes, node, varName) {
58117 return constTag(constNodes, node.content, varName);
58118 },
58119 'Object, FunctionAssignmentNode, string': function ObjectFunctionAssignmentNodeString(constNodes, node, varName) {
58120 if (node.params.indexOf(varName) === -1) {
58121 constNodes[node] = true;
58122 return true;
58123 }
58124
58125 return constTag(constNodes, node.expr, varName);
58126 },
58127 'Object, FunctionNode | OperatorNode, string': function ObjectFunctionNodeOperatorNodeString(constNodes, node, varName) {
58128 if (node.args.length > 0) {
58129 var isConst = constTag(constNodes, node.args[0], varName);
58130
58131 for (var i = 1; i < node.args.length; ++i) {
58132 isConst = constTag(constNodes, node.args[i], varName) && isConst;
58133 }
58134
58135 if (isConst) {
58136 constNodes[node] = true;
58137 return true;
58138 }
58139 }
58140
58141 return false;
58142 }
58143 });
58144 /**
58145 * Applies differentiation rules.
58146 *
58147 * @param {ConstantNode | SymbolNode | ParenthesisNode | FunctionNode | OperatorNode} node
58148 * @param {Object} constNodes Holds the nodes that are constant
58149 * @return {ConstantNode | SymbolNode | ParenthesisNode | FunctionNode | OperatorNode} The derivative of `expr`
58150 */
58151
58152 var _derivative = typed('_derivative', {
58153 'ConstantNode, Object': function ConstantNodeObject(node) {
58154 return createConstantNode(0);
58155 },
58156 'SymbolNode, Object': function SymbolNodeObject(node, constNodes) {
58157 if (constNodes[node] !== undefined) {
58158 return createConstantNode(0);
58159 }
58160
58161 return createConstantNode(1);
58162 },
58163 'ParenthesisNode, Object': function ParenthesisNodeObject(node, constNodes) {
58164 return new ParenthesisNode(_derivative(node.content, constNodes));
58165 },
58166 'FunctionAssignmentNode, Object': function FunctionAssignmentNodeObject(node, constNodes) {
58167 if (constNodes[node] !== undefined) {
58168 return createConstantNode(0);
58169 }
58170
58171 return _derivative(node.expr, constNodes);
58172 },
58173 'FunctionNode, Object': function FunctionNodeObject(node, constNodes) {
58174 if (node.args.length !== 1) {
58175 funcArgsCheck(node);
58176 }
58177
58178 if (constNodes[node] !== undefined) {
58179 return createConstantNode(0);
58180 }
58181
58182 var arg0 = node.args[0];
58183 var arg1;
58184 var div = false; // is output a fraction?
58185
58186 var negative = false; // is output negative?
58187
58188 var funcDerivative;
58189
58190 switch (node.name) {
58191 case 'cbrt':
58192 // d/dx(cbrt(x)) = 1 / (3x^(2/3))
58193 div = true;
58194 funcDerivative = new OperatorNode('*', 'multiply', [createConstantNode(3), new OperatorNode('^', 'pow', [arg0, new OperatorNode('/', 'divide', [createConstantNode(2), createConstantNode(3)])])]);
58195 break;
58196
58197 case 'sqrt':
58198 case 'nthRoot':
58199 // d/dx(sqrt(x)) = 1 / (2*sqrt(x))
58200 if (node.args.length === 1) {
58201 div = true;
58202 funcDerivative = new OperatorNode('*', 'multiply', [createConstantNode(2), new FunctionNode('sqrt', [arg0])]);
58203 } else if (node.args.length === 2) {
58204 // Rearrange from nthRoot(x, a) -> x^(1/a)
58205 arg1 = new OperatorNode('/', 'divide', [createConstantNode(1), node.args[1]]); // Is a variable?
58206
58207 constNodes[arg1] = constNodes[node.args[1]];
58208 return _derivative(new OperatorNode('^', 'pow', [arg0, arg1]), constNodes);
58209 }
58210
58211 break;
58212
58213 case 'log10':
58214 arg1 = createConstantNode(10);
58215
58216 /* fall through! */
58217
58218 case 'log':
58219 if (!arg1 && node.args.length === 1) {
58220 // d/dx(log(x)) = 1 / x
58221 funcDerivative = arg0.clone();
58222 div = true;
58223 } else if (node.args.length === 1 && arg1 || node.args.length === 2 && constNodes[node.args[1]] !== undefined) {
58224 // d/dx(log(x, c)) = 1 / (x*ln(c))
58225 funcDerivative = new OperatorNode('*', 'multiply', [arg0.clone(), new FunctionNode('log', [arg1 || node.args[1]])]);
58226 div = true;
58227 } else if (node.args.length === 2) {
58228 // d/dx(log(f(x), g(x))) = d/dx(log(f(x)) / log(g(x)))
58229 return _derivative(new OperatorNode('/', 'divide', [new FunctionNode('log', [arg0]), new FunctionNode('log', [node.args[1]])]), constNodes);
58230 }
58231
58232 break;
58233
58234 case 'pow':
58235 constNodes[arg1] = constNodes[node.args[1]]; // Pass to pow operator node parser
58236
58237 return _derivative(new OperatorNode('^', 'pow', [arg0, node.args[1]]), constNodes);
58238
58239 case 'exp':
58240 // d/dx(e^x) = e^x
58241 funcDerivative = new FunctionNode('exp', [arg0.clone()]);
58242 break;
58243
58244 case 'sin':
58245 // d/dx(sin(x)) = cos(x)
58246 funcDerivative = new FunctionNode('cos', [arg0.clone()]);
58247 break;
58248
58249 case 'cos':
58250 // d/dx(cos(x)) = -sin(x)
58251 funcDerivative = new OperatorNode('-', 'unaryMinus', [new FunctionNode('sin', [arg0.clone()])]);
58252 break;
58253
58254 case 'tan':
58255 // d/dx(tan(x)) = sec(x)^2
58256 funcDerivative = new OperatorNode('^', 'pow', [new FunctionNode('sec', [arg0.clone()]), createConstantNode(2)]);
58257 break;
58258
58259 case 'sec':
58260 // d/dx(sec(x)) = sec(x)tan(x)
58261 funcDerivative = new OperatorNode('*', 'multiply', [node, new FunctionNode('tan', [arg0.clone()])]);
58262 break;
58263
58264 case 'csc':
58265 // d/dx(csc(x)) = -csc(x)cot(x)
58266 negative = true;
58267 funcDerivative = new OperatorNode('*', 'multiply', [node, new FunctionNode('cot', [arg0.clone()])]);
58268 break;
58269
58270 case 'cot':
58271 // d/dx(cot(x)) = -csc(x)^2
58272 negative = true;
58273 funcDerivative = new OperatorNode('^', 'pow', [new FunctionNode('csc', [arg0.clone()]), createConstantNode(2)]);
58274 break;
58275
58276 case 'asin':
58277 // d/dx(asin(x)) = 1 / sqrt(1 - x^2)
58278 div = true;
58279 funcDerivative = new FunctionNode('sqrt', [new OperatorNode('-', 'subtract', [createConstantNode(1), new OperatorNode('^', 'pow', [arg0.clone(), createConstantNode(2)])])]);
58280 break;
58281
58282 case 'acos':
58283 // d/dx(acos(x)) = -1 / sqrt(1 - x^2)
58284 div = true;
58285 negative = true;
58286 funcDerivative = new FunctionNode('sqrt', [new OperatorNode('-', 'subtract', [createConstantNode(1), new OperatorNode('^', 'pow', [arg0.clone(), createConstantNode(2)])])]);
58287 break;
58288
58289 case 'atan':
58290 // d/dx(atan(x)) = 1 / (x^2 + 1)
58291 div = true;
58292 funcDerivative = new OperatorNode('+', 'add', [new OperatorNode('^', 'pow', [arg0.clone(), createConstantNode(2)]), createConstantNode(1)]);
58293 break;
58294
58295 case 'asec':
58296 // d/dx(asec(x)) = 1 / (|x|*sqrt(x^2 - 1))
58297 div = true;
58298 funcDerivative = new OperatorNode('*', 'multiply', [new FunctionNode('abs', [arg0.clone()]), new FunctionNode('sqrt', [new OperatorNode('-', 'subtract', [new OperatorNode('^', 'pow', [arg0.clone(), createConstantNode(2)]), createConstantNode(1)])])]);
58299 break;
58300
58301 case 'acsc':
58302 // d/dx(acsc(x)) = -1 / (|x|*sqrt(x^2 - 1))
58303 div = true;
58304 negative = true;
58305 funcDerivative = new OperatorNode('*', 'multiply', [new FunctionNode('abs', [arg0.clone()]), new FunctionNode('sqrt', [new OperatorNode('-', 'subtract', [new OperatorNode('^', 'pow', [arg0.clone(), createConstantNode(2)]), createConstantNode(1)])])]);
58306 break;
58307
58308 case 'acot':
58309 // d/dx(acot(x)) = -1 / (x^2 + 1)
58310 div = true;
58311 negative = true;
58312 funcDerivative = new OperatorNode('+', 'add', [new OperatorNode('^', 'pow', [arg0.clone(), createConstantNode(2)]), createConstantNode(1)]);
58313 break;
58314
58315 case 'sinh':
58316 // d/dx(sinh(x)) = cosh(x)
58317 funcDerivative = new FunctionNode('cosh', [arg0.clone()]);
58318 break;
58319
58320 case 'cosh':
58321 // d/dx(cosh(x)) = sinh(x)
58322 funcDerivative = new FunctionNode('sinh', [arg0.clone()]);
58323 break;
58324
58325 case 'tanh':
58326 // d/dx(tanh(x)) = sech(x)^2
58327 funcDerivative = new OperatorNode('^', 'pow', [new FunctionNode('sech', [arg0.clone()]), createConstantNode(2)]);
58328 break;
58329
58330 case 'sech':
58331 // d/dx(sech(x)) = -sech(x)tanh(x)
58332 negative = true;
58333 funcDerivative = new OperatorNode('*', 'multiply', [node, new FunctionNode('tanh', [arg0.clone()])]);
58334 break;
58335
58336 case 'csch':
58337 // d/dx(csch(x)) = -csch(x)coth(x)
58338 negative = true;
58339 funcDerivative = new OperatorNode('*', 'multiply', [node, new FunctionNode('coth', [arg0.clone()])]);
58340 break;
58341
58342 case 'coth':
58343 // d/dx(coth(x)) = -csch(x)^2
58344 negative = true;
58345 funcDerivative = new OperatorNode('^', 'pow', [new FunctionNode('csch', [arg0.clone()]), createConstantNode(2)]);
58346 break;
58347
58348 case 'asinh':
58349 // d/dx(asinh(x)) = 1 / sqrt(x^2 + 1)
58350 div = true;
58351 funcDerivative = new FunctionNode('sqrt', [new OperatorNode('+', 'add', [new OperatorNode('^', 'pow', [arg0.clone(), createConstantNode(2)]), createConstantNode(1)])]);
58352 break;
58353
58354 case 'acosh':
58355 // d/dx(acosh(x)) = 1 / sqrt(x^2 - 1); XXX potentially only for x >= 1 (the real spectrum)
58356 div = true;
58357 funcDerivative = new FunctionNode('sqrt', [new OperatorNode('-', 'subtract', [new OperatorNode('^', 'pow', [arg0.clone(), createConstantNode(2)]), createConstantNode(1)])]);
58358 break;
58359
58360 case 'atanh':
58361 // d/dx(atanh(x)) = 1 / (1 - x^2)
58362 div = true;
58363 funcDerivative = new OperatorNode('-', 'subtract', [createConstantNode(1), new OperatorNode('^', 'pow', [arg0.clone(), createConstantNode(2)])]);
58364 break;
58365
58366 case 'asech':
58367 // d/dx(asech(x)) = -1 / (x*sqrt(1 - x^2))
58368 div = true;
58369 negative = true;
58370 funcDerivative = new OperatorNode('*', 'multiply', [arg0.clone(), new FunctionNode('sqrt', [new OperatorNode('-', 'subtract', [createConstantNode(1), new OperatorNode('^', 'pow', [arg0.clone(), createConstantNode(2)])])])]);
58371 break;
58372
58373 case 'acsch':
58374 // d/dx(acsch(x)) = -1 / (|x|*sqrt(x^2 + 1))
58375 div = true;
58376 negative = true;
58377 funcDerivative = new OperatorNode('*', 'multiply', [new FunctionNode('abs', [arg0.clone()]), new FunctionNode('sqrt', [new OperatorNode('+', 'add', [new OperatorNode('^', 'pow', [arg0.clone(), createConstantNode(2)]), createConstantNode(1)])])]);
58378 break;
58379
58380 case 'acoth':
58381 // d/dx(acoth(x)) = -1 / (1 - x^2)
58382 div = true;
58383 negative = true;
58384 funcDerivative = new OperatorNode('-', 'subtract', [createConstantNode(1), new OperatorNode('^', 'pow', [arg0.clone(), createConstantNode(2)])]);
58385 break;
58386
58387 case 'abs':
58388 // d/dx(abs(x)) = abs(x)/x
58389 funcDerivative = new OperatorNode('/', 'divide', [new FunctionNode(new SymbolNode('abs'), [arg0.clone()]), arg0.clone()]);
58390 break;
58391
58392 case 'gamma': // Needs digamma function, d/dx(gamma(x)) = gamma(x)digamma(x)
58393
58394 default:
58395 throw new Error('Function "' + node.name + '" is not supported by derivative, or a wrong number of arguments is passed');
58396 }
58397
58398 var op, func;
58399
58400 if (div) {
58401 op = '/';
58402 func = 'divide';
58403 } else {
58404 op = '*';
58405 func = 'multiply';
58406 }
58407 /* Apply chain rule to all functions:
58408 F(x) = f(g(x))
58409 F'(x) = g'(x)*f'(g(x)) */
58410
58411
58412 var chainDerivative = _derivative(arg0, constNodes);
58413
58414 if (negative) {
58415 chainDerivative = new OperatorNode('-', 'unaryMinus', [chainDerivative]);
58416 }
58417
58418 return new OperatorNode(op, func, [chainDerivative, funcDerivative]);
58419 },
58420 'OperatorNode, Object': function OperatorNodeObject(node, constNodes) {
58421 if (constNodes[node] !== undefined) {
58422 return createConstantNode(0);
58423 }
58424
58425 if (node.op === '+') {
58426 // d/dx(sum(f(x)) = sum(f'(x))
58427 return new OperatorNode(node.op, node.fn, node.args.map(function (arg) {
58428 return _derivative(arg, constNodes);
58429 }));
58430 }
58431
58432 if (node.op === '-') {
58433 // d/dx(+/-f(x)) = +/-f'(x)
58434 if (node.isUnary()) {
58435 return new OperatorNode(node.op, node.fn, [_derivative(node.args[0], constNodes)]);
58436 } // Linearity of differentiation, d/dx(f(x) +/- g(x)) = f'(x) +/- g'(x)
58437
58438
58439 if (node.isBinary()) {
58440 return new OperatorNode(node.op, node.fn, [_derivative(node.args[0], constNodes), _derivative(node.args[1], constNodes)]);
58441 }
58442 }
58443
58444 if (node.op === '*') {
58445 // d/dx(c*f(x)) = c*f'(x)
58446 var constantTerms = node.args.filter(function (arg) {
58447 return constNodes[arg] !== undefined;
58448 });
58449
58450 if (constantTerms.length > 0) {
58451 var nonConstantTerms = node.args.filter(function (arg) {
58452 return constNodes[arg] === undefined;
58453 });
58454 var nonConstantNode = nonConstantTerms.length === 1 ? nonConstantTerms[0] : new OperatorNode('*', 'multiply', nonConstantTerms);
58455 var newArgs = constantTerms.concat(_derivative(nonConstantNode, constNodes));
58456 return new OperatorNode('*', 'multiply', newArgs);
58457 } // Product Rule, d/dx(f(x)*g(x)) = f'(x)*g(x) + f(x)*g'(x)
58458
58459
58460 return new OperatorNode('+', 'add', node.args.map(function (argOuter) {
58461 return new OperatorNode('*', 'multiply', node.args.map(function (argInner) {
58462 return argInner === argOuter ? _derivative(argInner, constNodes) : argInner.clone();
58463 }));
58464 }));
58465 }
58466
58467 if (node.op === '/' && node.isBinary()) {
58468 var arg0 = node.args[0];
58469 var arg1 = node.args[1]; // d/dx(f(x) / c) = f'(x) / c
58470
58471 if (constNodes[arg1] !== undefined) {
58472 return new OperatorNode('/', 'divide', [_derivative(arg0, constNodes), arg1]);
58473 } // Reciprocal Rule, d/dx(c / f(x)) = -c(f'(x)/f(x)^2)
58474
58475
58476 if (constNodes[arg0] !== undefined) {
58477 return new OperatorNode('*', 'multiply', [new OperatorNode('-', 'unaryMinus', [arg0]), new OperatorNode('/', 'divide', [_derivative(arg1, constNodes), new OperatorNode('^', 'pow', [arg1.clone(), createConstantNode(2)])])]);
58478 } // Quotient rule, d/dx(f(x) / g(x)) = (f'(x)g(x) - f(x)g'(x)) / g(x)^2
58479
58480
58481 return new OperatorNode('/', 'divide', [new OperatorNode('-', 'subtract', [new OperatorNode('*', 'multiply', [_derivative(arg0, constNodes), arg1.clone()]), new OperatorNode('*', 'multiply', [arg0.clone(), _derivative(arg1, constNodes)])]), new OperatorNode('^', 'pow', [arg1.clone(), createConstantNode(2)])]);
58482 }
58483
58484 if (node.op === '^' && node.isBinary()) {
58485 var _arg = node.args[0];
58486 var _arg2 = node.args[1];
58487
58488 if (constNodes[_arg] !== undefined) {
58489 // If is secretly constant; 0^f(x) = 1 (in JS), 1^f(x) = 1
58490 if (Object(is["l" /* isConstantNode */])(_arg) && (isZero(_arg.value) || equal(_arg.value, 1))) {
58491 return createConstantNode(0);
58492 } // d/dx(c^f(x)) = c^f(x)*ln(c)*f'(x)
58493
58494
58495 return new OperatorNode('*', 'multiply', [node, new OperatorNode('*', 'multiply', [new FunctionNode('log', [_arg.clone()]), _derivative(_arg2.clone(), constNodes)])]);
58496 }
58497
58498 if (constNodes[_arg2] !== undefined) {
58499 if (Object(is["l" /* isConstantNode */])(_arg2)) {
58500 // If is secretly constant; f(x)^0 = 1 -> d/dx(1) = 0
58501 if (isZero(_arg2.value)) {
58502 return createConstantNode(0);
58503 } // Ignore exponent; f(x)^1 = f(x)
58504
58505
58506 if (equal(_arg2.value, 1)) {
58507 return _derivative(_arg, constNodes);
58508 }
58509 } // Elementary Power Rule, d/dx(f(x)^c) = c*f'(x)*f(x)^(c-1)
58510
58511
58512 var powMinusOne = new OperatorNode('^', 'pow', [_arg.clone(), new OperatorNode('-', 'subtract', [_arg2, createConstantNode(1)])]);
58513 return new OperatorNode('*', 'multiply', [_arg2.clone(), new OperatorNode('*', 'multiply', [_derivative(_arg, constNodes), powMinusOne])]);
58514 } // Functional Power Rule, d/dx(f^g) = f^g*[f'*(g/f) + g'ln(f)]
58515
58516
58517 return new OperatorNode('*', 'multiply', [new OperatorNode('^', 'pow', [_arg.clone(), _arg2.clone()]), new OperatorNode('+', 'add', [new OperatorNode('*', 'multiply', [_derivative(_arg, constNodes), new OperatorNode('/', 'divide', [_arg2.clone(), _arg.clone()])]), new OperatorNode('*', 'multiply', [_derivative(_arg2, constNodes), new FunctionNode('log', [_arg.clone()])])])]);
58518 }
58519
58520 throw new Error('Operator "' + node.op + '" is not supported by derivative, or a wrong number of arguments is passed');
58521 }
58522 });
58523 /**
58524 * Ensures the number of arguments for a function are correct,
58525 * and will throw an error otherwise.
58526 *
58527 * @param {FunctionNode} node
58528 */
58529
58530
58531 function funcArgsCheck(node) {
58532 // TODO add min, max etc
58533 if ((node.name === 'log' || node.name === 'nthRoot' || node.name === 'pow') && node.args.length === 2) {
58534 return;
58535 } // There should be an incorrect number of arguments if we reach here
58536 // Change all args to constants to avoid unidentified
58537 // symbol error when compiling function
58538
58539
58540 for (var i = 0; i < node.args.length; ++i) {
58541 node.args[i] = createConstantNode(0);
58542 }
58543
58544 node.compile().evaluate();
58545 throw new Error('Expected TypeError, but none found');
58546 }
58547 /**
58548 * Helper function to create a constant node with a specific type
58549 * (number, BigNumber, Fraction)
58550 * @param {number} value
58551 * @param {string} [valueType]
58552 * @return {ConstantNode}
58553 */
58554
58555
58556 function createConstantNode(value, valueType) {
58557 return new ConstantNode(numeric(value, valueType || config.number));
58558 }
58559
58560 return derivative;
58561});
58562// CONCATENATED MODULE: ./src/function/algebra/rationalize.js
58563
58564
58565
58566
58567var rationalize_name = 'rationalize';
58568var rationalize_dependencies = ['config', 'typed', 'equal', 'isZero', 'add', 'subtract', 'multiply', 'divide', 'pow', 'parse', 'simplify', '?bignumber', '?fraction', 'mathWithTransform', 'ConstantNode', 'OperatorNode', 'FunctionNode', 'SymbolNode', 'ParenthesisNode'];
58569var createRationalize =
58570/* #__PURE__ */
58571Object(factory["a" /* factory */])(rationalize_name, rationalize_dependencies, function (_ref) {
58572 var config = _ref.config,
58573 typed = _ref.typed,
58574 equal = _ref.equal,
58575 isZero = _ref.isZero,
58576 add = _ref.add,
58577 subtract = _ref.subtract,
58578 multiply = _ref.multiply,
58579 divide = _ref.divide,
58580 pow = _ref.pow,
58581 parse = _ref.parse,
58582 simplify = _ref.simplify,
58583 fraction = _ref.fraction,
58584 bignumber = _ref.bignumber,
58585 mathWithTransform = _ref.mathWithTransform,
58586 ConstantNode = _ref.ConstantNode,
58587 OperatorNode = _ref.OperatorNode,
58588 FunctionNode = _ref.FunctionNode,
58589 SymbolNode = _ref.SymbolNode,
58590 ParenthesisNode = _ref.ParenthesisNode;
58591 var simplifyConstant = createSimplifyConstant({
58592 typed: typed,
58593 config: config,
58594 mathWithTransform: mathWithTransform,
58595 fraction: fraction,
58596 bignumber: bignumber,
58597 ConstantNode: ConstantNode,
58598 OperatorNode: OperatorNode,
58599 FunctionNode: FunctionNode,
58600 SymbolNode: SymbolNode
58601 });
58602 var simplifyCore = createSimplifyCore({
58603 equal: equal,
58604 isZero: isZero,
58605 add: add,
58606 subtract: subtract,
58607 multiply: multiply,
58608 divide: divide,
58609 pow: pow,
58610 ConstantNode: ConstantNode,
58611 OperatorNode: OperatorNode,
58612 FunctionNode: FunctionNode,
58613 ParenthesisNode: ParenthesisNode
58614 });
58615 /**
58616 * Transform a rationalizable expression in a rational fraction.
58617 * If rational fraction is one variable polynomial then converts
58618 * the numerator and denominator in canonical form, with decreasing
58619 * exponents, returning the coefficients of numerator.
58620 *
58621 * Syntax:
58622 *
58623 * rationalize(expr)
58624 * rationalize(expr, detailed)
58625 * rationalize(expr, scope)
58626 * rationalize(expr, scope, detailed)
58627 *
58628 * Examples:
58629 *
58630 * math.rationalize('sin(x)+y')
58631 * // Error: There is an unsolved function call
58632 * math.rationalize('2x/y - y/(x+1)')
58633 * // (2*x^2-y^2+2*x)/(x*y+y)
58634 * math.rationalize('(2x+1)^6')
58635 * // 64*x^6+192*x^5+240*x^4+160*x^3+60*x^2+12*x+1
58636 * math.rationalize('2x/( (2x-1) / (3x+2) ) - 5x/ ( (3x+4) / (2x^2-5) ) + 3')
58637 * // -20*x^4+28*x^3+104*x^2+6*x-12)/(6*x^2+5*x-4)
58638 * math.rationalize('x/(1-x)/(x-2)/(x-3)/(x-4) + 2x/ ( (1-2x)/(2-3x) )/ ((3-4x)/(4-5x) )') =
58639 * // (-30*x^7+344*x^6-1506*x^5+3200*x^4-3472*x^3+1846*x^2-381*x)/
58640 * // (-8*x^6+90*x^5-383*x^4+780*x^3-797*x^2+390*x-72)
58641 *
58642 * math.rationalize('x+x+x+y',{y:1}) // 3*x+1
58643 * math.rationalize('x+x+x+y',{}) // 3*x+y
58644 *
58645 * const ret = math.rationalize('x+x+x+y',{},true)
58646 * // ret.expression=3*x+y, ret.variables = ["x","y"]
58647 * const ret = math.rationalize('-2+5x^2',{},true)
58648 * // ret.expression=5*x^2-2, ret.variables = ["x"], ret.coefficients=[-2,0,5]
58649 *
58650 * See also:
58651 *
58652 * simplify
58653 *
58654 * @param {Node|string} expr The expression to check if is a polynomial expression
58655 * @param {Object|boolean} optional scope of expression or true for already evaluated rational expression at input
58656 * @param {Boolean} detailed optional True if return an object, false if return expression node (default)
58657 *
58658 * @return {Object | Node} The rational polynomial of `expr` or na object
58659 * {Object}
58660 * {Expression Node} expression: node simplified expression
58661 * {Expression Node} numerator: simplified numerator of expression
58662 * {Expression Node | boolean} denominator: simplified denominator or false (if there is no denominator)
58663 * {Array} variables: variable names
58664 * {Array} coefficients: coefficients of numerator sorted by increased exponent
58665 * {Expression Node} node simplified expression
58666 *
58667 */
58668
58669 var rationalize = typed(rationalize_name, {
58670 string: function string(expr) {
58671 return rationalize(parse(expr), {}, false);
58672 },
58673 'string, boolean': function stringBoolean(expr, detailed) {
58674 return rationalize(parse(expr), {}, detailed);
58675 },
58676 'string, Object': function stringObject(expr, scope) {
58677 return rationalize(parse(expr), scope, false);
58678 },
58679 'string, Object, boolean': function stringObjectBoolean(expr, scope, detailed) {
58680 return rationalize(parse(expr), scope, detailed);
58681 },
58682 Node: function Node(expr) {
58683 return rationalize(expr, {}, false);
58684 },
58685 'Node, boolean': function NodeBoolean(expr, detailed) {
58686 return rationalize(expr, {}, detailed);
58687 },
58688 'Node, Object': function NodeObject(expr, scope) {
58689 return rationalize(expr, scope, false);
58690 },
58691 'Node, Object, boolean': function NodeObjectBoolean(expr, scope, detailed) {
58692 var setRules = rulesRationalize(); // Rules for change polynomial in near canonical form
58693
58694 var polyRet = polynomial(expr, scope, true, setRules.firstRules); // Check if expression is a rationalizable polynomial
58695
58696 var nVars = polyRet.variables.length;
58697 expr = polyRet.expression;
58698
58699 if (nVars >= 1) {
58700 // If expression in not a constant
58701 expr = expandPower(expr); // First expand power of polynomials (cannot be made from rules!)
58702
58703 var sBefore; // Previous expression
58704
58705 var rules;
58706 var eDistrDiv = true;
58707 var redoInic = false;
58708 expr = simplify(expr, setRules.firstRules, {}, {
58709 exactFractions: false
58710 }); // Apply the initial rules, including succ div rules
58711
58712 var s;
58713
58714 while (true) {
58715 // Apply alternately successive division rules and distr.div.rules
58716 rules = eDistrDiv ? setRules.distrDivRules : setRules.sucDivRules;
58717 expr = simplify(expr, rules); // until no more changes
58718
58719 eDistrDiv = !eDistrDiv; // Swap between Distr.Div and Succ. Div. Rules
58720
58721 s = expr.toString();
58722
58723 if (s === sBefore) {
58724 break; // No changes : end of the loop
58725 }
58726
58727 redoInic = true;
58728 sBefore = s;
58729 }
58730
58731 if (redoInic) {
58732 // Apply first rules again without succ div rules (if there are changes)
58733 expr = simplify(expr, setRules.firstRulesAgain, {}, {
58734 exactFractions: false
58735 });
58736 }
58737
58738 expr = simplify(expr, setRules.finalRules, {}, {
58739 exactFractions: false
58740 }); // Apply final rules
58741 } // NVars >= 1
58742
58743
58744 var coefficients = [];
58745 var retRationalize = {};
58746
58747 if (expr.type === 'OperatorNode' && expr.isBinary() && expr.op === '/') {
58748 // Separate numerator from denominator
58749 if (nVars === 1) {
58750 expr.args[0] = polyToCanonical(expr.args[0], coefficients);
58751 expr.args[1] = polyToCanonical(expr.args[1]);
58752 }
58753
58754 if (detailed) {
58755 retRationalize.numerator = expr.args[0];
58756 retRationalize.denominator = expr.args[1];
58757 }
58758 } else {
58759 if (nVars === 1) {
58760 expr = polyToCanonical(expr, coefficients);
58761 }
58762
58763 if (detailed) {
58764 retRationalize.numerator = expr;
58765 retRationalize.denominator = null;
58766 }
58767 } // nVars
58768
58769
58770 if (!detailed) return expr;
58771 retRationalize.coefficients = coefficients;
58772 retRationalize.variables = polyRet.variables;
58773 retRationalize.expression = expr;
58774 return retRationalize;
58775 } // ^^^^^^^ end of rationalize ^^^^^^^^
58776
58777 }); // end of typed rationalize
58778
58779 /**
58780 * Function to simplify an expression using an optional scope and
58781 * return it if the expression is a polynomial expression, i.e.
58782 * an expression with one or more variables and the operators
58783 * +, -, *, and ^, where the exponent can only be a positive integer.
58784 *
58785 * Syntax:
58786 *
58787 * polynomial(expr,scope,extended, rules)
58788 *
58789 * @param {Node | string} expr The expression to simplify and check if is polynomial expression
58790 * @param {object} scope Optional scope for expression simplification
58791 * @param {boolean} extended Optional. Default is false. When true allows divide operator.
58792 * @param {array} rules Optional. Default is no rule.
58793 *
58794 *
58795 * @return {Object}
58796 * {Object} node: node simplified expression
58797 * {Array} variables: variable names
58798 */
58799
58800 function polynomial(expr, scope, extended, rules) {
58801 var variables = [];
58802 var node = simplify(expr, rules, scope, {
58803 exactFractions: false
58804 }); // Resolves any variables and functions with all defined parameters
58805
58806 extended = !!extended;
58807 var oper = '+-*' + (extended ? '/' : '');
58808 recPoly(node);
58809 var retFunc = {};
58810 retFunc.expression = node;
58811 retFunc.variables = variables;
58812 return retFunc; // -------------------------------------------------------------------------------------------------------
58813
58814 /**
58815 * Function to simplify an expression using an optional scope and
58816 * return it if the expression is a polynomial expression, i.e.
58817 * an expression with one or more variables and the operators
58818 * +, -, *, and ^, where the exponent can only be a positive integer.
58819 *
58820 * Syntax:
58821 *
58822 * recPoly(node)
58823 *
58824 *
58825 * @param {Node} node The current sub tree expression in recursion
58826 *
58827 * @return nothing, throw an exception if error
58828 */
58829
58830 function recPoly(node) {
58831 var tp = node.type; // node type
58832
58833 if (tp === 'FunctionNode') {
58834 // No function call in polynomial expression
58835 throw new Error('There is an unsolved function call');
58836 } else if (tp === 'OperatorNode') {
58837 if (node.op === '^') {
58838 if (node.args[1].fn === 'unaryMinus') {
58839 node = node.args[0];
58840 }
58841
58842 if (node.args[1].type !== 'ConstantNode' || !Object(utils_number["i" /* isInteger */])(parseFloat(node.args[1].value))) {
58843 throw new Error('There is a non-integer exponent');
58844 } else {
58845 recPoly(node.args[0]);
58846 }
58847 } else {
58848 if (oper.indexOf(node.op) === -1) {
58849 throw new Error('Operator ' + node.op + ' invalid in polynomial expression');
58850 }
58851
58852 for (var i = 0; i < node.args.length; i++) {
58853 recPoly(node.args[i]);
58854 }
58855 } // type of operator
58856
58857 } else if (tp === 'SymbolNode') {
58858 var _name = node.name; // variable name
58859
58860 var pos = variables.indexOf(_name);
58861
58862 if (pos === -1) {
58863 // new variable in expression
58864 variables.push(_name);
58865 }
58866 } else if (tp === 'ParenthesisNode') {
58867 recPoly(node.content);
58868 } else if (tp !== 'ConstantNode') {
58869 throw new Error('type ' + tp + ' is not allowed in polynomial expression');
58870 }
58871 } // end of recPoly
58872
58873 } // end of polynomial
58874 // ---------------------------------------------------------------------------------------
58875
58876 /**
58877 * Return a rule set to rationalize an polynomial expression in rationalize
58878 *
58879 * Syntax:
58880 *
58881 * rulesRationalize()
58882 *
58883 * @return {array} rule set to rationalize an polynomial expression
58884 */
58885
58886
58887 function rulesRationalize() {
58888 var oldRules = [simplifyCore, // sCore
58889 {
58890 l: 'n+n',
58891 r: '2*n'
58892 }, {
58893 l: 'n+-n',
58894 r: '0'
58895 }, simplifyConstant, // sConstant
58896 {
58897 l: 'n*(n1^-1)',
58898 r: 'n/n1'
58899 }, {
58900 l: 'n*n1^-n2',
58901 r: 'n/n1^n2'
58902 }, {
58903 l: 'n1^-1',
58904 r: '1/n1'
58905 }, {
58906 l: 'n*(n1/n2)',
58907 r: '(n*n1)/n2'
58908 }, {
58909 l: '1*n',
58910 r: 'n'
58911 }];
58912 var rulesFirst = [{
58913 l: '(-n1)/(-n2)',
58914 r: 'n1/n2'
58915 }, // Unary division
58916 {
58917 l: '(-n1)*(-n2)',
58918 r: 'n1*n2'
58919 }, // Unary multiplication
58920 {
58921 l: 'n1--n2',
58922 r: 'n1+n2'
58923 }, // '--' elimination
58924 {
58925 l: 'n1-n2',
58926 r: 'n1+(-n2)'
58927 }, // Subtraction turn into add with un�ry minus
58928 {
58929 l: '(n1+n2)*n3',
58930 r: '(n1*n3 + n2*n3)'
58931 }, // Distributive 1
58932 {
58933 l: 'n1*(n2+n3)',
58934 r: '(n1*n2+n1*n3)'
58935 }, // Distributive 2
58936 {
58937 l: 'c1*n + c2*n',
58938 r: '(c1+c2)*n'
58939 }, // Joining constants
58940 {
58941 l: 'c1*n + n',
58942 r: '(c1+1)*n'
58943 }, // Joining constants
58944 {
58945 l: 'c1*n - c2*n',
58946 r: '(c1-c2)*n'
58947 }, // Joining constants
58948 {
58949 l: 'c1*n - n',
58950 r: '(c1-1)*n'
58951 }, // Joining constants
58952 {
58953 l: 'v/c',
58954 r: '(1/c)*v'
58955 }, // variable/constant (new!)
58956 {
58957 l: 'v/-c',
58958 r: '-(1/c)*v'
58959 }, // variable/constant (new!)
58960 {
58961 l: '-v*-c',
58962 r: 'c*v'
58963 }, // Inversion constant and variable 1
58964 {
58965 l: '-v*c',
58966 r: '-c*v'
58967 }, // Inversion constant and variable 2
58968 {
58969 l: 'v*-c',
58970 r: '-c*v'
58971 }, // Inversion constant and variable 3
58972 {
58973 l: 'v*c',
58974 r: 'c*v'
58975 }, // Inversion constant and variable 4
58976 {
58977 l: '-(-n1*n2)',
58978 r: '(n1*n2)'
58979 }, // Unary propagation
58980 {
58981 l: '-(n1*n2)',
58982 r: '(-n1*n2)'
58983 }, // Unary propagation
58984 {
58985 l: '-(-n1+n2)',
58986 r: '(n1-n2)'
58987 }, // Unary propagation
58988 {
58989 l: '-(n1+n2)',
58990 r: '(-n1-n2)'
58991 }, // Unary propagation
58992 {
58993 l: '(n1^n2)^n3',
58994 r: '(n1^(n2*n3))'
58995 }, // Power to Power
58996 {
58997 l: '-(-n1/n2)',
58998 r: '(n1/n2)'
58999 }, // Division and Unary
59000 {
59001 l: '-(n1/n2)',
59002 r: '(-n1/n2)'
59003 }]; // Divisao and Unary
59004
59005 var rulesDistrDiv = [{
59006 l: '(n1/n2 + n3/n4)',
59007 r: '((n1*n4 + n3*n2)/(n2*n4))'
59008 }, // Sum of fractions
59009 {
59010 l: '(n1/n2 + n3)',
59011 r: '((n1 + n3*n2)/n2)'
59012 }, // Sum fraction with number 1
59013 {
59014 l: '(n1 + n2/n3)',
59015 r: '((n1*n3 + n2)/n3)'
59016 }]; // Sum fraction with number 1
59017
59018 var rulesSucDiv = [{
59019 l: '(n1/(n2/n3))',
59020 r: '((n1*n3)/n2)'
59021 }, // Division simplification
59022 {
59023 l: '(n1/n2/n3)',
59024 r: '(n1/(n2*n3))'
59025 }];
59026 var setRules = {}; // rules set in 4 steps.
59027 // All rules => infinite loop
59028 // setRules.allRules =oldRules.concat(rulesFirst,rulesDistrDiv,rulesSucDiv)
59029
59030 setRules.firstRules = oldRules.concat(rulesFirst, rulesSucDiv); // First rule set
59031
59032 setRules.distrDivRules = rulesDistrDiv; // Just distr. div. rules
59033
59034 setRules.sucDivRules = rulesSucDiv; // Jus succ. div. rules
59035
59036 setRules.firstRulesAgain = oldRules.concat(rulesFirst); // Last rules set without succ. div.
59037 // Division simplification
59038 // Second rule set.
59039 // There is no aggregate expression with parentesis, but the only variable can be scattered.
59040
59041 setRules.finalRules = [simplifyCore, // simplify.rules[0]
59042 {
59043 l: 'n*-n',
59044 r: '-n^2'
59045 }, // Joining multiply with power 1
59046 {
59047 l: 'n*n',
59048 r: 'n^2'
59049 }, // Joining multiply with power 2
59050 simplifyConstant, // simplify.rules[14] old 3rd index in oldRules
59051 {
59052 l: 'n*-n^n1',
59053 r: '-n^(n1+1)'
59054 }, // Joining multiply with power 3
59055 {
59056 l: 'n*n^n1',
59057 r: 'n^(n1+1)'
59058 }, // Joining multiply with power 4
59059 {
59060 l: 'n^n1*-n^n2',
59061 r: '-n^(n1+n2)'
59062 }, // Joining multiply with power 5
59063 {
59064 l: 'n^n1*n^n2',
59065 r: 'n^(n1+n2)'
59066 }, // Joining multiply with power 6
59067 {
59068 l: 'n^n1*-n',
59069 r: '-n^(n1+1)'
59070 }, // Joining multiply with power 7
59071 {
59072 l: 'n^n1*n',
59073 r: 'n^(n1+1)'
59074 }, // Joining multiply with power 8
59075 {
59076 l: 'n^n1/-n',
59077 r: '-n^(n1-1)'
59078 }, // Joining multiply with power 8
59079 {
59080 l: 'n^n1/n',
59081 r: 'n^(n1-1)'
59082 }, // Joining division with power 1
59083 {
59084 l: 'n/-n^n1',
59085 r: '-n^(1-n1)'
59086 }, // Joining division with power 2
59087 {
59088 l: 'n/n^n1',
59089 r: 'n^(1-n1)'
59090 }, // Joining division with power 3
59091 {
59092 l: 'n^n1/-n^n2',
59093 r: 'n^(n1-n2)'
59094 }, // Joining division with power 4
59095 {
59096 l: 'n^n1/n^n2',
59097 r: 'n^(n1-n2)'
59098 }, // Joining division with power 5
59099 {
59100 l: 'n1+(-n2*n3)',
59101 r: 'n1-n2*n3'
59102 }, // Solving useless parenthesis 1
59103 {
59104 l: 'v*(-c)',
59105 r: '-c*v'
59106 }, // Solving useless unary 2
59107 {
59108 l: 'n1+-n2',
59109 r: 'n1-n2'
59110 }, // Solving +- together (new!)
59111 {
59112 l: 'v*c',
59113 r: 'c*v'
59114 }, // inversion constant with variable
59115 {
59116 l: '(n1^n2)^n3',
59117 r: '(n1^(n2*n3))'
59118 } // Power to Power
59119 ];
59120 return setRules;
59121 } // End rulesRationalize
59122 // ---------------------------------------------------------------------------------------
59123
59124 /**
59125 * Expand recursively a tree node for handling with expressions with exponents
59126 * (it's not for constants, symbols or functions with exponents)
59127 * PS: The other parameters are internal for recursion
59128 *
59129 * Syntax:
59130 *
59131 * expandPower(node)
59132 *
59133 * @param {Node} node Current expression node
59134 * @param {node} parent Parent current node inside the recursion
59135 * @param (int} Parent number of chid inside the rercursion
59136 *
59137 * @return {node} node expression with all powers expanded.
59138 */
59139
59140
59141 function expandPower(node, parent, indParent) {
59142 var tp = node.type;
59143 var internal = arguments.length > 1; // TRUE in internal calls
59144
59145 if (tp === 'OperatorNode' && node.isBinary()) {
59146 var does = false;
59147 var val;
59148
59149 if (node.op === '^') {
59150 // First operator: Parenthesis or UnaryMinus
59151 if ((node.args[0].type === 'ParenthesisNode' || node.args[0].type === 'OperatorNode') && node.args[1].type === 'ConstantNode') {
59152 // Second operator: Constant
59153 val = parseFloat(node.args[1].value);
59154 does = val >= 2 && Object(utils_number["i" /* isInteger */])(val);
59155 }
59156 }
59157
59158 if (does) {
59159 // Exponent >= 2
59160 // Before:
59161 // operator A --> Subtree
59162 // parent pow
59163 // constant
59164 //
59165 if (val > 2) {
59166 // Exponent > 2,
59167 // AFTER: (exponent > 2)
59168 // operator A --> Subtree
59169 // parent *
59170 // deep clone (operator A --> Subtree
59171 // pow
59172 // constant - 1
59173 //
59174 var nEsqTopo = node.args[0];
59175 var nDirTopo = new OperatorNode('^', 'pow', [node.args[0].cloneDeep(), new ConstantNode(val - 1)]);
59176 node = new OperatorNode('*', 'multiply', [nEsqTopo, nDirTopo]);
59177 } else {
59178 // Expo = 2 - no power
59179 // AFTER: (exponent = 2)
59180 // operator A --> Subtree
59181 // parent oper
59182 // deep clone (operator A --> Subtree)
59183 //
59184 node = new OperatorNode('*', 'multiply', [node.args[0], node.args[0].cloneDeep()]);
59185 }
59186
59187 if (internal) {
59188 // Change parent references in internal recursive calls
59189 if (indParent === 'content') {
59190 parent.content = node;
59191 } else {
59192 parent.args[indParent] = node;
59193 }
59194 }
59195 } // does
59196
59197 } // binary OperatorNode
59198
59199
59200 if (tp === 'ParenthesisNode') {
59201 // Recursion
59202 expandPower(node.content, node, 'content');
59203 } else if (tp !== 'ConstantNode' && tp !== 'SymbolNode') {
59204 for (var i = 0; i < node.args.length; i++) {
59205 expandPower(node.args[i], node, i);
59206 }
59207 }
59208
59209 if (!internal) {
59210 // return the root node
59211 return node;
59212 }
59213 } // End expandPower
59214 // ---------------------------------------------------------------------------------------
59215
59216 /**
59217 * Auxilary function for rationalize
59218 * Convert near canonical polynomial in one variable in a canonical polynomial
59219 * with one term for each exponent in decreasing order
59220 *
59221 * Syntax:
59222 *
59223 * polyToCanonical(node [, coefficients])
59224 *
59225 * @param {Node | string} expr The near canonical polynomial expression to convert in a a canonical polynomial expression
59226 *
59227 * The string or tree expression needs to be at below syntax, with free spaces:
59228 * ( (^(-)? | [+-]? )cte (*)? var (^expo)? | cte )+
59229 * Where 'var' is one variable with any valid name
59230 * 'cte' are real numeric constants with any value. It can be omitted if equal than 1
59231 * 'expo' are integers greater than 0. It can be omitted if equal than 1.
59232 *
59233 * @param {array} coefficients Optional returns coefficients sorted by increased exponent
59234 *
59235 *
59236 * @return {node} new node tree with one variable polynomial or string error.
59237 */
59238
59239
59240 function polyToCanonical(node, coefficients) {
59241 if (coefficients === undefined) {
59242 coefficients = [];
59243 } // coefficients.
59244
59245
59246 coefficients[0] = 0; // index is the exponent
59247
59248 var o = {};
59249 o.cte = 1;
59250 o.oper = '+'; // fire: mark with * or ^ when finds * or ^ down tree, reset to "" with + and -.
59251 // It is used to deduce the exponent: 1 for *, 0 for "".
59252
59253 o.fire = '';
59254 var maxExpo = 0; // maximum exponent
59255
59256 var varname = ''; // variable name
59257
59258 recurPol(node, null, o);
59259 maxExpo = coefficients.length - 1;
59260 var first = true;
59261 var no;
59262
59263 for (var i = maxExpo; i >= 0; i--) {
59264 if (coefficients[i] === 0) continue;
59265 var n1 = new ConstantNode(first ? coefficients[i] : Math.abs(coefficients[i]));
59266 var op = coefficients[i] < 0 ? '-' : '+';
59267
59268 if (i > 0) {
59269 // Is not a constant without variable
59270 var n2 = new SymbolNode(varname);
59271
59272 if (i > 1) {
59273 var n3 = new ConstantNode(i);
59274 n2 = new OperatorNode('^', 'pow', [n2, n3]);
59275 }
59276
59277 if (coefficients[i] === -1 && first) {
59278 n1 = new OperatorNode('-', 'unaryMinus', [n2]);
59279 } else if (Math.abs(coefficients[i]) === 1) {
59280 n1 = n2;
59281 } else {
59282 n1 = new OperatorNode('*', 'multiply', [n1, n2]);
59283 }
59284 }
59285
59286 if (first) {
59287 no = n1;
59288 } else if (op === '+') {
59289 no = new OperatorNode('+', 'add', [no, n1]);
59290 } else {
59291 no = new OperatorNode('-', 'subtract', [no, n1]);
59292 }
59293
59294 first = false;
59295 } // for
59296
59297
59298 if (first) {
59299 return new ConstantNode(0);
59300 } else {
59301 return no;
59302 }
59303 /**
59304 * Recursive auxilary function inside polyToCanonical for
59305 * converting expression in canonical form
59306 *
59307 * Syntax:
59308 *
59309 * recurPol(node, noPai, obj)
59310 *
59311 * @param {Node} node The current subpolynomial expression
59312 * @param {Node | Null} noPai The current parent node
59313 * @param {object} obj Object with many internal flags
59314 *
59315 * @return {} No return. If error, throws an exception
59316 */
59317
59318
59319 function recurPol(node, noPai, o) {
59320 var tp = node.type;
59321
59322 if (tp === 'FunctionNode') {
59323 // ***** FunctionName *****
59324 // No function call in polynomial expression
59325 throw new Error('There is an unsolved function call');
59326 } else if (tp === 'OperatorNode') {
59327 // ***** OperatorName *****
59328 if ('+-*^'.indexOf(node.op) === -1) throw new Error('Operator ' + node.op + ' invalid');
59329
59330 if (noPai !== null) {
59331 // -(unary),^ : children of *,+,-
59332 if ((node.fn === 'unaryMinus' || node.fn === 'pow') && noPai.fn !== 'add' && noPai.fn !== 'subtract' && noPai.fn !== 'multiply') {
59333 throw new Error('Invalid ' + node.op + ' placing');
59334 } // -,+,* : children of +,-
59335
59336
59337 if ((node.fn === 'subtract' || node.fn === 'add' || node.fn === 'multiply') && noPai.fn !== 'add' && noPai.fn !== 'subtract') {
59338 throw new Error('Invalid ' + node.op + ' placing');
59339 } // -,+ : first child
59340
59341
59342 if ((node.fn === 'subtract' || node.fn === 'add' || node.fn === 'unaryMinus') && o.noFil !== 0) {
59343 throw new Error('Invalid ' + node.op + ' placing');
59344 }
59345 } // Has parent
59346 // Firers: ^,* Old: ^,&,-(unary): firers
59347
59348
59349 if (node.op === '^' || node.op === '*') {
59350 o.fire = node.op;
59351 }
59352
59353 for (var _i = 0; _i < node.args.length; _i++) {
59354 // +,-: reset fire
59355 if (node.fn === 'unaryMinus') o.oper = '-';
59356
59357 if (node.op === '+' || node.fn === 'subtract') {
59358 o.fire = '';
59359 o.cte = 1; // default if there is no constant
59360
59361 o.oper = _i === 0 ? '+' : node.op;
59362 }
59363
59364 o.noFil = _i; // number of son
59365
59366 recurPol(node.args[_i], node, o);
59367 } // for in children
59368
59369 } else if (tp === 'SymbolNode') {
59370 // ***** SymbolName *****
59371 if (node.name !== varname && varname !== '') {
59372 throw new Error('There is more than one variable');
59373 }
59374
59375 varname = node.name;
59376
59377 if (noPai === null) {
59378 coefficients[1] = 1;
59379 return;
59380 } // ^: Symbol is First child
59381
59382
59383 if (noPai.op === '^' && o.noFil !== 0) {
59384 throw new Error('In power the variable should be the first parameter');
59385 } // *: Symbol is Second child
59386
59387
59388 if (noPai.op === '*' && o.noFil !== 1) {
59389 throw new Error('In multiply the variable should be the second parameter');
59390 } // Symbol: firers '',* => it means there is no exponent above, so it's 1 (cte * var)
59391
59392
59393 if (o.fire === '' || o.fire === '*') {
59394 if (maxExpo < 1) coefficients[1] = 0;
59395 coefficients[1] += o.cte * (o.oper === '+' ? 1 : -1);
59396 maxExpo = Math.max(1, maxExpo);
59397 }
59398 } else if (tp === 'ConstantNode') {
59399 var valor = parseFloat(node.value);
59400
59401 if (noPai === null) {
59402 coefficients[0] = valor;
59403 return;
59404 }
59405
59406 if (noPai.op === '^') {
59407 // cte: second child of power
59408 if (o.noFil !== 1) throw new Error('Constant cannot be powered');
59409
59410 if (!Object(utils_number["i" /* isInteger */])(valor) || valor <= 0) {
59411 throw new Error('Non-integer exponent is not allowed');
59412 }
59413
59414 for (var _i2 = maxExpo + 1; _i2 < valor; _i2++) {
59415 coefficients[_i2] = 0;
59416 }
59417
59418 if (valor > maxExpo) coefficients[valor] = 0;
59419 coefficients[valor] += o.cte * (o.oper === '+' ? 1 : -1);
59420 maxExpo = Math.max(valor, maxExpo);
59421 return;
59422 }
59423
59424 o.cte = valor; // Cte: firer '' => There is no exponent and no multiplication, so the exponent is 0.
59425
59426 if (o.fire === '') {
59427 coefficients[0] += o.cte * (o.oper === '+' ? 1 : -1);
59428 }
59429 } else {
59430 throw new Error('Type ' + tp + ' is not allowed');
59431 }
59432 } // End of recurPol
59433
59434 } // End of polyToCanonical
59435
59436
59437 return rationalize;
59438});
59439// CONCATENATED MODULE: ./src/json/reviver.js
59440
59441var reviver_name = 'reviver';
59442var reviver_dependencies = ['classes'];
59443var createReviver =
59444/* #__PURE__ */
59445Object(factory["a" /* factory */])(reviver_name, reviver_dependencies, function (_ref) {
59446 var classes = _ref.classes;
59447
59448 /**
59449 * Instantiate mathjs data types from their JSON representation
59450 * @param {string} key
59451 * @param {*} value
59452 * @returns {*} Returns the revived object
59453 */
59454 return function reviver(key, value) {
59455 var constructor = classes[value && value.mathjs];
59456
59457 if (constructor && typeof constructor.fromJSON === 'function') {
59458 return constructor.fromJSON(value);
59459 }
59460
59461 return value;
59462 };
59463});
59464// CONCATENATED MODULE: ./src/version.js
59465var version = '6.2.3'; // Note: This file is automatically generated when building math.js.
59466// Changes made in this file will be overwritten.
59467// CONCATENATED MODULE: ./src/plain/number/constants.js
59468var constants_pi = Math.PI;
59469var tau = 2 * Math.PI;
59470var constants_e = Math.E;
59471var constants_phi = 1.61803398874989484820458683436563811772030917980576286213545;
59472// CONCATENATED MODULE: ./src/constants.js
59473
59474
59475
59476
59477var createTrue =
59478/* #__PURE__ */
59479Object(factory["a" /* factory */])('true', [], function () {
59480 return true;
59481});
59482var createFalse =
59483/* #__PURE__ */
59484Object(factory["a" /* factory */])('false', [], function () {
59485 return false;
59486});
59487var createNull =
59488/* #__PURE__ */
59489Object(factory["a" /* factory */])('null', [], function () {
59490 return null;
59491});
59492var createInfinity =
59493/* #__PURE__ */
59494recreateFactory('Infinity', ['config', '?BigNumber'], function (_ref) {
59495 var config = _ref.config,
59496 BigNumber = _ref.BigNumber;
59497 return config.number === 'BigNumber' ? new BigNumber(Infinity) : Infinity;
59498});
59499var createNaN =
59500/* #__PURE__ */
59501recreateFactory('NaN', ['config', '?BigNumber'], function (_ref2) {
59502 var config = _ref2.config,
59503 BigNumber = _ref2.BigNumber;
59504 return config.number === 'BigNumber' ? new BigNumber(NaN) : NaN;
59505});
59506var createPi =
59507/* #__PURE__ */
59508recreateFactory('pi', ['config', '?BigNumber'], function (_ref3) {
59509 var config = _ref3.config,
59510 BigNumber = _ref3.BigNumber;
59511 return config.number === 'BigNumber' ? createBigNumberPi(BigNumber) : constants_pi;
59512});
59513var createTau =
59514/* #__PURE__ */
59515recreateFactory('tau', ['config', '?BigNumber'], function (_ref4) {
59516 var config = _ref4.config,
59517 BigNumber = _ref4.BigNumber;
59518 return config.number === 'BigNumber' ? createBigNumberTau(BigNumber) : tau;
59519});
59520var createE =
59521/* #__PURE__ */
59522recreateFactory('e', ['config', '?BigNumber'], function (_ref5) {
59523 var config = _ref5.config,
59524 BigNumber = _ref5.BigNumber;
59525 return config.number === 'BigNumber' ? createBigNumberE(BigNumber) : constants_e;
59526}); // golden ratio, (1+sqrt(5))/2
59527
59528var createPhi =
59529/* #__PURE__ */
59530recreateFactory('phi', ['config', '?BigNumber'], function (_ref6) {
59531 var config = _ref6.config,
59532 BigNumber = _ref6.BigNumber;
59533 return config.number === 'BigNumber' ? createBigNumberPhi(BigNumber) : constants_phi;
59534});
59535var createLN2 =
59536/* #__PURE__ */
59537recreateFactory('LN2', ['config', '?BigNumber'], function (_ref7) {
59538 var config = _ref7.config,
59539 BigNumber = _ref7.BigNumber;
59540 return config.number === 'BigNumber' ? new BigNumber(2).ln() : Math.LN2;
59541});
59542var createLN10 =
59543/* #__PURE__ */
59544recreateFactory('LN10', ['config', '?BigNumber'], function (_ref8) {
59545 var config = _ref8.config,
59546 BigNumber = _ref8.BigNumber;
59547 return config.number === 'BigNumber' ? new BigNumber(10).ln() : Math.LN10;
59548});
59549var createLOG2E =
59550/* #__PURE__ */
59551recreateFactory('LOG2E', ['config', '?BigNumber'], function (_ref9) {
59552 var config = _ref9.config,
59553 BigNumber = _ref9.BigNumber;
59554 return config.number === 'BigNumber' ? new BigNumber(1).div(new BigNumber(2).ln()) : Math.LOG2E;
59555});
59556var createLOG10E =
59557/* #__PURE__ */
59558recreateFactory('LOG10E', ['config', '?BigNumber'], function (_ref10) {
59559 var config = _ref10.config,
59560 BigNumber = _ref10.BigNumber;
59561 return config.number === 'BigNumber' ? new BigNumber(1).div(new BigNumber(10).ln()) : Math.LOG10E;
59562});
59563var createSQRT1_2 =
59564/* #__PURE__ */
59565recreateFactory( // eslint-disable-line camelcase
59566'SQRT1_2', ['config', '?BigNumber'], function (_ref11) {
59567 var config = _ref11.config,
59568 BigNumber = _ref11.BigNumber;
59569 return config.number === 'BigNumber' ? new BigNumber('0.5').sqrt() : Math.SQRT1_2;
59570});
59571var createSQRT2 =
59572/* #__PURE__ */
59573recreateFactory('SQRT2', ['config', '?BigNumber'], function (_ref12) {
59574 var config = _ref12.config,
59575 BigNumber = _ref12.BigNumber;
59576 return config.number === 'BigNumber' ? new BigNumber(2).sqrt() : Math.SQRT2;
59577});
59578var createI =
59579/* #__PURE__ */
59580recreateFactory('i', ['Complex'], function (_ref13) {
59581 var Complex = _ref13.Complex;
59582 return Complex.I;
59583}); // for backward compatibility with v5
59584
59585var createUppercasePi =
59586/* #__PURE__ */
59587Object(factory["a" /* factory */])('PI', ['pi'], function (_ref14) {
59588 var pi = _ref14.pi;
59589 return pi;
59590});
59591var createUppercaseE =
59592/* #__PURE__ */
59593Object(factory["a" /* factory */])('E', ['e'], function (_ref15) {
59594 var e = _ref15.e;
59595 return e;
59596});
59597var createVersion =
59598/* #__PURE__ */
59599Object(factory["a" /* factory */])('version', [], function () {
59600 return version;
59601}); // helper function to create a factory with a flag recreateOnConfigChange
59602// idea: allow passing optional properties to be attached to the factory function as 4th argument?
59603
59604function recreateFactory(name, dependencies, create) {
59605 return Object(factory["a" /* factory */])(name, dependencies, create, {
59606 recreateOnConfigChange: true
59607 });
59608}
59609// CONCATENATED MODULE: ./src/type/unit/physicalConstants.js
59610 // Source: https://en.wikipedia.org/wiki/Physical_constant
59611// Universal constants
59612
59613var createSpeedOfLight =
59614/* #__PURE__ */
59615unitFactory('speedOfLight', '299792458', 'm s^-1');
59616var createGravitationConstant =
59617/* #__PURE__ */
59618unitFactory('gravitationConstant', '6.67430e-11', 'm^3 kg^-1 s^-2');
59619var createPlanckConstant =
59620/* #__PURE__ */
59621unitFactory('planckConstant', '6.62607015e-34', 'J s');
59622var createReducedPlanckConstant =
59623/* #__PURE__ */
59624unitFactory('reducedPlanckConstant', '1.0545718176461565e-34', 'J s'); // Electromagnetic constants
59625
59626var createMagneticConstant =
59627/* #__PURE__ */
59628unitFactory('magneticConstant', '1.25663706212e-6', 'N A^-2');
59629var createElectricConstant =
59630/* #__PURE__ */
59631unitFactory('electricConstant', '8.8541878128e-12', 'F m^-1');
59632var createVacuumImpedance =
59633/* #__PURE__ */
59634unitFactory('vacuumImpedance', '376.730313667', 'ohm');
59635var createCoulomb =
59636/* #__PURE__ */
59637unitFactory('coulomb', '8.987551792261171e9', 'N m^2 C^-2');
59638var createElementaryCharge =
59639/* #__PURE__ */
59640unitFactory('elementaryCharge', '1.602176634e-19', 'C');
59641var createBohrMagneton =
59642/* #__PURE__ */
59643unitFactory('bohrMagneton', '9.2740100783e-24', 'J T^-1');
59644var createConductanceQuantum =
59645/* #__PURE__ */
59646unitFactory('conductanceQuantum', '7.748091729863649e-5', 'S');
59647var createInverseConductanceQuantum =
59648/* #__PURE__ */
59649unitFactory('inverseConductanceQuantum', '12906.403729652257', 'ohm');
59650var createMagneticFluxQuantum =
59651/* #__PURE__ */
59652unitFactory('magneticFluxQuantum', '2.0678338484619295e-15', 'Wb');
59653var createNuclearMagneton =
59654/* #__PURE__ */
59655unitFactory('nuclearMagneton', '5.0507837461e-27', 'J T^-1');
59656var createKlitzing =
59657/* #__PURE__ */
59658unitFactory('klitzing', '25812.807459304513', 'ohm');
59659var createJosephson =
59660/* #__PURE__ */
59661unitFactory('josephson', '4.835978484169836e14 Hz V', 'Hz V^-1'); // TODO: support for Hz needed
59662// Atomic and nuclear constants
59663
59664var createBohrRadius =
59665/* #__PURE__ */
59666unitFactory('bohrRadius', '5.29177210903e-11', 'm');
59667var createClassicalElectronRadius =
59668/* #__PURE__ */
59669unitFactory('classicalElectronRadius', '2.8179403262e-15', 'm');
59670var createElectronMass =
59671/* #__PURE__ */
59672unitFactory('electronMass', '9.1093837015e-31', 'kg');
59673var createFermiCoupling =
59674/* #__PURE__ */
59675unitFactory('fermiCoupling', '1.1663787e-5', 'GeV^-2');
59676var createFineStructure = numberFactory('fineStructure', 7.2973525693e-3);
59677var createHartreeEnergy =
59678/* #__PURE__ */
59679unitFactory('hartreeEnergy', '4.3597447222071e-18', 'J');
59680var createProtonMass =
59681/* #__PURE__ */
59682unitFactory('protonMass', '1.67262192369e-27', 'kg');
59683var createDeuteronMass =
59684/* #__PURE__ */
59685unitFactory('deuteronMass', '3.3435830926e-27', 'kg');
59686var createNeutronMass =
59687/* #__PURE__ */
59688unitFactory('neutronMass', '1.6749271613e-27', 'kg');
59689var createQuantumOfCirculation =
59690/* #__PURE__ */
59691unitFactory('quantumOfCirculation', '3.6369475516e-4', 'm^2 s^-1');
59692var createRydberg =
59693/* #__PURE__ */
59694unitFactory('rydberg', '10973731.568160', 'm^-1');
59695var createThomsonCrossSection =
59696/* #__PURE__ */
59697unitFactory('thomsonCrossSection', '6.6524587321e-29', 'm^2');
59698var createWeakMixingAngle = numberFactory('weakMixingAngle', 0.22290);
59699var createEfimovFactor = numberFactory('efimovFactor', 22.7); // Physico-chemical constants
59700
59701var createAtomicMass =
59702/* #__PURE__ */
59703unitFactory('atomicMass', '1.66053906660e-27', 'kg');
59704var createAvogadro =
59705/* #__PURE__ */
59706unitFactory('avogadro', '6.02214076e23', 'mol^-1');
59707var createBoltzmann =
59708/* #__PURE__ */
59709unitFactory('boltzmann', '1.380649e-23', 'J K^-1');
59710var createFaraday =
59711/* #__PURE__ */
59712unitFactory('faraday', '96485.33212331001', 'C mol^-1');
59713var createFirstRadiation =
59714/* #__PURE__ */
59715unitFactory('firstRadiation', '3.7417718521927573e-16', 'W m^2'); // export const createSpectralRadiance = /* #__PURE__ */ unitFactory('spectralRadiance', '1.1910429723971881e-16', 'W m^2 sr^-1') // TODO spectralRadiance
59716
59717var createLoschmidt =
59718/* #__PURE__ */
59719unitFactory('loschmidt', '2.686780111798444e25', 'm^-3');
59720var createGasConstant =
59721/* #__PURE__ */
59722unitFactory('gasConstant', '8.31446261815324', 'J K^-1 mol^-1');
59723var createMolarPlanckConstant =
59724/* #__PURE__ */
59725unitFactory('molarPlanckConstant', '3.990312712893431e-10', 'J s mol^-1');
59726var createMolarVolume =
59727/* #__PURE__ */
59728unitFactory('molarVolume', '0.022413969545014137', 'm^3 mol^-1');
59729var createSackurTetrode = numberFactory('sackurTetrode', -1.16487052358);
59730var createSecondRadiation =
59731/* #__PURE__ */
59732unitFactory('secondRadiation', '0.014387768775039337', 'm K');
59733var createStefanBoltzmann =
59734/* #__PURE__ */
59735unitFactory('stefanBoltzmann', '5.67037441918443e-8', 'W m^-2 K^-4');
59736var createWienDisplacement =
59737/* #__PURE__ */
59738unitFactory('wienDisplacement', '2.897771955e-3', 'm K'); // Adopted values
59739
59740var createMolarMass =
59741/* #__PURE__ */
59742unitFactory('molarMass', '0.99999999965e-3', 'kg mol^-1');
59743var createMolarMassC12 =
59744/* #__PURE__ */
59745unitFactory('molarMassC12', '11.9999999958e-3', 'kg mol^-1');
59746var createGravity =
59747/* #__PURE__ */
59748unitFactory('gravity', '9.80665', 'm s^-2'); // atm is defined in Unit.js
59749// Natural units
59750
59751var createPlanckLength =
59752/* #__PURE__ */
59753unitFactory('planckLength', '1.616255e-35', 'm');
59754var createPlanckMass =
59755/* #__PURE__ */
59756unitFactory('planckMass', '2.176435e-8', 'kg');
59757var createPlanckTime =
59758/* #__PURE__ */
59759unitFactory('planckTime', '5.391245e-44', 's');
59760var createPlanckCharge =
59761/* #__PURE__ */
59762unitFactory('planckCharge', '1.87554603778e-18', 'C');
59763var createPlanckTemperature =
59764/* #__PURE__ */
59765unitFactory('planckTemperature', '1.416785e+32', 'K'); // helper function to create a factory function which creates a physical constant,
59766// a Unit with either a number value or a BigNumber value depending on the configuration
59767
59768function unitFactory(name, valueStr, unitStr) {
59769 var dependencies = ['config', 'Unit', 'BigNumber'];
59770 return Object(factory["a" /* factory */])(name, dependencies, function (_ref) {
59771 var config = _ref.config,
59772 Unit = _ref.Unit,
59773 BigNumber = _ref.BigNumber;
59774 // Note that we can parse into number or BigNumber.
59775 // We do not parse into Fractions as that doesn't make sense: we would lose precision of the values
59776 // Therefore we dont use Unit.parse()
59777 var value = config.number === 'BigNumber' ? new BigNumber(valueStr) : parseFloat(valueStr);
59778 var unit = new Unit(value, unitStr);
59779 unit.fixPrefix = true;
59780 return unit;
59781 });
59782} // helper function to create a factory function which creates a numeric constant,
59783// either a number or BigNumber depending on the configuration
59784
59785
59786function numberFactory(name, value) {
59787 var dependencies = ['config', 'BigNumber'];
59788 return Object(factory["a" /* factory */])(name, dependencies, function (_ref2) {
59789 var config = _ref2.config,
59790 BigNumber = _ref2.BigNumber;
59791 return config.number === 'BigNumber' ? new BigNumber(value) : value;
59792 });
59793}
59794// CONCATENATED MODULE: ./src/expression/transform/apply.transform.js
59795
59796
59797
59798
59799var apply_transform_name = 'apply';
59800var apply_transform_dependencies = ['typed', 'isInteger'];
59801/**
59802 * Attach a transform function to math.apply
59803 * Adds a property transform containing the transform function.
59804 *
59805 * This transform changed the last `dim` parameter of function apply
59806 * from one-based to zero based
59807 */
59808
59809var createApplyTransform =
59810/* #__PURE__ */
59811Object(factory["a" /* factory */])(apply_transform_name, apply_transform_dependencies, function (_ref) {
59812 var typed = _ref.typed,
59813 isInteger = _ref.isInteger;
59814 var apply = createApply({
59815 typed: typed,
59816 isInteger: isInteger
59817 }); // @see: comment of concat itself
59818
59819 return typed('apply', {
59820 '...any': function any(args) {
59821 // change dim from one-based to zero-based
59822 var dim = args[1];
59823
59824 if (Object(is["y" /* isNumber */])(dim)) {
59825 args[1] = dim - 1;
59826 } else if (Object(is["e" /* isBigNumber */])(dim)) {
59827 args[1] = dim.minus(1);
59828 }
59829
59830 try {
59831 return apply.apply(null, args);
59832 } catch (err) {
59833 throw errorTransform(err);
59834 }
59835 }
59836 });
59837}, {
59838 isTransformFunction: true
59839});
59840// CONCATENATED MODULE: ./src/expression/transform/column.transform.js
59841
59842
59843
59844
59845var column_transform_name = 'column';
59846var column_transform_dependencies = ['typed', 'Index', 'matrix', 'range'];
59847/**
59848 * Attach a transform function to matrix.column
59849 * Adds a property transform containing the transform function.
59850 *
59851 * This transform changed the last `index` parameter of function column
59852 * from zero-based to one-based
59853 */
59854
59855var createColumnTransform =
59856/* #__PURE__ */
59857Object(factory["a" /* factory */])(column_transform_name, column_transform_dependencies, function (_ref) {
59858 var typed = _ref.typed,
59859 Index = _ref.Index,
59860 matrix = _ref.matrix,
59861 range = _ref.range;
59862 var column = createColumn({
59863 typed: typed,
59864 Index: Index,
59865 matrix: matrix,
59866 range: range
59867 }); // @see: comment of column itself
59868
59869 return typed('column', {
59870 '...any': function any(args) {
59871 // change last argument from zero-based to one-based
59872 var lastIndex = args.length - 1;
59873 var last = args[lastIndex];
59874
59875 if (Object(is["y" /* isNumber */])(last)) {
59876 args[lastIndex] = last - 1;
59877 }
59878
59879 try {
59880 return column.apply(null, args);
59881 } catch (err) {
59882 throw errorTransform(err);
59883 }
59884 }
59885 });
59886}, {
59887 isTransformFunction: true
59888});
59889// CONCATENATED MODULE: ./src/expression/transform/utils/compileInlineExpression.js
59890
59891/**
59892 * Compile an inline expression like "x > 0"
59893 * @param {Node} expression
59894 * @param {Object} math
59895 * @param {Object} scope
59896 * @return {function} Returns a function with one argument which fills in the
59897 * undefined variable (like "x") and evaluates the expression
59898 */
59899
59900function compileInlineExpression(expression, math, scope) {
59901 // find an undefined symbol
59902 var symbol = expression.filter(function (node) {
59903 return Object(is["J" /* isSymbolNode */])(node) && !(node.name in math) && !(node.name in scope);
59904 })[0];
59905
59906 if (!symbol) {
59907 throw new Error('No undefined variable found in inline expression "' + expression + '"');
59908 } // create a test function for this equation
59909
59910
59911 var name = symbol.name; // variable name
59912
59913 var subScope = Object.create(scope);
59914 var eq = expression.compile();
59915 return function inlineExpression(x) {
59916 subScope[name] = x;
59917 return eq.evaluate(subScope);
59918 };
59919}
59920// CONCATENATED MODULE: ./src/expression/transform/filter.transform.js
59921
59922
59923
59924
59925
59926var filter_transform_name = 'filter';
59927var filter_transform_dependencies = ['typed'];
59928var createFilterTransform =
59929/* #__PURE__ */
59930Object(factory["a" /* factory */])(filter_transform_name, filter_transform_dependencies, function (_ref) {
59931 var typed = _ref.typed;
59932
59933 /**
59934 * Attach a transform function to math.filter
59935 * Adds a property transform containing the transform function.
59936 *
59937 * This transform adds support for equations as test function for math.filter,
59938 * so you can do something like 'filter([3, -2, 5], x > 0)'.
59939 */
59940 function filterTransform(args, math, scope) {
59941 var x, callback;
59942
59943 if (args[0]) {
59944 x = args[0].compile().evaluate(scope);
59945 }
59946
59947 if (args[1]) {
59948 if (Object(is["J" /* isSymbolNode */])(args[1]) || Object(is["q" /* isFunctionAssignmentNode */])(args[1])) {
59949 // a function pointer, like filter([3, -2, 5], myTestFunction)
59950 callback = args[1].compile().evaluate(scope);
59951 } else {
59952 // an expression like filter([3, -2, 5], x > 0)
59953 callback = compileInlineExpression(args[1], math, scope);
59954 }
59955 }
59956
59957 return filter(x, callback);
59958 }
59959
59960 filterTransform.rawArgs = true; // one based version of function filter
59961
59962 var filter = typed('filter', {
59963 'Array, function': _filter,
59964 'Matrix, function': function MatrixFunction(x, test) {
59965 return x.create(_filter(x.toArray(), test));
59966 },
59967 'Array, RegExp': utils_array["d" /* filterRegExp */],
59968 'Matrix, RegExp': function MatrixRegExp(x, test) {
59969 return x.create(Object(utils_array["d" /* filterRegExp */])(x.toArray(), test));
59970 }
59971 });
59972 return filterTransform;
59973}, {
59974 isTransformFunction: true
59975});
59976/**
59977 * Filter values in a callback given a callback function
59978 *
59979 * !!! Passes a one-based index !!!
59980 *
59981 * @param {Array} x
59982 * @param {Function} callback
59983 * @return {Array} Returns the filtered array
59984 * @private
59985 */
59986
59987function _filter(x, callback) {
59988 // figure out what number of arguments the callback function expects
59989 var args = maxArgumentCount(callback);
59990 return Object(utils_array["c" /* filter */])(x, function (value, index, array) {
59991 // invoke the callback function with the right number of arguments
59992 if (args === 1) {
59993 return callback(value);
59994 } else if (args === 2) {
59995 return callback(value, [index + 1]);
59996 } else {
59997 // 3 or -1
59998 return callback(value, [index + 1], array);
59999 }
60000 });
60001}
60002// CONCATENATED MODULE: ./src/expression/transform/forEach.transform.js
60003
60004
60005
60006
60007
60008var forEach_transform_name = 'forEach';
60009var forEach_transform_dependencies = ['typed'];
60010var createForEachTransform =
60011/* #__PURE__ */
60012Object(factory["a" /* factory */])(forEach_transform_name, forEach_transform_dependencies, function (_ref) {
60013 var typed = _ref.typed;
60014
60015 /**
60016 * Attach a transform function to math.forEach
60017 * Adds a property transform containing the transform function.
60018 *
60019 * This transform creates a one-based index instead of a zero-based index
60020 */
60021 function forEachTransform(args, math, scope) {
60022 var x, callback;
60023
60024 if (args[0]) {
60025 x = args[0].compile().evaluate(scope);
60026 }
60027
60028 if (args[1]) {
60029 if (Object(is["J" /* isSymbolNode */])(args[1]) || Object(is["q" /* isFunctionAssignmentNode */])(args[1])) {
60030 // a function pointer, like forEach([3, -2, 5], myTestFunction)
60031 callback = args[1].compile().evaluate(scope);
60032 } else {
60033 // an expression like forEach([3, -2, 5], x > 0 ? callback1(x) : callback2(x) )
60034 callback = compileInlineExpression(args[1], math, scope);
60035 }
60036 }
60037
60038 return _forEach(x, callback);
60039 }
60040
60041 forEachTransform.rawArgs = true; // one-based version of forEach
60042
60043 var _forEach = typed('forEach', {
60044 'Array | Matrix, function': function ArrayMatrixFunction(array, callback) {
60045 // figure out what number of arguments the callback function expects
60046 var args = maxArgumentCount(callback);
60047
60048 var recurse = function recurse(value, index) {
60049 if (Array.isArray(value)) {
60050 Object(utils_array["f" /* forEach */])(value, function (child, i) {
60051 // we create a copy of the index array and append the new index value
60052 recurse(child, index.concat(i + 1)); // one based index, hence i+1
60053 });
60054 } else {
60055 // invoke the callback function with the right number of arguments
60056 if (args === 1) {
60057 callback(value);
60058 } else if (args === 2) {
60059 callback(value, index);
60060 } else {
60061 // 3 or -1
60062 callback(value, index, array);
60063 }
60064 }
60065 };
60066
60067 recurse(array.valueOf(), []); // pass Array
60068 }
60069 });
60070
60071 return forEachTransform;
60072}, {
60073 isTransformFunction: true
60074});
60075// CONCATENATED MODULE: ./src/expression/transform/map.transform.js
60076
60077
60078
60079
60080
60081var map_transform_name = 'map';
60082var map_transform_dependencies = ['typed'];
60083var createMapTransform =
60084/* #__PURE__ */
60085Object(factory["a" /* factory */])(map_transform_name, map_transform_dependencies, function (_ref) {
60086 var typed = _ref.typed;
60087
60088 /**
60089 * Attach a transform function to math.map
60090 * Adds a property transform containing the transform function.
60091 *
60092 * This transform creates a one-based index instead of a zero-based index
60093 */
60094 function mapTransform(args, math, scope) {
60095 var x, callback;
60096
60097 if (args[0]) {
60098 x = args[0].compile().evaluate(scope);
60099 }
60100
60101 if (args[1]) {
60102 if (Object(is["J" /* isSymbolNode */])(args[1]) || Object(is["q" /* isFunctionAssignmentNode */])(args[1])) {
60103 // a function pointer, like filter([3, -2, 5], myTestFunction)
60104 callback = args[1].compile().evaluate(scope);
60105 } else {
60106 // an expression like filter([3, -2, 5], x > 0)
60107 callback = compileInlineExpression(args[1], math, scope);
60108 }
60109 }
60110
60111 return map(x, callback);
60112 }
60113
60114 mapTransform.rawArgs = true; // one-based version of map function
60115
60116 var map = typed('map', {
60117 'Array, function': function ArrayFunction(x, callback) {
60118 return map_transform_map(x, callback, x);
60119 },
60120 'Matrix, function': function MatrixFunction(x, callback) {
60121 return x.create(map_transform_map(x.valueOf(), callback, x));
60122 }
60123 });
60124 return mapTransform;
60125}, {
60126 isTransformFunction: true
60127});
60128/**
60129 * Map for a multi dimensional array. One-based indexes
60130 * @param {Array} array
60131 * @param {function} callback
60132 * @param {Array} orig
60133 * @return {Array}
60134 * @private
60135 */
60136
60137function map_transform_map(array, callback, orig) {
60138 // figure out what number of arguments the callback function expects
60139 var argsCount = maxArgumentCount(callback);
60140
60141 function recurse(value, index) {
60142 if (Array.isArray(value)) {
60143 return Object(utils_array["m" /* map */])(value, function (child, i) {
60144 // we create a copy of the index array and append the new index value
60145 return recurse(child, index.concat(i + 1)); // one based index, hence i + 1
60146 });
60147 } else {
60148 // invoke the (typed) callback function with the right number of arguments
60149 if (argsCount === 1) {
60150 return callback(value);
60151 } else if (argsCount === 2) {
60152 return callback(value, index);
60153 } else {
60154 // 3 or -1
60155 return callback(value, index, orig);
60156 }
60157 }
60158 }
60159
60160 return recurse(array, []);
60161}
60162// CONCATENATED MODULE: ./src/expression/transform/max.transform.js
60163
60164
60165
60166
60167var max_transform_name = 'max';
60168var max_transform_dependencies = ['typed', 'larger'];
60169var createMaxTransform =
60170/* #__PURE__ */
60171Object(factory["a" /* factory */])(max_transform_name, max_transform_dependencies, function (_ref) {
60172 var typed = _ref.typed,
60173 larger = _ref.larger;
60174 var max = createMax({
60175 typed: typed,
60176 larger: larger
60177 });
60178 /**
60179 * Attach a transform function to math.max
60180 * Adds a property transform containing the transform function.
60181 *
60182 * This transform changed the last `dim` parameter of function max
60183 * from one-based to zero based
60184 */
60185
60186 return typed('max', {
60187 '...any': function any(args) {
60188 // change last argument dim from one-based to zero-based
60189 if (args.length === 2 && Object(is["i" /* isCollection */])(args[0])) {
60190 var dim = args[1];
60191
60192 if (Object(is["y" /* isNumber */])(dim)) {
60193 args[1] = dim - 1;
60194 } else if (Object(is["e" /* isBigNumber */])(dim)) {
60195 args[1] = dim.minus(1);
60196 }
60197 }
60198
60199 try {
60200 return max.apply(null, args);
60201 } catch (err) {
60202 throw errorTransform(err);
60203 }
60204 }
60205 });
60206}, {
60207 isTransformFunction: true
60208});
60209// CONCATENATED MODULE: ./src/expression/transform/mean.transform.js
60210
60211
60212
60213
60214var mean_transform_name = 'mean';
60215var mean_transform_dependencies = ['typed', 'add', 'divide'];
60216var createMeanTransform =
60217/* #__PURE__ */
60218Object(factory["a" /* factory */])(mean_transform_name, mean_transform_dependencies, function (_ref) {
60219 var typed = _ref.typed,
60220 add = _ref.add,
60221 divide = _ref.divide;
60222 var mean = createMean({
60223 typed: typed,
60224 add: add,
60225 divide: divide
60226 });
60227 /**
60228 * Attach a transform function to math.mean
60229 * Adds a property transform containing the transform function.
60230 *
60231 * This transform changed the last `dim` parameter of function mean
60232 * from one-based to zero based
60233 */
60234
60235 return typed('mean', {
60236 '...any': function any(args) {
60237 // change last argument dim from one-based to zero-based
60238 if (args.length === 2 && Object(is["i" /* isCollection */])(args[0])) {
60239 var dim = args[1];
60240
60241 if (Object(is["y" /* isNumber */])(dim)) {
60242 args[1] = dim - 1;
60243 } else if (Object(is["e" /* isBigNumber */])(dim)) {
60244 args[1] = dim.minus(1);
60245 }
60246 }
60247
60248 try {
60249 return mean.apply(null, args);
60250 } catch (err) {
60251 throw errorTransform(err);
60252 }
60253 }
60254 });
60255}, {
60256 isTransformFunction: true
60257});
60258// CONCATENATED MODULE: ./src/expression/transform/min.transform.js
60259
60260
60261
60262
60263var min_transform_name = 'min';
60264var min_transform_dependencies = ['typed', 'smaller'];
60265var createMinTransform =
60266/* #__PURE__ */
60267Object(factory["a" /* factory */])(min_transform_name, min_transform_dependencies, function (_ref) {
60268 var typed = _ref.typed,
60269 smaller = _ref.smaller;
60270 var min = createMin({
60271 typed: typed,
60272 smaller: smaller
60273 });
60274 /**
60275 * Attach a transform function to math.min
60276 * Adds a property transform containing the transform function.
60277 *
60278 * This transform changed the last `dim` parameter of function min
60279 * from one-based to zero based
60280 */
60281
60282 return typed('min', {
60283 '...any': function any(args) {
60284 // change last argument dim from one-based to zero-based
60285 if (args.length === 2 && Object(is["i" /* isCollection */])(args[0])) {
60286 var dim = args[1];
60287
60288 if (Object(is["y" /* isNumber */])(dim)) {
60289 args[1] = dim - 1;
60290 } else if (Object(is["e" /* isBigNumber */])(dim)) {
60291 args[1] = dim.minus(1);
60292 }
60293 }
60294
60295 try {
60296 return min.apply(null, args);
60297 } catch (err) {
60298 throw errorTransform(err);
60299 }
60300 }
60301 });
60302}, {
60303 isTransformFunction: true
60304});
60305// CONCATENATED MODULE: ./src/expression/transform/range.transform.js
60306
60307
60308var range_transform_name = 'range';
60309var range_transform_dependencies = ['typed', 'config', '?matrix', '?bignumber', 'smaller', 'smallerEq', 'larger', 'largerEq'];
60310var createRangeTransform =
60311/* #__PURE__ */
60312Object(factory["a" /* factory */])(range_transform_name, range_transform_dependencies, function (_ref) {
60313 var typed = _ref.typed,
60314 config = _ref.config,
60315 matrix = _ref.matrix,
60316 bignumber = _ref.bignumber,
60317 smaller = _ref.smaller,
60318 smallerEq = _ref.smallerEq,
60319 larger = _ref.larger,
60320 largerEq = _ref.largerEq;
60321 var range = range_createRange({
60322 typed: typed,
60323 config: config,
60324 matrix: matrix,
60325 bignumber: bignumber,
60326 smaller: smaller,
60327 smallerEq: smallerEq,
60328 larger: larger,
60329 largerEq: largerEq
60330 });
60331 /**
60332 * Attach a transform function to math.range
60333 * Adds a property transform containing the transform function.
60334 *
60335 * This transform creates a range which includes the end value
60336 */
60337
60338 return typed('range', {
60339 '...any': function any(args) {
60340 var lastIndex = args.length - 1;
60341 var last = args[lastIndex];
60342
60343 if (typeof last !== 'boolean') {
60344 // append a parameter includeEnd=true
60345 args.push(true);
60346 }
60347
60348 return range.apply(null, args);
60349 }
60350 });
60351}, {
60352 isTransformFunction: true
60353});
60354// CONCATENATED MODULE: ./src/expression/transform/row.transform.js
60355
60356
60357
60358
60359var row_transform_name = 'row';
60360var row_transform_dependencies = ['typed', 'Index', 'matrix', 'range'];
60361/**
60362 * Attach a transform function to matrix.column
60363 * Adds a property transform containing the transform function.
60364 *
60365 * This transform changed the last `index` parameter of function column
60366 * from zero-based to one-based
60367 */
60368
60369var createRowTransform =
60370/* #__PURE__ */
60371Object(factory["a" /* factory */])(row_transform_name, row_transform_dependencies, function (_ref) {
60372 var typed = _ref.typed,
60373 Index = _ref.Index,
60374 matrix = _ref.matrix,
60375 range = _ref.range;
60376 var row = createRow({
60377 typed: typed,
60378 Index: Index,
60379 matrix: matrix,
60380 range: range
60381 }); // @see: comment of row itself
60382
60383 return typed('row', {
60384 '...any': function any(args) {
60385 // change last argument from zero-based to one-based
60386 var lastIndex = args.length - 1;
60387 var last = args[lastIndex];
60388
60389 if (Object(is["y" /* isNumber */])(last)) {
60390 args[lastIndex] = last - 1;
60391 }
60392
60393 try {
60394 return row.apply(null, args);
60395 } catch (err) {
60396 throw errorTransform(err);
60397 }
60398 }
60399 });
60400}, {
60401 isTransformFunction: true
60402});
60403// CONCATENATED MODULE: ./src/expression/transform/subset.transform.js
60404
60405
60406
60407var subset_transform_name = 'subset';
60408var subset_transform_dependencies = ['typed', 'matrix'];
60409var createSubsetTransform =
60410/* #__PURE__ */
60411Object(factory["a" /* factory */])(subset_transform_name, subset_transform_dependencies, function (_ref) {
60412 var typed = _ref.typed,
60413 matrix = _ref.matrix;
60414 var subset = createSubset({
60415 typed: typed,
60416 matrix: matrix
60417 });
60418 /**
60419 * Attach a transform function to math.subset
60420 * Adds a property transform containing the transform function.
60421 *
60422 * This transform creates a range which includes the end value
60423 */
60424
60425 return typed('subset', {
60426 '...any': function any(args) {
60427 try {
60428 return subset.apply(null, args);
60429 } catch (err) {
60430 throw errorTransform(err);
60431 }
60432 }
60433 });
60434}, {
60435 isTransformFunction: true
60436});
60437// CONCATENATED MODULE: ./src/expression/transform/concat.transform.js
60438
60439
60440
60441
60442var concat_transform_name = 'concat';
60443var concat_transform_dependencies = ['typed', 'matrix', 'isInteger'];
60444var createConcatTransform =
60445/* #__PURE__ */
60446Object(factory["a" /* factory */])(concat_transform_name, concat_transform_dependencies, function (_ref) {
60447 var typed = _ref.typed,
60448 matrix = _ref.matrix,
60449 isInteger = _ref.isInteger;
60450 var concat = createConcat({
60451 typed: typed,
60452 matrix: matrix,
60453 isInteger: isInteger
60454 });
60455 /**
60456 * Attach a transform function to math.range
60457 * Adds a property transform containing the transform function.
60458 *
60459 * This transform changed the last `dim` parameter of function concat
60460 * from one-based to zero based
60461 */
60462
60463 return typed('concat', {
60464 '...any': function any(args) {
60465 // change last argument from one-based to zero-based
60466 var lastIndex = args.length - 1;
60467 var last = args[lastIndex];
60468
60469 if (Object(is["y" /* isNumber */])(last)) {
60470 args[lastIndex] = last - 1;
60471 } else if (Object(is["e" /* isBigNumber */])(last)) {
60472 args[lastIndex] = last.minus(1);
60473 }
60474
60475 try {
60476 return concat.apply(null, args);
60477 } catch (err) {
60478 throw errorTransform(err);
60479 }
60480 }
60481 });
60482}, {
60483 isTransformFunction: true
60484});
60485// CONCATENATED MODULE: ./src/expression/transform/std.transform.js
60486
60487
60488
60489
60490var std_transform_name = 'std';
60491var std_transform_dependencies = ['typed', 'sqrt', 'variance'];
60492/**
60493 * Attach a transform function to math.std
60494 * Adds a property transform containing the transform function.
60495 *
60496 * This transform changed the `dim` parameter of function std
60497 * from one-based to zero based
60498 */
60499
60500var createStdTransform =
60501/* #__PURE__ */
60502Object(factory["a" /* factory */])(std_transform_name, std_transform_dependencies, function (_ref) {
60503 var typed = _ref.typed,
60504 sqrt = _ref.sqrt,
60505 variance = _ref.variance;
60506 var std = createStd({
60507 typed: typed,
60508 sqrt: sqrt,
60509 variance: variance
60510 });
60511 return typed('std', {
60512 '...any': function any(args) {
60513 // change last argument dim from one-based to zero-based
60514 if (args.length >= 2 && Object(is["i" /* isCollection */])(args[0])) {
60515 var dim = args[1];
60516
60517 if (Object(is["y" /* isNumber */])(dim)) {
60518 args[1] = dim - 1;
60519 } else if (Object(is["e" /* isBigNumber */])(dim)) {
60520 args[1] = dim.minus(1);
60521 }
60522 }
60523
60524 try {
60525 return std.apply(null, args);
60526 } catch (err) {
60527 throw errorTransform(err);
60528 }
60529 }
60530 });
60531}, {
60532 isTransformFunction: true
60533});
60534// CONCATENATED MODULE: ./src/expression/transform/sum.transform.js
60535
60536
60537
60538
60539/**
60540 * Attach a transform function to math.sum
60541 * Adds a property transform containing the transform function.
60542 *
60543 * This transform changed the last `dim` parameter of function mean
60544 * from one-based to zero based
60545 */
60546
60547var sum_transform_name = 'sum';
60548var sum_transform_dependencies = ['typed', 'config', 'add', '?bignumber', '?fraction'];
60549var createSumTransform =
60550/* #__PURE__ */
60551Object(factory["a" /* factory */])(sum_transform_name, sum_transform_dependencies, function (_ref) {
60552 var typed = _ref.typed,
60553 config = _ref.config,
60554 add = _ref.add,
60555 bignumber = _ref.bignumber,
60556 fraction = _ref.fraction;
60557 var sum = createSum({
60558 typed: typed,
60559 config: config,
60560 add: add,
60561 bignumber: bignumber,
60562 fraction: fraction
60563 });
60564 return typed(sum_transform_name, {
60565 '...any': function any(args) {
60566 // change last argument dim from one-based to zero-based
60567 if (args.length === 2 && Object(is["i" /* isCollection */])(args[0])) {
60568 var dim = args[1];
60569
60570 if (Object(is["y" /* isNumber */])(dim)) {
60571 args[1] = dim - 1;
60572 } else if (Object(is["e" /* isBigNumber */])(dim)) {
60573 args[1] = dim.minus(1);
60574 }
60575 }
60576
60577 try {
60578 return sum.apply(null, args);
60579 } catch (err) {
60580 throw errorTransform(err);
60581 }
60582 }
60583 });
60584}, {
60585 isTransformFunction: true
60586});
60587// CONCATENATED MODULE: ./src/expression/transform/variance.transform.js
60588
60589
60590
60591
60592var variance_transform_name = 'variance';
60593var variance_transform_dependencies = ['typed', 'add', 'subtract', 'multiply', 'divide', 'apply', 'isNaN'];
60594/**
60595 * Attach a transform function to math.var
60596 * Adds a property transform containing the transform function.
60597 *
60598 * This transform changed the `dim` parameter of function var
60599 * from one-based to zero based
60600 */
60601
60602var createVarianceTransform =
60603/* #__PURE__ */
60604Object(factory["a" /* factory */])(variance_transform_name, variance_transform_dependencies, function (_ref) {
60605 var typed = _ref.typed,
60606 add = _ref.add,
60607 subtract = _ref.subtract,
60608 multiply = _ref.multiply,
60609 divide = _ref.divide,
60610 apply = _ref.apply,
60611 isNaN = _ref.isNaN;
60612 var variance = createVariance({
60613 typed: typed,
60614 add: add,
60615 subtract: subtract,
60616 multiply: multiply,
60617 divide: divide,
60618 apply: apply,
60619 isNaN: isNaN
60620 });
60621 return typed(variance_transform_name, {
60622 '...any': function any(args) {
60623 // change last argument dim from one-based to zero-based
60624 if (args.length >= 2 && Object(is["i" /* isCollection */])(args[0])) {
60625 var dim = args[1];
60626
60627 if (Object(is["y" /* isNumber */])(dim)) {
60628 args[1] = dim - 1;
60629 } else if (Object(is["e" /* isBigNumber */])(dim)) {
60630 args[1] = dim.minus(1);
60631 }
60632 }
60633
60634 try {
60635 return variance.apply(null, args);
60636 } catch (err) {
60637 throw errorTransform(err);
60638 }
60639 }
60640 });
60641}, {
60642 isTransformFunction: true
60643});
60644// CONCATENATED MODULE: ./src/factoriesAny.js
60645/* concated harmony reexport createTyped */__webpack_require__.d(__webpack_exports__, "createTyped", function() { return typed_createTyped; });
60646/* concated harmony reexport createResultSet */__webpack_require__.d(__webpack_exports__, "createResultSet", function() { return createResultSet; });
60647/* concated harmony reexport createBigNumberClass */__webpack_require__.d(__webpack_exports__, "createBigNumberClass", function() { return createBigNumberClass; });
60648/* concated harmony reexport createComplexClass */__webpack_require__.d(__webpack_exports__, "createComplexClass", function() { return createComplexClass; });
60649/* concated harmony reexport createFractionClass */__webpack_require__.d(__webpack_exports__, "createFractionClass", function() { return createFractionClass; });
60650/* concated harmony reexport createRangeClass */__webpack_require__.d(__webpack_exports__, "createRangeClass", function() { return createRangeClass; });
60651/* concated harmony reexport createMatrixClass */__webpack_require__.d(__webpack_exports__, "createMatrixClass", function() { return createMatrixClass; });
60652/* concated harmony reexport createDenseMatrixClass */__webpack_require__.d(__webpack_exports__, "createDenseMatrixClass", function() { return createDenseMatrixClass; });
60653/* concated harmony reexport createClone */__webpack_require__.d(__webpack_exports__, "createClone", function() { return createClone; });
60654/* concated harmony reexport createIsInteger */__webpack_require__.d(__webpack_exports__, "createIsInteger", function() { return createIsInteger; });
60655/* concated harmony reexport createIsNegative */__webpack_require__.d(__webpack_exports__, "createIsNegative", function() { return createIsNegative; });
60656/* concated harmony reexport createIsNumeric */__webpack_require__.d(__webpack_exports__, "createIsNumeric", function() { return createIsNumeric; });
60657/* concated harmony reexport createHasNumericValue */__webpack_require__.d(__webpack_exports__, "createHasNumericValue", function() { return createHasNumericValue; });
60658/* concated harmony reexport createIsPositive */__webpack_require__.d(__webpack_exports__, "createIsPositive", function() { return createIsPositive; });
60659/* concated harmony reexport createIsZero */__webpack_require__.d(__webpack_exports__, "createIsZero", function() { return createIsZero; });
60660/* concated harmony reexport createIsNaN */__webpack_require__.d(__webpack_exports__, "createIsNaN", function() { return createIsNaN; });
60661/* concated harmony reexport createTypeOf */__webpack_require__.d(__webpack_exports__, "createTypeOf", function() { return createTypeOf; });
60662/* concated harmony reexport createDeprecatedTypeof */__webpack_require__.d(__webpack_exports__, "createDeprecatedTypeof", function() { return createDeprecatedTypeof; });
60663/* concated harmony reexport createEqualScalar */__webpack_require__.d(__webpack_exports__, "createEqualScalar", function() { return createEqualScalar; });
60664/* concated harmony reexport createSparseMatrixClass */__webpack_require__.d(__webpack_exports__, "createSparseMatrixClass", function() { return createSparseMatrixClass; });
60665/* concated harmony reexport createNumber */__webpack_require__.d(__webpack_exports__, "createNumber", function() { return createNumber; });
60666/* concated harmony reexport createString */__webpack_require__.d(__webpack_exports__, "createString", function() { return createString; });
60667/* concated harmony reexport createBoolean */__webpack_require__.d(__webpack_exports__, "createBoolean", function() { return createBoolean; });
60668/* concated harmony reexport createBignumber */__webpack_require__.d(__webpack_exports__, "createBignumber", function() { return createBignumber; });
60669/* concated harmony reexport createComplex */__webpack_require__.d(__webpack_exports__, "createComplex", function() { return createComplex; });
60670/* concated harmony reexport createFraction */__webpack_require__.d(__webpack_exports__, "createFraction", function() { return createFraction; });
60671/* concated harmony reexport createMatrix */__webpack_require__.d(__webpack_exports__, "createMatrix", function() { return createMatrix; });
60672/* concated harmony reexport createSplitUnit */__webpack_require__.d(__webpack_exports__, "createSplitUnit", function() { return createSplitUnit; });
60673/* concated harmony reexport createUnaryMinus */__webpack_require__.d(__webpack_exports__, "createUnaryMinus", function() { return createUnaryMinus; });
60674/* concated harmony reexport createUnaryPlus */__webpack_require__.d(__webpack_exports__, "createUnaryPlus", function() { return createUnaryPlus; });
60675/* concated harmony reexport createAbs */__webpack_require__.d(__webpack_exports__, "createAbs", function() { return createAbs; });
60676/* concated harmony reexport createApply */__webpack_require__.d(__webpack_exports__, "createApply", function() { return createApply; });
60677/* concated harmony reexport createAddScalar */__webpack_require__.d(__webpack_exports__, "createAddScalar", function() { return createAddScalar; });
60678/* concated harmony reexport createCbrt */__webpack_require__.d(__webpack_exports__, "createCbrt", function() { return createCbrt; });
60679/* concated harmony reexport createCeil */__webpack_require__.d(__webpack_exports__, "createCeil", function() { return createCeil; });
60680/* concated harmony reexport createCube */__webpack_require__.d(__webpack_exports__, "createCube", function() { return createCube; });
60681/* concated harmony reexport createExp */__webpack_require__.d(__webpack_exports__, "createExp", function() { return createExp; });
60682/* concated harmony reexport createExpm1 */__webpack_require__.d(__webpack_exports__, "createExpm1", function() { return createExpm1; });
60683/* concated harmony reexport createFix */__webpack_require__.d(__webpack_exports__, "createFix", function() { return createFix; });
60684/* concated harmony reexport createFloor */__webpack_require__.d(__webpack_exports__, "createFloor", function() { return createFloor; });
60685/* concated harmony reexport createGcd */__webpack_require__.d(__webpack_exports__, "createGcd", function() { return createGcd; });
60686/* concated harmony reexport createLcm */__webpack_require__.d(__webpack_exports__, "createLcm", function() { return createLcm; });
60687/* concated harmony reexport createLog10 */__webpack_require__.d(__webpack_exports__, "createLog10", function() { return createLog10; });
60688/* concated harmony reexport createLog2 */__webpack_require__.d(__webpack_exports__, "createLog2", function() { return createLog2; });
60689/* concated harmony reexport createMod */__webpack_require__.d(__webpack_exports__, "createMod", function() { return createMod; });
60690/* concated harmony reexport createMultiplyScalar */__webpack_require__.d(__webpack_exports__, "createMultiplyScalar", function() { return createMultiplyScalar; });
60691/* concated harmony reexport createMultiply */__webpack_require__.d(__webpack_exports__, "createMultiply", function() { return createMultiply; });
60692/* concated harmony reexport createNthRoot */__webpack_require__.d(__webpack_exports__, "createNthRoot", function() { return createNthRoot; });
60693/* concated harmony reexport createSign */__webpack_require__.d(__webpack_exports__, "createSign", function() { return createSign; });
60694/* concated harmony reexport createSqrt */__webpack_require__.d(__webpack_exports__, "createSqrt", function() { return createSqrt; });
60695/* concated harmony reexport createSquare */__webpack_require__.d(__webpack_exports__, "createSquare", function() { return createSquare; });
60696/* concated harmony reexport createSubtract */__webpack_require__.d(__webpack_exports__, "createSubtract", function() { return createSubtract; });
60697/* concated harmony reexport createXgcd */__webpack_require__.d(__webpack_exports__, "createXgcd", function() { return createXgcd; });
60698/* concated harmony reexport createDotMultiply */__webpack_require__.d(__webpack_exports__, "createDotMultiply", function() { return createDotMultiply; });
60699/* concated harmony reexport createBitAnd */__webpack_require__.d(__webpack_exports__, "createBitAnd", function() { return createBitAnd; });
60700/* concated harmony reexport createBitNot */__webpack_require__.d(__webpack_exports__, "createBitNot", function() { return createBitNot; });
60701/* concated harmony reexport createBitOr */__webpack_require__.d(__webpack_exports__, "createBitOr", function() { return createBitOr; });
60702/* concated harmony reexport createBitXor */__webpack_require__.d(__webpack_exports__, "createBitXor", function() { return createBitXor; });
60703/* concated harmony reexport createArg */__webpack_require__.d(__webpack_exports__, "createArg", function() { return createArg; });
60704/* concated harmony reexport createConj */__webpack_require__.d(__webpack_exports__, "createConj", function() { return createConj; });
60705/* concated harmony reexport createIm */__webpack_require__.d(__webpack_exports__, "createIm", function() { return createIm; });
60706/* concated harmony reexport createRe */__webpack_require__.d(__webpack_exports__, "createRe", function() { return createRe; });
60707/* concated harmony reexport createNot */__webpack_require__.d(__webpack_exports__, "createNot", function() { return createNot; });
60708/* concated harmony reexport createOr */__webpack_require__.d(__webpack_exports__, "createOr", function() { return createOr; });
60709/* concated harmony reexport createXor */__webpack_require__.d(__webpack_exports__, "createXor", function() { return createXor; });
60710/* concated harmony reexport createConcat */__webpack_require__.d(__webpack_exports__, "createConcat", function() { return createConcat; });
60711/* concated harmony reexport createColumn */__webpack_require__.d(__webpack_exports__, "createColumn", function() { return createColumn; });
60712/* concated harmony reexport createCross */__webpack_require__.d(__webpack_exports__, "createCross", function() { return createCross; });
60713/* concated harmony reexport createDiag */__webpack_require__.d(__webpack_exports__, "createDiag", function() { return createDiag; });
60714/* concated harmony reexport createEye */__webpack_require__.d(__webpack_exports__, "createEye", function() { return createEye; });
60715/* concated harmony reexport createFilter */__webpack_require__.d(__webpack_exports__, "createFilter", function() { return createFilter; });
60716/* concated harmony reexport createFlatten */__webpack_require__.d(__webpack_exports__, "createFlatten", function() { return createFlatten; });
60717/* concated harmony reexport createForEach */__webpack_require__.d(__webpack_exports__, "createForEach", function() { return createForEach; });
60718/* concated harmony reexport createGetMatrixDataType */__webpack_require__.d(__webpack_exports__, "createGetMatrixDataType", function() { return createGetMatrixDataType; });
60719/* concated harmony reexport createIdentity */__webpack_require__.d(__webpack_exports__, "createIdentity", function() { return createIdentity; });
60720/* concated harmony reexport createKron */__webpack_require__.d(__webpack_exports__, "createKron", function() { return createKron; });
60721/* concated harmony reexport createMap */__webpack_require__.d(__webpack_exports__, "createMap", function() { return createMap; });
60722/* concated harmony reexport createOnes */__webpack_require__.d(__webpack_exports__, "createOnes", function() { return createOnes; });
60723/* concated harmony reexport createRange */__webpack_require__.d(__webpack_exports__, "createRange", function() { return range_createRange; });
60724/* concated harmony reexport createReshape */__webpack_require__.d(__webpack_exports__, "createReshape", function() { return createReshape; });
60725/* concated harmony reexport createResize */__webpack_require__.d(__webpack_exports__, "createResize", function() { return createResize; });
60726/* concated harmony reexport createRow */__webpack_require__.d(__webpack_exports__, "createRow", function() { return createRow; });
60727/* concated harmony reexport createSize */__webpack_require__.d(__webpack_exports__, "createSize", function() { return createSize; });
60728/* concated harmony reexport createSqueeze */__webpack_require__.d(__webpack_exports__, "createSqueeze", function() { return createSqueeze; });
60729/* concated harmony reexport createSubset */__webpack_require__.d(__webpack_exports__, "createSubset", function() { return createSubset; });
60730/* concated harmony reexport createTranspose */__webpack_require__.d(__webpack_exports__, "createTranspose", function() { return createTranspose; });
60731/* concated harmony reexport createCtranspose */__webpack_require__.d(__webpack_exports__, "createCtranspose", function() { return createCtranspose; });
60732/* concated harmony reexport createZeros */__webpack_require__.d(__webpack_exports__, "createZeros", function() { return createZeros; });
60733/* concated harmony reexport createErf */__webpack_require__.d(__webpack_exports__, "createErf", function() { return createErf; });
60734/* concated harmony reexport createMode */__webpack_require__.d(__webpack_exports__, "createMode", function() { return createMode; });
60735/* concated harmony reexport createProd */__webpack_require__.d(__webpack_exports__, "createProd", function() { return createProd; });
60736/* concated harmony reexport createFormat */__webpack_require__.d(__webpack_exports__, "createFormat", function() { return createFormat; });
60737/* concated harmony reexport createPrint */__webpack_require__.d(__webpack_exports__, "createPrint", function() { return createPrint; });
60738/* concated harmony reexport createTo */__webpack_require__.d(__webpack_exports__, "createTo", function() { return createTo; });
60739/* concated harmony reexport createIsPrime */__webpack_require__.d(__webpack_exports__, "createIsPrime", function() { return createIsPrime; });
60740/* concated harmony reexport createNumeric */__webpack_require__.d(__webpack_exports__, "createNumeric", function() { return createNumeric; });
60741/* concated harmony reexport createDivideScalar */__webpack_require__.d(__webpack_exports__, "createDivideScalar", function() { return createDivideScalar; });
60742/* concated harmony reexport createPow */__webpack_require__.d(__webpack_exports__, "createPow", function() { return createPow; });
60743/* concated harmony reexport createRound */__webpack_require__.d(__webpack_exports__, "createRound", function() { return createRound; });
60744/* concated harmony reexport createLog */__webpack_require__.d(__webpack_exports__, "createLog", function() { return createLog; });
60745/* concated harmony reexport createLog1p */__webpack_require__.d(__webpack_exports__, "createLog1p", function() { return createLog1p; });
60746/* concated harmony reexport createNthRoots */__webpack_require__.d(__webpack_exports__, "createNthRoots", function() { return createNthRoots; });
60747/* concated harmony reexport createDotPow */__webpack_require__.d(__webpack_exports__, "createDotPow", function() { return createDotPow; });
60748/* concated harmony reexport createDotDivide */__webpack_require__.d(__webpack_exports__, "createDotDivide", function() { return createDotDivide; });
60749/* concated harmony reexport createLsolve */__webpack_require__.d(__webpack_exports__, "createLsolve", function() { return createLsolve; });
60750/* concated harmony reexport createUsolve */__webpack_require__.d(__webpack_exports__, "createUsolve", function() { return createUsolve; });
60751/* concated harmony reexport createLeftShift */__webpack_require__.d(__webpack_exports__, "createLeftShift", function() { return createLeftShift; });
60752/* concated harmony reexport createRightArithShift */__webpack_require__.d(__webpack_exports__, "createRightArithShift", function() { return createRightArithShift; });
60753/* concated harmony reexport createRightLogShift */__webpack_require__.d(__webpack_exports__, "createRightLogShift", function() { return createRightLogShift; });
60754/* concated harmony reexport createAnd */__webpack_require__.d(__webpack_exports__, "createAnd", function() { return createAnd; });
60755/* concated harmony reexport createCompare */__webpack_require__.d(__webpack_exports__, "createCompare", function() { return createCompare; });
60756/* concated harmony reexport createCompareNatural */__webpack_require__.d(__webpack_exports__, "createCompareNatural", function() { return createCompareNatural; });
60757/* concated harmony reexport createCompareText */__webpack_require__.d(__webpack_exports__, "createCompareText", function() { return createCompareText; });
60758/* concated harmony reexport createEqual */__webpack_require__.d(__webpack_exports__, "createEqual", function() { return createEqual; });
60759/* concated harmony reexport createEqualText */__webpack_require__.d(__webpack_exports__, "createEqualText", function() { return createEqualText; });
60760/* concated harmony reexport createSmaller */__webpack_require__.d(__webpack_exports__, "createSmaller", function() { return createSmaller; });
60761/* concated harmony reexport createSmallerEq */__webpack_require__.d(__webpack_exports__, "createSmallerEq", function() { return createSmallerEq; });
60762/* concated harmony reexport createLarger */__webpack_require__.d(__webpack_exports__, "createLarger", function() { return createLarger; });
60763/* concated harmony reexport createLargerEq */__webpack_require__.d(__webpack_exports__, "createLargerEq", function() { return createLargerEq; });
60764/* concated harmony reexport createDeepEqual */__webpack_require__.d(__webpack_exports__, "createDeepEqual", function() { return createDeepEqual; });
60765/* concated harmony reexport createUnequal */__webpack_require__.d(__webpack_exports__, "createUnequal", function() { return createUnequal; });
60766/* concated harmony reexport createPartitionSelect */__webpack_require__.d(__webpack_exports__, "createPartitionSelect", function() { return createPartitionSelect; });
60767/* concated harmony reexport createSort */__webpack_require__.d(__webpack_exports__, "createSort", function() { return createSort; });
60768/* concated harmony reexport createMax */__webpack_require__.d(__webpack_exports__, "createMax", function() { return createMax; });
60769/* concated harmony reexport createMin */__webpack_require__.d(__webpack_exports__, "createMin", function() { return createMin; });
60770/* concated harmony reexport createImmutableDenseMatrixClass */__webpack_require__.d(__webpack_exports__, "createImmutableDenseMatrixClass", function() { return createImmutableDenseMatrixClass; });
60771/* concated harmony reexport createIndexClass */__webpack_require__.d(__webpack_exports__, "createIndexClass", function() { return createIndexClass; });
60772/* concated harmony reexport createFibonacciHeapClass */__webpack_require__.d(__webpack_exports__, "createFibonacciHeapClass", function() { return createFibonacciHeapClass; });
60773/* concated harmony reexport createSpaClass */__webpack_require__.d(__webpack_exports__, "createSpaClass", function() { return createSpaClass; });
60774/* concated harmony reexport createUnitClass */__webpack_require__.d(__webpack_exports__, "createUnitClass", function() { return createUnitClass; });
60775/* concated harmony reexport createUnitFunction */__webpack_require__.d(__webpack_exports__, "createUnitFunction", function() { return createUnitFunction; });
60776/* concated harmony reexport createSparse */__webpack_require__.d(__webpack_exports__, "createSparse", function() { return createSparse; });
60777/* concated harmony reexport createCreateUnit */__webpack_require__.d(__webpack_exports__, "createCreateUnit", function() { return createCreateUnit; });
60778/* concated harmony reexport createAcos */__webpack_require__.d(__webpack_exports__, "createAcos", function() { return createAcos; });
60779/* concated harmony reexport createAcosh */__webpack_require__.d(__webpack_exports__, "createAcosh", function() { return createAcosh; });
60780/* concated harmony reexport createAcot */__webpack_require__.d(__webpack_exports__, "createAcot", function() { return createAcot; });
60781/* concated harmony reexport createAcoth */__webpack_require__.d(__webpack_exports__, "createAcoth", function() { return createAcoth; });
60782/* concated harmony reexport createAcsc */__webpack_require__.d(__webpack_exports__, "createAcsc", function() { return createAcsc; });
60783/* concated harmony reexport createAcsch */__webpack_require__.d(__webpack_exports__, "createAcsch", function() { return createAcsch; });
60784/* concated harmony reexport createAsec */__webpack_require__.d(__webpack_exports__, "createAsec", function() { return createAsec; });
60785/* concated harmony reexport createAsech */__webpack_require__.d(__webpack_exports__, "createAsech", function() { return createAsech; });
60786/* concated harmony reexport createAsin */__webpack_require__.d(__webpack_exports__, "createAsin", function() { return createAsin; });
60787/* concated harmony reexport createAsinh */__webpack_require__.d(__webpack_exports__, "createAsinh", function() { return createAsinh; });
60788/* concated harmony reexport createAtan */__webpack_require__.d(__webpack_exports__, "createAtan", function() { return createAtan; });
60789/* concated harmony reexport createAtan2 */__webpack_require__.d(__webpack_exports__, "createAtan2", function() { return createAtan2; });
60790/* concated harmony reexport createAtanh */__webpack_require__.d(__webpack_exports__, "createAtanh", function() { return createAtanh; });
60791/* concated harmony reexport createCos */__webpack_require__.d(__webpack_exports__, "createCos", function() { return createCos; });
60792/* concated harmony reexport createCosh */__webpack_require__.d(__webpack_exports__, "createCosh", function() { return createCosh; });
60793/* concated harmony reexport createCot */__webpack_require__.d(__webpack_exports__, "createCot", function() { return createCot; });
60794/* concated harmony reexport createCoth */__webpack_require__.d(__webpack_exports__, "createCoth", function() { return createCoth; });
60795/* concated harmony reexport createCsc */__webpack_require__.d(__webpack_exports__, "createCsc", function() { return createCsc; });
60796/* concated harmony reexport createCsch */__webpack_require__.d(__webpack_exports__, "createCsch", function() { return createCsch; });
60797/* concated harmony reexport createSec */__webpack_require__.d(__webpack_exports__, "createSec", function() { return createSec; });
60798/* concated harmony reexport createSech */__webpack_require__.d(__webpack_exports__, "createSech", function() { return createSech; });
60799/* concated harmony reexport createSin */__webpack_require__.d(__webpack_exports__, "createSin", function() { return createSin; });
60800/* concated harmony reexport createSinh */__webpack_require__.d(__webpack_exports__, "createSinh", function() { return createSinh; });
60801/* concated harmony reexport createTan */__webpack_require__.d(__webpack_exports__, "createTan", function() { return createTan; });
60802/* concated harmony reexport createTanh */__webpack_require__.d(__webpack_exports__, "createTanh", function() { return createTanh; });
60803/* concated harmony reexport createSetCartesian */__webpack_require__.d(__webpack_exports__, "createSetCartesian", function() { return createSetCartesian; });
60804/* concated harmony reexport createSetDifference */__webpack_require__.d(__webpack_exports__, "createSetDifference", function() { return createSetDifference; });
60805/* concated harmony reexport createSetDistinct */__webpack_require__.d(__webpack_exports__, "createSetDistinct", function() { return createSetDistinct; });
60806/* concated harmony reexport createSetIntersect */__webpack_require__.d(__webpack_exports__, "createSetIntersect", function() { return createSetIntersect; });
60807/* concated harmony reexport createSetIsSubset */__webpack_require__.d(__webpack_exports__, "createSetIsSubset", function() { return createSetIsSubset; });
60808/* concated harmony reexport createSetMultiplicity */__webpack_require__.d(__webpack_exports__, "createSetMultiplicity", function() { return createSetMultiplicity; });
60809/* concated harmony reexport createSetPowerset */__webpack_require__.d(__webpack_exports__, "createSetPowerset", function() { return createSetPowerset; });
60810/* concated harmony reexport createSetSize */__webpack_require__.d(__webpack_exports__, "createSetSize", function() { return createSetSize; });
60811/* concated harmony reexport createSetSymDifference */__webpack_require__.d(__webpack_exports__, "createSetSymDifference", function() { return createSetSymDifference; });
60812/* concated harmony reexport createSetUnion */__webpack_require__.d(__webpack_exports__, "createSetUnion", function() { return createSetUnion; });
60813/* concated harmony reexport createAdd */__webpack_require__.d(__webpack_exports__, "createAdd", function() { return createAdd; });
60814/* concated harmony reexport createHypot */__webpack_require__.d(__webpack_exports__, "createHypot", function() { return createHypot; });
60815/* concated harmony reexport createNorm */__webpack_require__.d(__webpack_exports__, "createNorm", function() { return createNorm; });
60816/* concated harmony reexport createDot */__webpack_require__.d(__webpack_exports__, "createDot", function() { return createDot; });
60817/* concated harmony reexport createTrace */__webpack_require__.d(__webpack_exports__, "createTrace", function() { return createTrace; });
60818/* concated harmony reexport createIndex */__webpack_require__.d(__webpack_exports__, "createIndex", function() { return createIndex; });
60819/* concated harmony reexport createNode */__webpack_require__.d(__webpack_exports__, "createNode", function() { return createNode; });
60820/* concated harmony reexport createAccessorNode */__webpack_require__.d(__webpack_exports__, "createAccessorNode", function() { return createAccessorNode; });
60821/* concated harmony reexport createArrayNode */__webpack_require__.d(__webpack_exports__, "createArrayNode", function() { return createArrayNode; });
60822/* concated harmony reexport createAssignmentNode */__webpack_require__.d(__webpack_exports__, "createAssignmentNode", function() { return createAssignmentNode; });
60823/* concated harmony reexport createBlockNode */__webpack_require__.d(__webpack_exports__, "createBlockNode", function() { return createBlockNode; });
60824/* concated harmony reexport createConditionalNode */__webpack_require__.d(__webpack_exports__, "createConditionalNode", function() { return createConditionalNode; });
60825/* concated harmony reexport createConstantNode */__webpack_require__.d(__webpack_exports__, "createConstantNode", function() { return ConstantNode_createConstantNode; });
60826/* concated harmony reexport createFunctionAssignmentNode */__webpack_require__.d(__webpack_exports__, "createFunctionAssignmentNode", function() { return createFunctionAssignmentNode; });
60827/* concated harmony reexport createIndexNode */__webpack_require__.d(__webpack_exports__, "createIndexNode", function() { return createIndexNode; });
60828/* concated harmony reexport createObjectNode */__webpack_require__.d(__webpack_exports__, "createObjectNode", function() { return createObjectNode; });
60829/* concated harmony reexport createOperatorNode */__webpack_require__.d(__webpack_exports__, "createOperatorNode", function() { return createOperatorNode; });
60830/* concated harmony reexport createParenthesisNode */__webpack_require__.d(__webpack_exports__, "createParenthesisNode", function() { return createParenthesisNode; });
60831/* concated harmony reexport createRangeNode */__webpack_require__.d(__webpack_exports__, "createRangeNode", function() { return createRangeNode; });
60832/* concated harmony reexport createRelationalNode */__webpack_require__.d(__webpack_exports__, "createRelationalNode", function() { return createRelationalNode; });
60833/* concated harmony reexport createSymbolNode */__webpack_require__.d(__webpack_exports__, "createSymbolNode", function() { return createSymbolNode; });
60834/* concated harmony reexport createFunctionNode */__webpack_require__.d(__webpack_exports__, "createFunctionNode", function() { return createFunctionNode; });
60835/* concated harmony reexport createParse */__webpack_require__.d(__webpack_exports__, "createParse", function() { return createParse; });
60836/* concated harmony reexport createCompile */__webpack_require__.d(__webpack_exports__, "createCompile", function() { return createCompile; });
60837/* concated harmony reexport createEvaluate */__webpack_require__.d(__webpack_exports__, "createEvaluate", function() { return createEvaluate; });
60838/* concated harmony reexport createDeprecatedEval */__webpack_require__.d(__webpack_exports__, "createDeprecatedEval", function() { return createDeprecatedEval; });
60839/* concated harmony reexport createParserClass */__webpack_require__.d(__webpack_exports__, "createParserClass", function() { return createParserClass; });
60840/* concated harmony reexport createParser */__webpack_require__.d(__webpack_exports__, "createParser", function() { return createParser; });
60841/* concated harmony reexport createLup */__webpack_require__.d(__webpack_exports__, "createLup", function() { return createLup; });
60842/* concated harmony reexport createQr */__webpack_require__.d(__webpack_exports__, "createQr", function() { return createQr; });
60843/* concated harmony reexport createSlu */__webpack_require__.d(__webpack_exports__, "createSlu", function() { return createSlu; });
60844/* concated harmony reexport createLusolve */__webpack_require__.d(__webpack_exports__, "createLusolve", function() { return createLusolve; });
60845/* concated harmony reexport createHelpClass */__webpack_require__.d(__webpack_exports__, "createHelpClass", function() { return createHelpClass; });
60846/* concated harmony reexport createChainClass */__webpack_require__.d(__webpack_exports__, "createChainClass", function() { return createChainClass; });
60847/* concated harmony reexport createHelp */__webpack_require__.d(__webpack_exports__, "createHelp", function() { return createHelp; });
60848/* concated harmony reexport createChain */__webpack_require__.d(__webpack_exports__, "createChain", function() { return createChain; });
60849/* concated harmony reexport createDet */__webpack_require__.d(__webpack_exports__, "createDet", function() { return createDet; });
60850/* concated harmony reexport createInv */__webpack_require__.d(__webpack_exports__, "createInv", function() { return createInv; });
60851/* concated harmony reexport createExpm */__webpack_require__.d(__webpack_exports__, "createExpm", function() { return createExpm; });
60852/* concated harmony reexport createSqrtm */__webpack_require__.d(__webpack_exports__, "createSqrtm", function() { return createSqrtm; });
60853/* concated harmony reexport createDivide */__webpack_require__.d(__webpack_exports__, "createDivide", function() { return createDivide; });
60854/* concated harmony reexport createDistance */__webpack_require__.d(__webpack_exports__, "createDistance", function() { return createDistance; });
60855/* concated harmony reexport createIntersect */__webpack_require__.d(__webpack_exports__, "createIntersect", function() { return createIntersect; });
60856/* concated harmony reexport createSum */__webpack_require__.d(__webpack_exports__, "createSum", function() { return createSum; });
60857/* concated harmony reexport createMean */__webpack_require__.d(__webpack_exports__, "createMean", function() { return createMean; });
60858/* concated harmony reexport createMedian */__webpack_require__.d(__webpack_exports__, "createMedian", function() { return createMedian; });
60859/* concated harmony reexport createMad */__webpack_require__.d(__webpack_exports__, "createMad", function() { return createMad; });
60860/* concated harmony reexport createVariance */__webpack_require__.d(__webpack_exports__, "createVariance", function() { return createVariance; });
60861/* concated harmony reexport createDeprecatedVar */__webpack_require__.d(__webpack_exports__, "createDeprecatedVar", function() { return createDeprecatedVar; });
60862/* concated harmony reexport createQuantileSeq */__webpack_require__.d(__webpack_exports__, "createQuantileSeq", function() { return createQuantileSeq; });
60863/* concated harmony reexport createStd */__webpack_require__.d(__webpack_exports__, "createStd", function() { return createStd; });
60864/* concated harmony reexport createCombinations */__webpack_require__.d(__webpack_exports__, "createCombinations", function() { return createCombinations; });
60865/* concated harmony reexport createCombinationsWithRep */__webpack_require__.d(__webpack_exports__, "createCombinationsWithRep", function() { return createCombinationsWithRep; });
60866/* concated harmony reexport createGamma */__webpack_require__.d(__webpack_exports__, "createGamma", function() { return createGamma; });
60867/* concated harmony reexport createFactorial */__webpack_require__.d(__webpack_exports__, "createFactorial", function() { return createFactorial; });
60868/* concated harmony reexport createKldivergence */__webpack_require__.d(__webpack_exports__, "createKldivergence", function() { return createKldivergence; });
60869/* concated harmony reexport createMultinomial */__webpack_require__.d(__webpack_exports__, "createMultinomial", function() { return createMultinomial; });
60870/* concated harmony reexport createPermutations */__webpack_require__.d(__webpack_exports__, "createPermutations", function() { return createPermutations; });
60871/* concated harmony reexport createPickRandom */__webpack_require__.d(__webpack_exports__, "createPickRandom", function() { return createPickRandom; });
60872/* concated harmony reexport createRandom */__webpack_require__.d(__webpack_exports__, "createRandom", function() { return createRandom; });
60873/* concated harmony reexport createRandomInt */__webpack_require__.d(__webpack_exports__, "createRandomInt", function() { return createRandomInt; });
60874/* concated harmony reexport createStirlingS2 */__webpack_require__.d(__webpack_exports__, "createStirlingS2", function() { return createStirlingS2; });
60875/* concated harmony reexport createBellNumbers */__webpack_require__.d(__webpack_exports__, "createBellNumbers", function() { return createBellNumbers; });
60876/* concated harmony reexport createCatalan */__webpack_require__.d(__webpack_exports__, "createCatalan", function() { return createCatalan; });
60877/* concated harmony reexport createComposition */__webpack_require__.d(__webpack_exports__, "createComposition", function() { return createComposition; });
60878/* concated harmony reexport createSimplify */__webpack_require__.d(__webpack_exports__, "createSimplify", function() { return createSimplify; });
60879/* concated harmony reexport createDerivative */__webpack_require__.d(__webpack_exports__, "createDerivative", function() { return createDerivative; });
60880/* concated harmony reexport createRationalize */__webpack_require__.d(__webpack_exports__, "createRationalize", function() { return createRationalize; });
60881/* concated harmony reexport createReviver */__webpack_require__.d(__webpack_exports__, "createReviver", function() { return createReviver; });
60882/* concated harmony reexport createE */__webpack_require__.d(__webpack_exports__, "createE", function() { return createE; });
60883/* concated harmony reexport createUppercaseE */__webpack_require__.d(__webpack_exports__, "createUppercaseE", function() { return createUppercaseE; });
60884/* concated harmony reexport createFalse */__webpack_require__.d(__webpack_exports__, "createFalse", function() { return createFalse; });
60885/* concated harmony reexport createI */__webpack_require__.d(__webpack_exports__, "createI", function() { return createI; });
60886/* concated harmony reexport createInfinity */__webpack_require__.d(__webpack_exports__, "createInfinity", function() { return createInfinity; });
60887/* concated harmony reexport createLN10 */__webpack_require__.d(__webpack_exports__, "createLN10", function() { return createLN10; });
60888/* concated harmony reexport createLN2 */__webpack_require__.d(__webpack_exports__, "createLN2", function() { return createLN2; });
60889/* concated harmony reexport createLOG10E */__webpack_require__.d(__webpack_exports__, "createLOG10E", function() { return createLOG10E; });
60890/* concated harmony reexport createLOG2E */__webpack_require__.d(__webpack_exports__, "createLOG2E", function() { return createLOG2E; });
60891/* concated harmony reexport createNaN */__webpack_require__.d(__webpack_exports__, "createNaN", function() { return createNaN; });
60892/* concated harmony reexport createNull */__webpack_require__.d(__webpack_exports__, "createNull", function() { return createNull; });
60893/* concated harmony reexport createPhi */__webpack_require__.d(__webpack_exports__, "createPhi", function() { return createPhi; });
60894/* concated harmony reexport createPi */__webpack_require__.d(__webpack_exports__, "createPi", function() { return createPi; });
60895/* concated harmony reexport createUppercasePi */__webpack_require__.d(__webpack_exports__, "createUppercasePi", function() { return createUppercasePi; });
60896/* concated harmony reexport createSQRT1_2 */__webpack_require__.d(__webpack_exports__, "createSQRT1_2", function() { return createSQRT1_2; });
60897/* concated harmony reexport createSQRT2 */__webpack_require__.d(__webpack_exports__, "createSQRT2", function() { return createSQRT2; });
60898/* concated harmony reexport createTau */__webpack_require__.d(__webpack_exports__, "createTau", function() { return createTau; });
60899/* concated harmony reexport createTrue */__webpack_require__.d(__webpack_exports__, "createTrue", function() { return createTrue; });
60900/* concated harmony reexport createVersion */__webpack_require__.d(__webpack_exports__, "createVersion", function() { return createVersion; });
60901/* concated harmony reexport createAtomicMass */__webpack_require__.d(__webpack_exports__, "createAtomicMass", function() { return createAtomicMass; });
60902/* concated harmony reexport createAvogadro */__webpack_require__.d(__webpack_exports__, "createAvogadro", function() { return createAvogadro; });
60903/* concated harmony reexport createBohrMagneton */__webpack_require__.d(__webpack_exports__, "createBohrMagneton", function() { return createBohrMagneton; });
60904/* concated harmony reexport createBohrRadius */__webpack_require__.d(__webpack_exports__, "createBohrRadius", function() { return createBohrRadius; });
60905/* concated harmony reexport createBoltzmann */__webpack_require__.d(__webpack_exports__, "createBoltzmann", function() { return createBoltzmann; });
60906/* concated harmony reexport createClassicalElectronRadius */__webpack_require__.d(__webpack_exports__, "createClassicalElectronRadius", function() { return createClassicalElectronRadius; });
60907/* concated harmony reexport createConductanceQuantum */__webpack_require__.d(__webpack_exports__, "createConductanceQuantum", function() { return createConductanceQuantum; });
60908/* concated harmony reexport createCoulomb */__webpack_require__.d(__webpack_exports__, "createCoulomb", function() { return createCoulomb; });
60909/* concated harmony reexport createDeuteronMass */__webpack_require__.d(__webpack_exports__, "createDeuteronMass", function() { return createDeuteronMass; });
60910/* concated harmony reexport createEfimovFactor */__webpack_require__.d(__webpack_exports__, "createEfimovFactor", function() { return createEfimovFactor; });
60911/* concated harmony reexport createElectricConstant */__webpack_require__.d(__webpack_exports__, "createElectricConstant", function() { return createElectricConstant; });
60912/* concated harmony reexport createElectronMass */__webpack_require__.d(__webpack_exports__, "createElectronMass", function() { return createElectronMass; });
60913/* concated harmony reexport createElementaryCharge */__webpack_require__.d(__webpack_exports__, "createElementaryCharge", function() { return createElementaryCharge; });
60914/* concated harmony reexport createFaraday */__webpack_require__.d(__webpack_exports__, "createFaraday", function() { return createFaraday; });
60915/* concated harmony reexport createFermiCoupling */__webpack_require__.d(__webpack_exports__, "createFermiCoupling", function() { return createFermiCoupling; });
60916/* concated harmony reexport createFineStructure */__webpack_require__.d(__webpack_exports__, "createFineStructure", function() { return createFineStructure; });
60917/* concated harmony reexport createFirstRadiation */__webpack_require__.d(__webpack_exports__, "createFirstRadiation", function() { return createFirstRadiation; });
60918/* concated harmony reexport createGasConstant */__webpack_require__.d(__webpack_exports__, "createGasConstant", function() { return createGasConstant; });
60919/* concated harmony reexport createGravitationConstant */__webpack_require__.d(__webpack_exports__, "createGravitationConstant", function() { return createGravitationConstant; });
60920/* concated harmony reexport createGravity */__webpack_require__.d(__webpack_exports__, "createGravity", function() { return createGravity; });
60921/* concated harmony reexport createHartreeEnergy */__webpack_require__.d(__webpack_exports__, "createHartreeEnergy", function() { return createHartreeEnergy; });
60922/* concated harmony reexport createInverseConductanceQuantum */__webpack_require__.d(__webpack_exports__, "createInverseConductanceQuantum", function() { return createInverseConductanceQuantum; });
60923/* concated harmony reexport createKlitzing */__webpack_require__.d(__webpack_exports__, "createKlitzing", function() { return createKlitzing; });
60924/* concated harmony reexport createLoschmidt */__webpack_require__.d(__webpack_exports__, "createLoschmidt", function() { return createLoschmidt; });
60925/* concated harmony reexport createMagneticConstant */__webpack_require__.d(__webpack_exports__, "createMagneticConstant", function() { return createMagneticConstant; });
60926/* concated harmony reexport createMagneticFluxQuantum */__webpack_require__.d(__webpack_exports__, "createMagneticFluxQuantum", function() { return createMagneticFluxQuantum; });
60927/* concated harmony reexport createMolarMass */__webpack_require__.d(__webpack_exports__, "createMolarMass", function() { return createMolarMass; });
60928/* concated harmony reexport createMolarMassC12 */__webpack_require__.d(__webpack_exports__, "createMolarMassC12", function() { return createMolarMassC12; });
60929/* concated harmony reexport createMolarPlanckConstant */__webpack_require__.d(__webpack_exports__, "createMolarPlanckConstant", function() { return createMolarPlanckConstant; });
60930/* concated harmony reexport createMolarVolume */__webpack_require__.d(__webpack_exports__, "createMolarVolume", function() { return createMolarVolume; });
60931/* concated harmony reexport createNeutronMass */__webpack_require__.d(__webpack_exports__, "createNeutronMass", function() { return createNeutronMass; });
60932/* concated harmony reexport createNuclearMagneton */__webpack_require__.d(__webpack_exports__, "createNuclearMagneton", function() { return createNuclearMagneton; });
60933/* concated harmony reexport createPlanckCharge */__webpack_require__.d(__webpack_exports__, "createPlanckCharge", function() { return createPlanckCharge; });
60934/* concated harmony reexport createPlanckConstant */__webpack_require__.d(__webpack_exports__, "createPlanckConstant", function() { return createPlanckConstant; });
60935/* concated harmony reexport createPlanckLength */__webpack_require__.d(__webpack_exports__, "createPlanckLength", function() { return createPlanckLength; });
60936/* concated harmony reexport createPlanckMass */__webpack_require__.d(__webpack_exports__, "createPlanckMass", function() { return createPlanckMass; });
60937/* concated harmony reexport createPlanckTemperature */__webpack_require__.d(__webpack_exports__, "createPlanckTemperature", function() { return createPlanckTemperature; });
60938/* concated harmony reexport createPlanckTime */__webpack_require__.d(__webpack_exports__, "createPlanckTime", function() { return createPlanckTime; });
60939/* concated harmony reexport createProtonMass */__webpack_require__.d(__webpack_exports__, "createProtonMass", function() { return createProtonMass; });
60940/* concated harmony reexport createQuantumOfCirculation */__webpack_require__.d(__webpack_exports__, "createQuantumOfCirculation", function() { return createQuantumOfCirculation; });
60941/* concated harmony reexport createReducedPlanckConstant */__webpack_require__.d(__webpack_exports__, "createReducedPlanckConstant", function() { return createReducedPlanckConstant; });
60942/* concated harmony reexport createRydberg */__webpack_require__.d(__webpack_exports__, "createRydberg", function() { return createRydberg; });
60943/* concated harmony reexport createSackurTetrode */__webpack_require__.d(__webpack_exports__, "createSackurTetrode", function() { return createSackurTetrode; });
60944/* concated harmony reexport createSecondRadiation */__webpack_require__.d(__webpack_exports__, "createSecondRadiation", function() { return createSecondRadiation; });
60945/* concated harmony reexport createSpeedOfLight */__webpack_require__.d(__webpack_exports__, "createSpeedOfLight", function() { return createSpeedOfLight; });
60946/* concated harmony reexport createStefanBoltzmann */__webpack_require__.d(__webpack_exports__, "createStefanBoltzmann", function() { return createStefanBoltzmann; });
60947/* concated harmony reexport createThomsonCrossSection */__webpack_require__.d(__webpack_exports__, "createThomsonCrossSection", function() { return createThomsonCrossSection; });
60948/* concated harmony reexport createVacuumImpedance */__webpack_require__.d(__webpack_exports__, "createVacuumImpedance", function() { return createVacuumImpedance; });
60949/* concated harmony reexport createWeakMixingAngle */__webpack_require__.d(__webpack_exports__, "createWeakMixingAngle", function() { return createWeakMixingAngle; });
60950/* concated harmony reexport createWienDisplacement */__webpack_require__.d(__webpack_exports__, "createWienDisplacement", function() { return createWienDisplacement; });
60951/* concated harmony reexport createApplyTransform */__webpack_require__.d(__webpack_exports__, "createApplyTransform", function() { return createApplyTransform; });
60952/* concated harmony reexport createColumnTransform */__webpack_require__.d(__webpack_exports__, "createColumnTransform", function() { return createColumnTransform; });
60953/* concated harmony reexport createFilterTransform */__webpack_require__.d(__webpack_exports__, "createFilterTransform", function() { return createFilterTransform; });
60954/* concated harmony reexport createForEachTransform */__webpack_require__.d(__webpack_exports__, "createForEachTransform", function() { return createForEachTransform; });
60955/* concated harmony reexport createIndexTransform */__webpack_require__.d(__webpack_exports__, "createIndexTransform", function() { return createIndexTransform; });
60956/* concated harmony reexport createMapTransform */__webpack_require__.d(__webpack_exports__, "createMapTransform", function() { return createMapTransform; });
60957/* concated harmony reexport createMaxTransform */__webpack_require__.d(__webpack_exports__, "createMaxTransform", function() { return createMaxTransform; });
60958/* concated harmony reexport createMeanTransform */__webpack_require__.d(__webpack_exports__, "createMeanTransform", function() { return createMeanTransform; });
60959/* concated harmony reexport createMinTransform */__webpack_require__.d(__webpack_exports__, "createMinTransform", function() { return createMinTransform; });
60960/* concated harmony reexport createRangeTransform */__webpack_require__.d(__webpack_exports__, "createRangeTransform", function() { return createRangeTransform; });
60961/* concated harmony reexport createRowTransform */__webpack_require__.d(__webpack_exports__, "createRowTransform", function() { return createRowTransform; });
60962/* concated harmony reexport createSubsetTransform */__webpack_require__.d(__webpack_exports__, "createSubsetTransform", function() { return createSubsetTransform; });
60963/* concated harmony reexport createConcatTransform */__webpack_require__.d(__webpack_exports__, "createConcatTransform", function() { return createConcatTransform; });
60964/* concated harmony reexport createStdTransform */__webpack_require__.d(__webpack_exports__, "createStdTransform", function() { return createStdTransform; });
60965/* concated harmony reexport createSumTransform */__webpack_require__.d(__webpack_exports__, "createSumTransform", function() { return createSumTransform; });
60966/* concated harmony reexport createVarianceTransform */__webpack_require__.d(__webpack_exports__, "createVarianceTransform", function() { return createVarianceTransform; });
60967
60968
60969
60970
60971
60972
60973
60974
60975
60976
60977
60978
60979
60980
60981
60982
60983
60984
60985
60986
60987
60988
60989
60990
60991
60992
60993
60994
60995
60996
60997
60998
60999
61000
61001
61002
61003
61004
61005
61006
61007
61008
61009
61010
61011
61012
61013
61014
61015
61016
61017
61018
61019
61020
61021
61022
61023
61024
61025
61026
61027
61028
61029
61030
61031
61032
61033
61034
61035
61036
61037
61038
61039
61040
61041
61042
61043
61044
61045
61046
61047
61048
61049
61050
61051
61052
61053
61054
61055
61056
61057
61058
61059
61060
61061
61062
61063
61064
61065
61066
61067
61068
61069
61070
61071
61072
61073
61074
61075
61076
61077
61078
61079
61080
61081
61082
61083
61084
61085
61086
61087
61088
61089
61090
61091
61092
61093
61094
61095
61096
61097
61098
61099
61100
61101
61102
61103
61104
61105
61106
61107
61108
61109
61110
61111
61112
61113
61114
61115
61116
61117
61118
61119
61120
61121
61122
61123
61124
61125
61126
61127
61128
61129
61130
61131
61132
61133
61134
61135
61136
61137
61138
61139
61140
61141
61142
61143
61144
61145
61146
61147
61148
61149
61150
61151
61152
61153
61154
61155
61156
61157
61158
61159
61160
61161
61162
61163
61164
61165
61166
61167
61168
61169
61170
61171
61172
61173
61174
61175
61176
61177
61178
61179
61180
61181
61182
61183
61184
61185
61186
61187
61188
61189
61190
61191
61192
61193
61194
61195
61196
61197
61198
61199
61200
61201
61202
61203
61204
61205
61206
61207
61208
61209
61210
61211
61212
61213
61214
61215
61216
61217
61218
61219
61220
61221/***/ }),
61222/* 22 */
61223/***/ (function(module, __webpack_exports__, __webpack_require__) {
61224
61225"use strict";
61226__webpack_require__.r(__webpack_exports__);
61227
61228// EXTERNAL MODULE: ./src/utils/object.js
61229var utils_object = __webpack_require__(3);
61230
61231// EXTERNAL MODULE: ./node_modules/tiny-emitter/index.js
61232var tiny_emitter = __webpack_require__(18);
61233var tiny_emitter_default = /*#__PURE__*/__webpack_require__.n(tiny_emitter);
61234
61235// CONCATENATED MODULE: ./src/utils/emitter.js
61236
61237/**
61238 * Extend given object with emitter functions `on`, `off`, `once`, `emit`
61239 * @param {Object} obj
61240 * @return {Object} obj
61241 */
61242
61243function mixin(obj) {
61244 // create event emitter
61245 var emitter = new tiny_emitter_default.a(); // bind methods to obj (we don't want to expose the emitter.e Array...)
61246
61247 obj.on = emitter.on.bind(emitter);
61248 obj.off = emitter.off.bind(emitter);
61249 obj.once = emitter.once.bind(emitter);
61250 obj.emit = emitter.emit.bind(emitter);
61251 return obj;
61252}
61253// EXTERNAL MODULE: ./src/utils/is.js
61254var is = __webpack_require__(1);
61255
61256// EXTERNAL MODULE: ./src/utils/factory.js
61257var utils_factory = __webpack_require__(0);
61258
61259// EXTERNAL MODULE: ./src/utils/array.js
61260var array = __webpack_require__(2);
61261
61262// EXTERNAL MODULE: ./src/error/ArgumentsError.js
61263var ArgumentsError = __webpack_require__(13);
61264
61265// EXTERNAL MODULE: ./src/utils/log.js
61266var log = __webpack_require__(8);
61267
61268// CONCATENATED MODULE: ./src/core/function/import.js
61269function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
61270
61271function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
61272
61273
61274
61275
61276
61277
61278
61279function importFactory(typed, load, math, importedFactories) {
61280 /**
61281 * Import functions from an object or a module.
61282 *
61283 * This function is only available on a mathjs instance created using `create`.
61284 *
61285 * Syntax:
61286 *
61287 * math.import(functions)
61288 * math.import(functions, options)
61289 *
61290 * Where:
61291 *
61292 * - `functions: Object`
61293 * An object with functions or factories to be imported.
61294 * - `options: Object` An object with import options. Available options:
61295 * - `override: boolean`
61296 * If true, existing functions will be overwritten. False by default.
61297 * - `silent: boolean`
61298 * If true, the function will not throw errors on duplicates or invalid
61299 * types. False by default.
61300 * - `wrap: boolean`
61301 * If true, the functions will be wrapped in a wrapper function
61302 * which converts data types like Matrix to primitive data types like Array.
61303 * The wrapper is needed when extending math.js with libraries which do not
61304 * support these data type. False by default.
61305 *
61306 * Examples:
61307 *
61308 * import { create, all } from 'mathjs'
61309 * import * as numbers from 'numbers'
61310 *
61311 * // create a mathjs instance
61312 * const math = create(all)
61313 *
61314 * // define new functions and variables
61315 * math.import({
61316 * myvalue: 42,
61317 * hello: function (name) {
61318 * return 'hello, ' + name + '!'
61319 * }
61320 * })
61321 *
61322 * // use the imported function and variable
61323 * math.myvalue * 2 // 84
61324 * math.hello('user') // 'hello, user!'
61325 *
61326 * // import the npm module 'numbers'
61327 * // (must be installed first with `npm install numbers`)
61328 * math.import(numbers, {wrap: true})
61329 *
61330 * math.fibonacci(7) // returns 13
61331 *
61332 * @param {Object | Array} functions Object with functions to be imported.
61333 * @param {Object} [options] Import options.
61334 */
61335 function mathImport(functions, options) {
61336 var num = arguments.length;
61337
61338 if (num !== 1 && num !== 2) {
61339 throw new ArgumentsError["a" /* ArgumentsError */]('import', num, 1, 2);
61340 }
61341
61342 if (!options) {
61343 options = {};
61344 }
61345
61346 function flattenImports(flatValues, value, name) {
61347 if (Object(utils_object["g" /* isLegacyFactory */])(value)) {
61348 // legacy factories don't always have a name,
61349 // let's not handle them via the new flatValues
61350 _importLegacyFactory(value, options);
61351 } else if (Array.isArray(value)) {
61352 value.forEach(function (item) {
61353 return flattenImports(flatValues, item);
61354 });
61355 } else if (_typeof(value) === 'object') {
61356 for (var _name in value) {
61357 if (Object(utils_object["f" /* hasOwnProperty */])(value, _name)) {
61358 flattenImports(flatValues, value[_name], _name);
61359 }
61360 }
61361 } else if (Object(utils_factory["b" /* isFactory */])(value) || name !== undefined) {
61362 var flatName = Object(utils_factory["b" /* isFactory */])(value) ? isTransformFunctionFactory(value) ? value.fn + '.transform' : // TODO: this is ugly
61363 value.fn : name; // we allow importing the same function twice if it points to the same implementation
61364
61365 if (Object(utils_object["f" /* hasOwnProperty */])(flatValues, flatName) && flatValues[flatName] !== value && !options.silent) {
61366 throw new Error('Cannot import "' + flatName + '" twice');
61367 }
61368
61369 flatValues[flatName] = value;
61370 } else {
61371 if (!options.silent) {
61372 throw new TypeError('Factory, Object, or Array expected');
61373 }
61374 }
61375 }
61376
61377 var flatValues = {};
61378 flattenImports(flatValues, functions);
61379
61380 for (var name in flatValues) {
61381 if (Object(utils_object["f" /* hasOwnProperty */])(flatValues, name)) {
61382 // console.log('import', name)
61383 var value = flatValues[name];
61384
61385 if (Object(utils_factory["b" /* isFactory */])(value)) {
61386 // we ignore name here and enforce the name of the factory
61387 // maybe at some point we do want to allow overriding it
61388 // in that case we can implement an option overrideFactoryNames: true
61389 _importFactory(value, options);
61390 } else if (isSupportedType(value)) {
61391 _import(name, value, options);
61392 } else {
61393 if (!options.silent) {
61394 throw new TypeError('Factory, Object, or Array expected');
61395 }
61396 }
61397 }
61398 }
61399 }
61400 /**
61401 * Add a property to the math namespace
61402 * @param {string} name
61403 * @param {*} value
61404 * @param {Object} options See import for a description of the options
61405 * @private
61406 */
61407
61408
61409 function _import(name, value, options) {
61410 // TODO: refactor this function, it's to complicated and contains duplicate code
61411 if (options.wrap && typeof value === 'function') {
61412 // create a wrapper around the function
61413 value = _wrap(value);
61414 } // turn a plain function with a typed-function signature into a typed-function
61415
61416
61417 if (hasTypedFunctionSignature(value)) {
61418 value = typed(name, _defineProperty({}, value.signature, value));
61419 }
61420
61421 if (isTypedFunction(math[name]) && isTypedFunction(value)) {
61422 if (options.override) {
61423 // give the typed function the right name
61424 value = typed(name, value.signatures);
61425 } else {
61426 // merge the existing and typed function
61427 value = typed(math[name], value);
61428 }
61429
61430 math[name] = value;
61431 delete importedFactories[name];
61432
61433 _importTransform(name, value);
61434
61435 math.emit('import', name, function resolver() {
61436 return value;
61437 });
61438 return;
61439 }
61440
61441 if (math[name] === undefined || options.override) {
61442 math[name] = value;
61443 delete importedFactories[name];
61444
61445 _importTransform(name, value);
61446
61447 math.emit('import', name, function resolver() {
61448 return value;
61449 });
61450 return;
61451 }
61452
61453 if (!options.silent) {
61454 throw new Error('Cannot import "' + name + '": already exists');
61455 }
61456 }
61457
61458 function _importTransform(name, value) {
61459 if (value && typeof value.transform === 'function') {
61460 math.expression.transform[name] = value.transform;
61461
61462 if (allowedInExpressions(name)) {
61463 math.expression.mathWithTransform[name] = value.transform;
61464 }
61465 } else {
61466 // remove existing transform
61467 delete math.expression.transform[name];
61468
61469 if (allowedInExpressions(name)) {
61470 math.expression.mathWithTransform[name] = value;
61471 }
61472 }
61473 }
61474
61475 function _deleteTransform(name) {
61476 delete math.expression.transform[name];
61477
61478 if (allowedInExpressions(name)) {
61479 math.expression.mathWithTransform[name] = math[name];
61480 } else {
61481 delete math.expression.mathWithTransform[name];
61482 }
61483 }
61484 /**
61485 * Create a wrapper a round an function which converts the arguments
61486 * to their primitive values (like convert a Matrix to Array)
61487 * @param {Function} fn
61488 * @return {Function} Returns the wrapped function
61489 * @private
61490 */
61491
61492
61493 function _wrap(fn) {
61494 var wrapper = function wrapper() {
61495 var args = [];
61496
61497 for (var i = 0, len = arguments.length; i < len; i++) {
61498 var arg = arguments[i];
61499 args[i] = arg && arg.valueOf();
61500 }
61501
61502 return fn.apply(math, args);
61503 };
61504
61505 if (fn.transform) {
61506 wrapper.transform = fn.transform;
61507 }
61508
61509 return wrapper;
61510 }
61511 /**
61512 * Import an instance of a factory into math.js
61513 * @param {{factory: Function, name: string, path: string, math: boolean}} factory
61514 * @param {Object} options See import for a description of the options
61515 * @private
61516 */
61517 // TODO: _importLegacyFactory is deprecated since v6.0.0, clean up some day
61518
61519
61520 function _importLegacyFactory(factory, options) {
61521 Object(log["a" /* warnOnce */])('Factories of type { name, factory } are deprecated since v6. ' + 'Please create your factory functions using the math.factory function.');
61522
61523 if (typeof factory.name === 'string') {
61524 var name = factory.name;
61525 var existingTransform = name in math.expression.transform;
61526 var namespace = factory.path ? Object(utils_object["k" /* traverse */])(math, factory.path) : math;
61527 var existing = Object(utils_object["f" /* hasOwnProperty */])(namespace, name) ? namespace[name] : undefined;
61528
61529 var resolver = function resolver() {
61530 var instance = load(factory);
61531
61532 if (instance && typeof instance.transform === 'function') {
61533 throw new Error('Transforms cannot be attached to factory functions. ' + 'Please create a separate function for it with exports.path="expression.transform"');
61534 }
61535
61536 if (isTypedFunction(existing) && isTypedFunction(instance)) {
61537 if (options.override) {// replace the existing typed function (nothing to do)
61538 } else {
61539 // merge the existing and new typed function
61540 instance = typed(existing, instance);
61541 }
61542
61543 return instance;
61544 }
61545
61546 if (existing === undefined || options.override) {
61547 return instance;
61548 }
61549
61550 if (options.silent) {
61551 return existing;
61552 } else {
61553 throw new Error('Cannot import "' + name + '": already exists');
61554 }
61555 };
61556
61557 if (factory.lazy !== false) {
61558 Object(utils_object["h" /* lazy */])(namespace, name, resolver);
61559
61560 if (existingTransform) {
61561 _deleteTransform(name);
61562 } else {
61563 if (factory.path === 'expression.transform' || legacyFactoryAllowedInExpressions(factory)) {
61564 Object(utils_object["h" /* lazy */])(math.expression.mathWithTransform, name, resolver);
61565 }
61566 }
61567 } else {
61568 namespace[name] = resolver();
61569
61570 if (existingTransform) {
61571 _deleteTransform(name);
61572 } else {
61573 if (factory.path === 'expression.transform' || legacyFactoryAllowedInExpressions(factory)) {
61574 math.expression.mathWithTransform[name] = resolver();
61575 }
61576 }
61577 }
61578
61579 var key = factory.path ? factory.path + '.' + factory.name : factory.name;
61580 importedFactories[key] = factory;
61581 math.emit('import', name, resolver, factory.path);
61582 } else {
61583 // unnamed factory.
61584 // no lazy loading
61585 load(factory);
61586 }
61587 }
61588 /**
61589 * Import an instance of a factory into math.js
61590 * @param {function(scope: object)} factory
61591 * @param {Object} options See import for a description of the options
61592 * @param {string} [name=factory.name] Optional custom name
61593 * @private
61594 */
61595
61596
61597 function _importFactory(factory, options) {
61598 var name = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : factory.fn;
61599
61600 if (Object(array["b" /* contains */])(name, '.')) {
61601 throw new Error('Factory name should not contain a nested path. ' + 'Name: ' + JSON.stringify(name));
61602 }
61603
61604 var namespace = isTransformFunctionFactory(factory) ? math.expression.transform : math;
61605 var existingTransform = name in math.expression.transform;
61606 var existing = Object(utils_object["f" /* hasOwnProperty */])(namespace, name) ? namespace[name] : undefined;
61607
61608 var resolver = function resolver() {
61609 // collect all dependencies, handle finding both functions and classes and other special cases
61610 var dependencies = {};
61611 factory.dependencies.map(utils_factory["c" /* stripOptionalNotation */]).forEach(function (dependency) {
61612 if (Object(array["b" /* contains */])(dependency, '.')) {
61613 throw new Error('Factory dependency should not contain a nested path. ' + 'Name: ' + JSON.stringify(dependency));
61614 }
61615
61616 if (dependency === 'math') {
61617 dependencies.math = math;
61618 } else if (dependency === 'mathWithTransform') {
61619 dependencies.mathWithTransform = math.expression.mathWithTransform;
61620 } else if (dependency === 'classes') {
61621 // special case for json reviver
61622 dependencies.classes = math;
61623 } else {
61624 dependencies[dependency] = math[dependency];
61625 }
61626 });
61627 var instance =
61628 /* #__PURE__ */
61629 factory(dependencies);
61630
61631 if (instance && typeof instance.transform === 'function') {
61632 throw new Error('Transforms cannot be attached to factory functions. ' + 'Please create a separate function for it with exports.path="expression.transform"');
61633 }
61634
61635 if (existing === undefined || options.override) {
61636 return instance;
61637 }
61638
61639 if (isTypedFunction(existing) && isTypedFunction(instance)) {
61640 // merge the existing and new typed function
61641 return typed(existing, instance);
61642 }
61643
61644 if (options.silent) {
61645 // keep existing, ignore imported function
61646 return existing;
61647 } else {
61648 throw new Error('Cannot import "' + name + '": already exists');
61649 }
61650 }; // TODO: add unit test with non-lazy factory
61651
61652
61653 if (!factory.meta || factory.meta.lazy !== false) {
61654 Object(utils_object["h" /* lazy */])(namespace, name, resolver); // FIXME: remove the `if (existing &&` condition again. Can we make sure subset is loaded before subset.transform? (Name collision, and no dependencies between the two)
61655
61656 if (existing && existingTransform) {
61657 _deleteTransform(name);
61658 } else {
61659 if (isTransformFunctionFactory(factory) || factoryAllowedInExpressions(factory)) {
61660 Object(utils_object["h" /* lazy */])(math.expression.mathWithTransform, name, function () {
61661 return namespace[name];
61662 });
61663 }
61664 }
61665 } else {
61666 namespace[name] = resolver(); // FIXME: remove the `if (existing &&` condition again. Can we make sure subset is loaded before subset.transform? (Name collision, and no dependencies between the two)
61667
61668 if (existing && existingTransform) {
61669 _deleteTransform(name);
61670 } else {
61671 if (isTransformFunctionFactory(factory) || factoryAllowedInExpressions(factory)) {
61672 Object(utils_object["h" /* lazy */])(math.expression.mathWithTransform, name, function () {
61673 return namespace[name];
61674 });
61675 }
61676 }
61677 } // TODO: improve factories, store a list with imports instead which can be re-played
61678
61679
61680 importedFactories[name] = factory;
61681 math.emit('import', name, resolver);
61682 }
61683 /**
61684 * Check whether given object is a type which can be imported
61685 * @param {Function | number | string | boolean | null | Unit | Complex} object
61686 * @return {boolean}
61687 * @private
61688 */
61689
61690
61691 function isSupportedType(object) {
61692 return typeof object === 'function' || typeof object === 'number' || typeof object === 'string' || typeof object === 'boolean' || object === null || Object(is["L" /* isUnit */])(object) || Object(is["j" /* isComplex */])(object) || Object(is["e" /* isBigNumber */])(object) || Object(is["o" /* isFraction */])(object) || Object(is["v" /* isMatrix */])(object) || Array.isArray(object);
61693 }
61694 /**
61695 * Test whether a given thing is a typed-function
61696 * @param {*} fn
61697 * @return {boolean} Returns true when `fn` is a typed-function
61698 */
61699
61700
61701 function isTypedFunction(fn) {
61702 return typeof fn === 'function' && _typeof(fn.signatures) === 'object';
61703 }
61704
61705 function hasTypedFunctionSignature(fn) {
61706 return typeof fn === 'function' && typeof fn.signature === 'string';
61707 }
61708
61709 function allowedInExpressions(name) {
61710 return !Object(utils_object["f" /* hasOwnProperty */])(unsafe, name);
61711 }
61712
61713 function legacyFactoryAllowedInExpressions(factory) {
61714 return factory.path === undefined && !Object(utils_object["f" /* hasOwnProperty */])(unsafe, factory.name);
61715 }
61716
61717 function factoryAllowedInExpressions(factory) {
61718 return factory.fn.indexOf('.') === -1 && // FIXME: make checking on path redundant, check on meta data instead
61719 !Object(utils_object["f" /* hasOwnProperty */])(unsafe, factory.fn) && (!factory.meta || !factory.meta.isClass);
61720 }
61721
61722 function isTransformFunctionFactory(factory) {
61723 return factory !== undefined && factory.meta !== undefined && factory.meta.isTransformFunction === true || false;
61724 } // namespaces and functions not available in the parser for safety reasons
61725
61726
61727 var unsafe = {
61728 expression: true,
61729 type: true,
61730 docs: true,
61731 error: true,
61732 json: true,
61733 chain: true // chain method not supported. Note that there is a unit chain too.
61734
61735 };
61736 return mathImport;
61737}
61738// CONCATENATED MODULE: ./src/core/config.js
61739var DEFAULT_CONFIG = {
61740 // minimum relative difference between two compared values,
61741 // used by all comparison functions
61742 epsilon: 1e-12,
61743 // type of default matrix output. Choose 'matrix' (default) or 'array'
61744 matrix: 'Matrix',
61745 // type of default number output. Choose 'number' (default) 'BigNumber', or 'Fraction
61746 number: 'number',
61747 // number of significant digits in BigNumbers
61748 precision: 64,
61749 // predictable output type of functions. When true, output type depends only
61750 // on the input types. When false (default), output type can vary depending
61751 // on input values. For example `math.sqrt(-4)` returns `complex('2i')` when
61752 // predictable is false, and returns `NaN` when true.
61753 predictable: false,
61754 // random seed for seeded pseudo random number generation
61755 // null = randomly seed
61756 randomSeed: null
61757};
61758// CONCATENATED MODULE: ./src/core/function/config.js
61759
61760
61761var MATRIX_OPTIONS = ['Matrix', 'Array']; // valid values for option matrix
61762
61763var NUMBER_OPTIONS = ['number', 'BigNumber', 'Fraction']; // valid values for option number
61764
61765function configFactory(config, emit) {
61766 /**
61767 * Set configuration options for math.js, and get current options.
61768 * Will emit a 'config' event, with arguments (curr, prev, changes).
61769 *
61770 * This function is only available on a mathjs instance created using `create`.
61771 *
61772 * Syntax:
61773 *
61774 * math.config(config: Object): Object
61775 *
61776 * Examples:
61777 *
61778 *
61779 * import { create, all } from 'mathjs'
61780 *
61781 * // create a mathjs instance
61782 * const math = create(all)
61783 *
61784 * math.config().number // outputs 'number'
61785 * math.evaluate('0.4') // outputs number 0.4
61786 * math.config({number: 'Fraction'})
61787 * math.evaluate('0.4') // outputs Fraction 2/5
61788 *
61789 * @param {Object} [options] Available options:
61790 * {number} epsilon
61791 * Minimum relative difference between two
61792 * compared values, used by all comparison functions.
61793 * {string} matrix
61794 * A string 'Matrix' (default) or 'Array'.
61795 * {string} number
61796 * A string 'number' (default), 'BigNumber', or 'Fraction'
61797 * {number} precision
61798 * The number of significant digits for BigNumbers.
61799 * Not applicable for Numbers.
61800 * {string} parenthesis
61801 * How to display parentheses in LaTeX and string
61802 * output.
61803 * {string} randomSeed
61804 * Random seed for seeded pseudo random number generator.
61805 * Set to null to randomly seed.
61806 * @return {Object} Returns the current configuration
61807 */
61808 function _config(options) {
61809 if (options) {
61810 var prev = Object(utils_object["i" /* mapObject */])(config, utils_object["a" /* clone */]); // validate some of the options
61811
61812 validateOption(options, 'matrix', MATRIX_OPTIONS);
61813 validateOption(options, 'number', NUMBER_OPTIONS); // merge options
61814
61815 Object(utils_object["b" /* deepExtend */])(config, options);
61816 var curr = Object(utils_object["i" /* mapObject */])(config, utils_object["a" /* clone */]);
61817 var changes = Object(utils_object["i" /* mapObject */])(options, utils_object["a" /* clone */]); // emit 'config' event
61818
61819 emit('config', curr, prev, changes);
61820 return curr;
61821 } else {
61822 return Object(utils_object["i" /* mapObject */])(config, utils_object["a" /* clone */]);
61823 }
61824 } // attach the valid options to the function so they can be extended
61825
61826
61827 _config.MATRIX_OPTIONS = MATRIX_OPTIONS;
61828 _config.NUMBER_OPTIONS = NUMBER_OPTIONS; // attach the config properties as readonly properties to the config function
61829
61830 Object.keys(DEFAULT_CONFIG).forEach(function (key) {
61831 Object.defineProperty(_config, key, {
61832 get: function get() {
61833 return config[key];
61834 },
61835 enumerable: true,
61836 configurable: true
61837 });
61838 });
61839 return _config;
61840}
61841/**
61842 * Test whether an Array contains a specific item.
61843 * @param {Array.<string>} array
61844 * @param {string} item
61845 * @return {boolean}
61846 */
61847
61848function contains(array, item) {
61849 return array.indexOf(item) !== -1;
61850}
61851/**
61852 * Find a string in an array. Case insensitive search
61853 * @param {Array.<string>} array
61854 * @param {string} item
61855 * @return {number} Returns the index when found. Returns -1 when not found
61856 */
61857
61858
61859function findIndex(array, item) {
61860 return array.map(function (i) {
61861 return i.toLowerCase();
61862 }).indexOf(item.toLowerCase());
61863}
61864/**
61865 * Validate an option
61866 * @param {Object} options Object with options
61867 * @param {string} name Name of the option to validate
61868 * @param {Array.<string>} values Array with valid values for this option
61869 */
61870
61871
61872function validateOption(options, name, values) {
61873 if (options[name] !== undefined && !contains(values, options[name])) {
61874 var index = findIndex(values, options[name]);
61875
61876 if (index !== -1) {
61877 // right value, wrong casing
61878 // TODO: lower case values are deprecated since v3, remove this warning some day.
61879 console.warn('Warning: Wrong casing for configuration option "' + name + '", should be "' + values[index] + '" instead of "' + options[name] + '".');
61880 options[name] = values[index]; // change the option to the right casing
61881 } else {
61882 // unknown value
61883 console.warn('Warning: Unknown value "' + options[name] + '" for configuration option "' + name + '". Available options: ' + values.map(JSON.stringify).join(', ') + '.');
61884 }
61885 }
61886}
61887// EXTERNAL MODULE: ./src/error/DimensionError.js
61888var DimensionError = __webpack_require__(6);
61889
61890// EXTERNAL MODULE: ./src/error/IndexError.js
61891var IndexError = __webpack_require__(10);
61892
61893// CONCATENATED MODULE: ./src/core/create.js
61894/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "create", function() { return create; });
61895function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
61896
61897
61898
61899
61900
61901
61902
61903
61904
61905
61906
61907
61908
61909
61910/**
61911 * Create a mathjs instance from given factory functions and optionally config
61912 *
61913 * Usage:
61914 *
61915 * const mathjs1 = create({ createAdd, createMultiply, ...})
61916 * const config = { number: 'BigNumber' }
61917 * const mathjs2 = create(all, config)
61918 *
61919 * @param {Object} [factories] An object with factory functions
61920 * The object can contain nested objects,
61921 * all nested objects will be flattened.
61922 * @param {Object} [config] Available options:
61923 * {number} epsilon
61924 * Minimum relative difference between two
61925 * compared values, used by all comparison functions.
61926 * {string} matrix
61927 * A string 'Matrix' (default) or 'Array'.
61928 * {string} number
61929 * A string 'number' (default), 'BigNumber', or 'Fraction'
61930 * {number} precision
61931 * The number of significant digits for BigNumbers.
61932 * Not applicable for Numbers.
61933 * {boolean} predictable
61934 * Predictable output type of functions. When true,
61935 * output type depends only on the input types. When
61936 * false (default), output type can vary depending
61937 * on input values. For example `math.sqrt(-4)`
61938 * returns `complex('2i')` when predictable is false, and
61939 * returns `NaN` when true.
61940 * {string} randomSeed
61941 * Random seed for seeded pseudo random number generator.
61942 * Set to null to randomly seed.
61943 * @returns {Object} Returns a bare-bone math.js instance containing
61944 * functions:
61945 * - `import` to add new functions
61946 * - `config` to change configuration
61947 * - `on`, `off`, `once`, `emit` for events
61948 */
61949
61950function create(factories, config) {
61951 var configInternal = _extends({}, DEFAULT_CONFIG, config); // simple test for ES5 support
61952
61953
61954 if (typeof Object.create !== 'function') {
61955 throw new Error('ES5 not supported by this JavaScript engine. ' + 'Please load the es5-shim and es5-sham library for compatibility.');
61956 } // create the mathjs instance
61957
61958
61959 var math = mixin({
61960 // only here for backward compatibility for legacy factory functions
61961 isNumber: is["y" /* isNumber */],
61962 isComplex: is["j" /* isComplex */],
61963 isBigNumber: is["e" /* isBigNumber */],
61964 isFraction: is["o" /* isFraction */],
61965 isUnit: is["L" /* isUnit */],
61966 isString: is["I" /* isString */],
61967 isArray: is["b" /* isArray */],
61968 isMatrix: is["v" /* isMatrix */],
61969 isCollection: is["i" /* isCollection */],
61970 isDenseMatrix: is["n" /* isDenseMatrix */],
61971 isSparseMatrix: is["H" /* isSparseMatrix */],
61972 isRange: is["D" /* isRange */],
61973 isIndex: is["t" /* isIndex */],
61974 isBoolean: is["g" /* isBoolean */],
61975 isResultSet: is["G" /* isResultSet */],
61976 isHelp: is["s" /* isHelp */],
61977 isFunction: is["p" /* isFunction */],
61978 isDate: is["m" /* isDate */],
61979 isRegExp: is["F" /* isRegExp */],
61980 isObject: is["z" /* isObject */],
61981 isNull: is["x" /* isNull */],
61982 isUndefined: is["K" /* isUndefined */],
61983 isAccessorNode: is["a" /* isAccessorNode */],
61984 isArrayNode: is["c" /* isArrayNode */],
61985 isAssignmentNode: is["d" /* isAssignmentNode */],
61986 isBlockNode: is["f" /* isBlockNode */],
61987 isConditionalNode: is["k" /* isConditionalNode */],
61988 isConstantNode: is["l" /* isConstantNode */],
61989 isFunctionAssignmentNode: is["q" /* isFunctionAssignmentNode */],
61990 isFunctionNode: is["r" /* isFunctionNode */],
61991 isIndexNode: is["u" /* isIndexNode */],
61992 isNode: is["w" /* isNode */],
61993 isObjectNode: is["A" /* isObjectNode */],
61994 isOperatorNode: is["B" /* isOperatorNode */],
61995 isParenthesisNode: is["C" /* isParenthesisNode */],
61996 isRangeNode: is["E" /* isRangeNode */],
61997 isSymbolNode: is["J" /* isSymbolNode */],
61998 isChain: is["h" /* isChain */]
61999 }); // load config function and apply provided config
62000
62001 math.config = configFactory(configInternal, math.emit);
62002 math.expression = {
62003 transform: {},
62004 mathWithTransform: {
62005 config: math.config
62006 }
62007 }; // cached factories and instances used by function load
62008
62009 var legacyFactories = [];
62010 var legacyInstances = [];
62011 /**
62012 * Load a function or data type from a factory.
62013 * If the function or data type already exists, the existing instance is
62014 * returned.
62015 * @param {Function} factory
62016 * @returns {*}
62017 */
62018
62019 function load(factory) {
62020 if (Object(utils_factory["b" /* isFactory */])(factory)) {
62021 return factory(math);
62022 }
62023
62024 var firstProperty = factory[Object.keys(factory)[0]];
62025
62026 if (Object(utils_factory["b" /* isFactory */])(firstProperty)) {
62027 return firstProperty(math);
62028 }
62029
62030 if (!Object(utils_object["g" /* isLegacyFactory */])(factory)) {
62031 console.warn('Factory object with properties `type`, `name`, and `factory` expected', factory);
62032 throw new Error('Factory object with properties `type`, `name`, and `factory` expected');
62033 }
62034
62035 var index = legacyFactories.indexOf(factory);
62036 var instance;
62037
62038 if (index === -1) {
62039 // doesn't yet exist
62040 if (factory.math === true) {
62041 // pass with math namespace
62042 instance = factory.factory(math.type, configInternal, load, math.typed, math);
62043 } else {
62044 instance = factory.factory(math.type, configInternal, load, math.typed);
62045 } // append to the cache
62046
62047
62048 legacyFactories.push(factory);
62049 legacyInstances.push(instance);
62050 } else {
62051 // already existing function, return the cached instance
62052 instance = legacyInstances[index];
62053 }
62054
62055 return instance;
62056 }
62057
62058 var importedFactories = {}; // load the import function
62059
62060 function lazyTyped() {
62061 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
62062 args[_key] = arguments[_key];
62063 }
62064
62065 return math.typed.apply(math.typed, args);
62066 }
62067
62068 var internalImport = importFactory(lazyTyped, load, math, importedFactories);
62069 math["import"] = internalImport; // listen for changes in config, import all functions again when changed
62070 // TODO: move this listener into the import function?
62071
62072 math.on('config', function () {
62073 Object(utils_object["l" /* values */])(importedFactories).forEach(function (factory) {
62074 if (factory && factory.meta && factory.meta.recreateOnConfigChange) {
62075 // FIXME: only re-create when the current instance is the same as was initially created
62076 // FIXME: delete the functions/constants before importing them again?
62077 internalImport(factory, {
62078 override: true
62079 });
62080 }
62081 });
62082 }); // the create function exposed on the mathjs instance is bound to
62083 // the factory functions passed before
62084
62085 math.create = create.bind(null, factories); // export factory function
62086
62087 math.factory = utils_factory["a" /* factory */]; // import the factory functions like createAdd as an array instead of object,
62088 // else they will get a different naming (`createAdd` instead of `add`).
62089
62090 math["import"](Object(utils_object["l" /* values */])(Object(utils_object["c" /* deepFlatten */])(factories))); // TODO: deprecated since v6.0.0. Clean up some day
62091
62092 var movedNames = ['type.isNumber', 'type.isComplex', 'type.isBigNumber', 'type.isFraction', 'type.isUnit', 'type.isString', 'type.isArray', 'type.isMatrix', 'type.isDenseMatrix', 'type.isSparseMatrix', 'type.isCollection', 'type.isRange', 'type.isIndex', 'type.isBoolean', 'type.isResultSet', 'type.isHelp', 'type.isFunction', 'type.isDate', 'type.isRegExp', 'type.isObject', 'type.isNull', 'type.isUndefined', 'type.isAccessorNode', 'type.isArrayNode', 'type.isAssignmentNode', 'type.isBlockNode', 'type.isConditionalNode', 'type.isConstantNode', 'type.isFunctionAssignmentNode', 'type.isFunctionNode', 'type.isIndexNode', 'type.isNode', 'type.isObjectNode', 'type.isOperatorNode', 'type.isParenthesisNode', 'type.isRangeNode', 'type.isSymbolNode', 'type.isChain', 'type.BigNumber', 'type.Chain', 'type.Complex', 'type.Fraction', 'type.Matrix', 'type.DenseMatrix', 'type.SparseMatrix', 'type.Spa', 'type.FibonacciHeap', 'type.ImmutableDenseMatrix', 'type.Index', 'type.Range', 'type.ResultSet', 'type.Unit', 'type.Help', 'type.Parser', 'expression.parse', 'expression.Parser', 'expression.node.AccessorNode', 'expression.node.ArrayNode', 'expression.node.AssignmentNode', 'expression.node.BlockNode', 'expression.node.ConditionalNode', 'expression.node.ConstantNode', 'expression.node.IndexNode', 'expression.node.FunctionAssignmentNode', 'expression.node.FunctionNode', 'expression.node.Node', 'expression.node.ObjectNode', 'expression.node.OperatorNode', 'expression.node.ParenthesisNode', 'expression.node.RangeNode', 'expression.node.RelationalNode', 'expression.node.SymbolNode', 'json.reviver', 'error.ArgumentsError', 'error.DimensionError', 'error.IndexError'];
62093 movedNames.forEach(function (fullName) {
62094 var parts = fullName.split('.');
62095 var path = Object(array["j" /* initial */])(parts);
62096 var name = Object(array["l" /* last */])(parts);
62097 var obj = Object(utils_object["k" /* traverse */])(math, path);
62098 Object(utils_object["h" /* lazy */])(obj, name, function () {
62099 Object(log["a" /* warnOnce */])("math.".concat(fullName, " is moved to math.").concat(name, " in v6.0.0. ") + 'Please use the new location instead.');
62100 return math[name];
62101 });
62102 });
62103 Object(utils_object["h" /* lazy */])(math.expression, 'docs', function () {
62104 throw new Error('math.expression.docs has been moved. ' + 'Please import via "import { docs } from \'mathjs\'"');
62105 });
62106 math.ArgumentsError = ArgumentsError["a" /* ArgumentsError */];
62107 math.DimensionError = DimensionError["a" /* DimensionError */];
62108 math.IndexError = IndexError["a" /* IndexError */];
62109 return math;
62110}
62111
62112/***/ })
62113/******/ ]);
62114});
\No newline at end of file